0

I am trying to pass a custom class (Custom class is Juice), from a fragment to an activity. I saw an answer here but it is not working when i am trying to turn the json string back into a Juice object. Here is my code with the error message

Fragment

Intent intent = new Intent(getActivity().getBaseContext(), SelectionActivity.class);
            Bundle bundle = new Bundle();
            Gson gson = new Gson();
            String json = gson.toJson(juices.get(position));
            Log.e("tree",json);
            intent.putExtra("position",json);
            getActivity().startActivity(intent);

Activity

Gson gson = new Gson();
    Intent intent = getIntent();
    if (getIntent().getStringExtra("position")!=null) {
        String position = getIntent().getStringExtra("position");
        Juice juice =gson.fromJson(position, Juice.class);
        TextView textTitle = (TextView) findViewById(R.id.selectedTitle);
        textTitle.setText(juice.getName());
        ImageView imageView = (ImageView) findViewById(R.id.selected);
        imageView.setImageResource((int) juice.getDrawable());

        TextView textDescription = (TextView) findViewById(R.id.selectedDescription);
        textDescription.setText(juice.getDescription());
    }

Error

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.intellidev.******/com.intellidev.*****.SelectionActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.intellidev.******.Juice.getDescription()' on a null object reference
Community
  • 1
  • 1
Intelli Dev
  • 156
  • 3
  • 15

1 Answers1

0

You can also access your class object from fragment to activity using implementation of Serializable.

class Juice implements Serializable{
    private static final long serialVersionUID = 2310640779687082782L;
    private String id;
    private String name;

    public String getId(){
        return this.id;
    }

    public String setId(String id){
        this.id = id;
    }

    public String getName(){
        return this.name;
    }

    public String setName(String name){
        this.name = name;
    }
}

Intent mIntent = new Intent(this,SelectionActivity.class);  
Bundle mBundle = new Bundle();  
mBundle.putSerializable(SER_KEY,juice);  
mIntent.putExtras(mBundle); 

where at SelectionActivity you can access it like...

Juice juice = (Juice)getIntent().getExtra().getSerializable(SER_KEY);
Android Leo
  • 666
  • 1
  • 8
  • 24