Passing custom objects between activities?

前端 未结 5 1266
忘掉有多难
忘掉有多难 2020-12-03 17:43

How do I pass custom objects between activites in android? I\'m aware of bundles but I can\'t seem to see any functionality for this in them. Could anyone show me a nice exa

5条回答
  •  鱼传尺愫
    2020-12-03 18:27

    a Parcel MIGHT solve your problem.

    think of a Parcel as an "array" (metaphorical) of primitive types (long, String, Double, int, etc). if your custom class is composed of primitive types ONLY, then change your class declaration including implements Parcelable.

    you can pass a parcelable object thru an intent with no difficulty whatsoever (just like you would send a primitive-typed object). in this case i have a parcelable custom class called FarmData (composed of longs, strings and doubles) which i pass from one activity to another via intent.

        FarmData farmData = new FarmData();
    // code that populates farmData - etc etc etc
        Intent intent00 = new Intent(getApplicationContext(), com.example.yourpackage.yourclass.class);
        intent00.putExtra("farmData",farmData);
        startActivity(intent00);    
    

    but retrieving it may be tricky. the activity that receives the intent will check if a bundle of extras was send along with the intent.

        Bundle extras = getIntent().getExtras();
        FarmData farmData = new FarmData();
        Intent intentIncoming = getIntent();
        if(extras != null) {
            farmData = (FarmData) intentIncoming.getParcelableExtra("farmData");// OK
        }
    

提交回复
热议问题