简体   繁体   中英

Getting the content of the Intent's Extra in new Activity

I send data from one Activity (actually a Fragment in my case) to a new Activity using an Intent . Here's the code I use:

Intent detailIntent = new Intent(getActivity(), NewActivity.class);
detailIntent.putExtra("News", n);
startActivity(detailIntent);

I know how to get the data in my NewActivity using

News news = (News) getIntent().getSerializableExtra("News");

and then populate the different UI components that I created in the XML.

but where should those lines of code be. There are multiple methods that it could possibly live in:

protected void onCreate(Bundle savedInstanceState)
public View onCreateView(String name, Context context, AttributeSet attrs)
public View onCreateView(View parent, String name, Context context, AttributeSet attrs)

由于它是您从上一个Activity收到的信息而且不会被修改,因此您应该从onCreate方法中读取它。

If you navigate back and forth between your Activities and the extra can change it is best to put the line

News news = (News) getIntent().getSerializableExtra("News");

in onResume , as onCreate will only be called on the first creation of the Activity, but not if it is on the stack and moved to the top later. If your second Activity is static and the extra never changes it is better to have the code in onCreate .

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