试图将数据从片段分类到活动?

时间:2015-10-31 19:34:48

标签: android android-fragments android-activity gson

我正在尝试将自定义类(Custom类是Juice)从片段传递到活动。我看到了一个答案here,但是当我试图将json字符串变回Juice对象时,它无效。这是我的代码,错误消息

片段

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);

活动

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());
    }

错误

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

1 个答案:

答案 0 :(得分:0)

您还可以使用Serializable的实现从片段到活动访问您的类对象。

public function show($id)
{
    $item = MenuItem::findOrFail($id)->with('variant')->get();
    return $item;
}

在SelectionActivity,您可以像...一样访问它。

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);