Error passing variables with Intent - NullPointerException

3

I am trying to pass a ArrayList<Pet> from a Fragment to my MainActivity.java for from here, if you press a ImageButton (from the action bar) we go to another activity in which I need the data of said ArrayList Well, I create a Intent in my class Fragment and% bundle to receive this data in my MainActivity and I get an exception NullPointerException when receiving this data.

Code of Intent of class Fragment

//Intent
Intent intent = new Intent(getContext(), MainActivity.class);
String [] nombre = new String [pets.size()];
int []numeroLikes = new int[pets.size()];
int []foto = new int [pets.size()];
for (int i = 0;i<pets.size();i++){
    nombre [i] = pets.get(i).getPetName();
    numeroLikes[i]=pets.get(i).getNumberOfLikes();
    foto[i] = pets.get(i).getFoto();
}
intent.putExtra(getString(R.string.nombre_mascota),nombre);
intent.putExtra(getString(R.string.numberOfLikes),numeroLikes);
intent.putExtra(getString(R.string.foto),foto);
startActivity(intent);

Code of Bundle to receive the data in MainActivity

//Bundle para inicializar pets
Bundle bundle = getIntent().getExtras();
String [] nombres = bundle.getStringArray(getString(R.string.nombre_mascota));
int [] nLikes = bundle.getIntArray(getString(R.string.numberOfLikes));
int [] foto  = bundle.getIntArray(getString(R.string.foto));
for (int i = 0; i<nombres.length;i++){
    pets.add(new Pet(nLikes[i],nombres[i],foto[i]));
}

At this point I miss the error, on the line:

String [] nombres = bundle.getStringArray(getString(R.string.nombre_mascota));

I do not know why I get a nullPointerException if all references are well placed. If it is a programming logic error, I would like you to comment on it as well.

I do not know if it will be important but I mention that my Fragment is composed of RecyclerView

The error is as follows:

08-26 09:19:07.807 8061-8061/es.uclm.mylittlepets E/AndroidRuntime: FATAL EXCEPTION: main
Process: es.uclm.mylittlepets, PID: 8061
java.lang.RuntimeException: Unable to start activity ComponentInfo{es.uclm.mylittlepets/es.uclm.mylittlepets.Layout.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String[] android.os.Bundle.getStringArray(java.lang.String)' on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String[] android.os.Bundle.getStringArray(java.lang.String)' on a null object reference
    at es.uclm.mylittlepets.Layout.MainActivity.onCreate(MainActivity.java:55)
    at android.app.Activity.performCreate(Activity.java:6237)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
    at android.app.ActivityThread.-wrap11(ActivityThread.java) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
    at android.os.Handler.dispatchMessage(Handler.java:102) 
    at android.os.Looper.loop(Looper.java:148) 
    at android.app.ActivityThread.main(ActivityThread.java:5417) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

EDIT 1: pets , the ArrayList, it does have data. Just before the Intent, I call the inicializarMascotas() method whose content is:

public void inicializarMascotas(){
    pets.add(new Pet(0,"Pet1",R.drawable.perro));
    pets.add(new Pet(0,"Pet2",R.drawable.burro));
    pets.add(new Pet(0,"Pet3", R.drawable.cangrejo));
    pets.add(new Pet(0,"Pet4",R.drawable.gallo));
    pets.add(new Pet(0,"Pet5",R.drawable.pulpo));
}

The constructor of class Pet receives: (int numeroLikes, String nombre_mascota, int foto)

EDIT 2:

A user told me that I should try implementing the interface Parcelable , and I have done so.

1.- In my POJO Pet , I have implemented Parcelable with its obligatory methods.

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel parcel, int i) {
    parcel.writeInt(numberOfLikes);
    parcel.writeInt(foto);
    parcel.writeString(petName);
}
public void readToParcel (Parcel parcel){
    numberOfLikes = parcel.readInt();
    foto = parcel.readInt();
    petName = parcel.readString();
}

I have also added a constructor in the following way:

public Pet (Parcel parcel){
    readToParcel(parcel);
}

Finally, this has also been overwritten:

 public static final Parcelable.Creator<Pet> CREATOR = new Parcelable.Creator<Pet>() {
    @Override
    public Pet createFromParcel(Parcel in) {
        return new Pet(in);
    }

    @Override
    public Pet[] newArray(int size) {
        return new Pet[size];
    }
};

2.- In my class Fragment of origin, the Intent is as follows:

Intent intent = new Intent(getActivity(),MainActivity.class);
    intent.putExtra("array",pets);
    startActivity(intent);

3.- In my class MainActivity I received the data like this:

pets = getIntent().getParcelableArrayListExtra("array");

If I try to do something like this:

Log.i("nombre", pets.get(0).getPetName());

The error you give me is exactly the same as above on this last line.

EDIT 3: With the user response @dddenis , the NullPointerException exception does not appear but it seems to enter an infinite loop in the that these lines are repeated in logcat :

  

08-29 10: 13: 50.414 14960-15004 / en.uclm.mylittlepets E / Surface: getSlotFromBufferLocked: unknown buffer: 0x9ece3960

     

