Android; How can I initialise state in one activity, then have another refresh that?

隐身守侯 提交于 2019-12-29 08:10:12

问题


I have two activities

The first one gets some data from a content provider, and displays it

The second activity has a button, and when clicked it should call the first activity to "refresh", in other words to reload data from the content provider

This is my first activity

...
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
         setContentView(R.layout.contactsview);
            // Grab data and put it onto screen
                getDataAndPutToUI();
    }

    @Override
    public void onStart()
    {
       //Refresh data
           getDataAndPutToUI();
    }
...

And this is my second activity

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.optionsview);

        Button button = (Button) findViewById(R.id.intentButton);
            button.setOnClickListener(this);

    }   

    // This is bound to the "refresh" button
    @Override
    public void onClick(View v) {
        // Call first activity, to reload the contacts
        Intent i = new Intent(this, FirstActivity.class);
        startActivity(i);

    }

Is this the correct way to be implementing such functionality? It feels incorrect, but I can't determine any reasons to backup my claims


回答1:


It depends what behavior you are looking for. As you have currently implemented it, the first Activity will be refreshed any time that it is displayed to the user. For example, if the user pressed the home button from the first activity and later returned to the first activity via a long press on home, then the first activity would refresh it's data.

If that is what you want, then you're doing it right.

If you only want the first activity to refresh when you press the refresh button on the second activity, then you need to use your Intent to do that. One way would be to add a boolean extra to your Intent:

i.putExtra("reloadContent", true);

Then check for this extra in the onStart menthod.




回答2:


i u can do it by setting flags for your intent try like below,go through other flags

Intent i = new Intent();
                            i.setClass(this, Rss_Feed.class);
//                          i.setClass(Rss_Feed.this, Bru_Maps.class);
                            i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);


来源:https://stackoverflow.com/questions/3750776/android-how-can-i-initialise-state-in-one-activity-then-have-another-refresh-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!