Thomas Dupont
Thomas Dupont

Reputation: 427

java code doesn't work in fragment activity

I try to create an application in android platform with 3 fragments

When I try to input some java code inside the fragment class, i have always this error: java.lang.NullPointerException

For example, with a simple button to change view:

package com.test;



import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;

public class creation extends Fragment {


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

         View root = inflater.inflate(R.layout.creation, container, false);

        final Button ok = (Button)getView(). findViewById(R.id.button3);
        ok.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // Create new fragment and transaction
                Fragment newFragment = new mesvideos();
                // consider using Java coding conventions (upper char class names!!!)
                FragmentTransaction transaction = getFragmentManager().beginTransaction();

                // Replace whatever is in the fragment_container view with this fragment,
                // and add the transaction to the back stack
                transaction.replace(R.layout.creation, newFragment);
                transaction.addToBackStack(null);

                // Commit the transaction
                transaction.commit(); 


        }
    });
return root ;
}

Or with a VideoView :

mVideoView = (VideoView) findViewById(R.id.videoView1);
             mVideoView.setVideoURI(Uri.parse("android.resource://" + getPackageName() +
                        "/" + R.raw.presentation));
             mVideoView.setMediaController(new MediaController(this));
             mVideoView.requestFocus();

Upvotes: 0

Views: 340

Answers (1)

Tobias
Tobias

Reputation: 1157

Rather than just saying that you encounter NullPointerException, please specify the full stacktrace or tell us on which line of your code the NPE occurs.

FWIW, your

final Button ok = (Button)getView(). findViewById(R.id.button3);

should probably be

final Button ok = (Button) root.findViewById(R.id.button3);

I suspect since you have only just created the root view and haven't returned/set it yet, getView() will return null

PS. Your class name "creation" is nonstandard. Java class names should start with a capital letter, and if your class extends Fragment then it's customary to let the class name end with "Fragment". E.g.: "CreationFragment".

Upvotes: 3

Related Questions