08-29 10: 13: 50.439 14960-14960 / en.uclm.mylittlepets I / AppCompatViewInflater: app: theme is now deprecated. Please move to using android: theme instead.

     

08-29 10: 13: 50.509 14960-15004 / en.uclm.mylittlepets W / EGL_emulation: eglSurfaceAttrib not implemented

     

08-29 10: 13: 50.509 14960-15004 / en.uclm.mylittlepets W / OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x9e66c200, error = EGL_SUCCESS

     

08-29 10: 13: 50.532 14960-14960 / en.uclm.mylittlepets E / RecyclerView: No attached plugin; skipping layout

     

08-29 10: 13: 50.584 14960-14960 / en.uclm.mylittlepets E / RecyclerView: No adapter attached; skipping layout

     

08-29 10: 13: 50.612 14960-14960 / en.uclm.mylittlepets I / AppCompatViewInflater: app: theme is now deprecated. Please move to using android: theme instead.

    
asked by Iván García 26.08.2016 в 11:33
source

4 answers

0

I have finally managed to pass the data from Fragment to MainActivity . I have done it in the following way:

  

IN MY CLASS Fragment .

1.-I create an interface FragmentIterationListener that I will use to communicate with the Activity .

public interface FragmentIterationListener{
    public void onFragmentIteration(Bundle parameters);
} 

We create an attribute private FragmentIterationListener mcallback that we will use to pass data to Activity .

2.- In the onAttach(Activity activity) method we do the following:

try {
        mcallback = (FragmentIterationListener) activity;
    }catch(ClassCastException ex){
        Log.e("PetsFragment","El activity debe implementar la interfaz FragmentIterationListener");
    }

In this way we assign to our attribute the Activity with which it is going to communicate.

3.- In the onCreateView() method, besides inflating the Layout we instantiate our RecyclerView .

recyclerView = (RecyclerView) view.findViewById(R.id.rvPets);

4.- In the onViewCreated() method we set the RecyclerView as a LinearLayout , we initialize the ArrayList <Pet> pets and we pass it to the class MainActivity in the following way:

Bundle extras = new Bundle();
extras.putParcelableArrayList("EXTRA_PETS", pets);
mcallback.onFragmentIteration(extras);
  

IN MY CLASS MainActivity.java

1.- We implemented the interface that we have created previously:

public class MainActivity extends AppCompatActivity implements PetsFragment.FragmentIterationListener{

2.- We implemented the mandatory method of this interface:

public void onFragmentIteration(Bundle parameters) {
    pets = parameters.getParcelableArrayList("EXTRA_PETS");
}

3.- We receive the data in the following way (in the onCreate() method):

Bundle bundle = new Bundle();
onFragmentIteration(bundle);
    
answered by 30.08.2016 / 12:21
source
1

The error says that getString(R.string.nombre_mascota) == null therefore, when here intent.putExtra(getString(R.string.nombre_mascota),nombre); you spend nombre == null .

    
answered by 26.08.2016 в 12:42
1

In your code both the shipping

intent.putExtra(getString(R.string.nombre_mascota),nombre);

as the reception of the arrangement is correct:

Bundle bundle = getIntent().getExtras();
String [] nombres = bundle.getStringArray(getString(R.string.nombre_mascota));

This detail strikes me:

  

Caused by: java.lang.NullPointerException: Attempt to invoke virtual   method 'java.lang.String []   android.os.Bundle.getStringArray (java.lang.String) 'on a null object   reference

You are running the getStringArray() method of a bundle instance that has the value null.

Use getActivity() instead of getContext() to get the context of the Activity in the fragment and use it in your intent:

Intent intent = new Intent(getActivity(), MainActivity.class);
    
answered by 26.08.2016 в 20:04
1
  • Implement the Parcelable interface in Pet .

  • Prepare the Bundle with a ArrayList<Pet> with the putParcelableArrayList(key,value) method.

  • Receive ArrayList<Pet> with the getParcelableArrayList(key) method from Bundle .

  •   

    DATA TO SEND

    List<Pet> pets = new ArrayList<Pet>(){
        {
            add(new Pet(0,"Pet1",R.drawable.perro));
            add(new Pet(0,"Pet2",R.drawable.burro));
            add(new Pet(0,"Pet3", R.drawable.cangrejo));
            add(new Pet(0,"Pet4",R.drawable.gallo));
            add(new Pet(0,"Pet5",R.drawable.pulpo));
        }
    };
    
      

    PREPARING THE DATA

    Bundle extras = new Bundle();
    extras.putParcelableArrayList("EXTRA_PETS", (ArrayList<Pet>) pets);
    
      

    SENDING DATA

    Intent intent = new Intent(this, MainActivity.class).putExtras(extras);
    startActivity(intent);
    
      

    DATA RECEPTION

    List<Pet> petsReceived = getIntent().getParcelableArrayList("EXTRA_PETS");
    

    PD: It can also be done (and in many fewer steps), with the Serialization offered by Java, but it is not recommended for performance.

        
    answered by 29.08.2016 в 11:59