简体   繁体   中英

Getting null values when passing data from one activity to another in android

I am storing some data in static varibles in Activity1 and accessing in Activity3,and Activity 5. ie..
Activity1---> Activity2--->Activ3
.....................|
......................Activity4.-----> Activ5

This works fine if we close the application completely, from Activity1 (ie if the user is at Activ5 if he clicks back button then -->Activ4-->Activ2-->Activ1-->Exit)

But the user is exiting app at Activ3,4,5 by clicking Mobile exit button(Not the application exit), Now after few hrs the user is reopening application then , It(app) gets started from Activi3 or 4 or 5. (ie where ever app was closed).

Now, Since i am using some data(which i stored in static varibles in Activ1.)
I am getting null values. Why this is happining. How to avoid this types of errors.
I have used sharedpref to avoid this.Is this the only solution ?

You need to add onSaveInstanceState methods to your earlier activities, and check the bundle received by the onCreate methods. Check out the Activity Lifecycle for details.

Restore the state of activity when it is recreated, so that the values passed can be retrieved at a later time. eg for an integer that was passed through intent do as following: -

//this will save the value if an activity is killed in background.
@Override
    protected void onSaveInstanceState(Bundle outState) 
    {
        getIntent().putExtra("count", getIntent().getStringExtra("count"));
        super.onSaveInstanceState(outState);
    }

//In restore instance state, retrieve the stored values. The following work can also be done //in oncreate, as when an activity is killed in background, onCreate method is also called.

@Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) 
    {
        if(savedInstanceState == null)
            return;
        int count = getIntent().getIntExtra("count", 0);
        super.onRestoreInstanceState(savedInstanceState);
    }

You should not store values in static members, the activity context gets released, thus you losing your static values. The preferred way of passing values between activities is using Bundles along with the Intents.

您可以创建新类并扩展应用程序,并在其中存储所需的所有数据,它非常有用,但请记住,如果这样做,则必须在清单文件中添加应用程序名称

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM