[英]How to get data from 2nd Activity to 1st Activity
我的MainActivity正在調用第二個包含列表視圖的活動PopupWindow。 當用戶單擊列表視圖時,我需要將該信息返回到第一個活動(MainActivity)。 因此在MainActivity中,我有這兩種方法。 第一個方法調用第二個活動,第二個從第二個活動獲取結果
//event listener for authors list menu (popup window)
authorListImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent popupWinIntent = new Intent(getBaseContext(), AuthorsPopup.class);
popupWinIntent.putExtra("allauthors", allAuthors);
startActivity(popupWinIntent);
}
});
//fetching result -- author from AuthorsPopup activity back
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if(resultCode == RESULT_OK) {
String author = data.getStringExtra("author");
Log.v("author ", author);
}
}
}
此方法在onCreate()方法之外。 一些教程建議創建avobe方法,就像onActivityResul()一樣,我假設這種情況將在onCreate()方法內部。 我的是一個方法聲明。 如此執着地不執行。 在我的第二項活動中。 我有這個
//event listener for authros listview
authorListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> paren, View view, int position, long id) {
// Log.v("author: ", authorsList[position]);
String author = authorsList[position];
Intent returnResultIntent = new Intent(getBaseContext(), MainActivity.class);
returnResultIntent.putExtra("author", author);
setResult(RESULT_OK, returnResultIntent);
finish();
}
});
從第二個活動中取回數據的正確方法是什么?
您需要使用startActivityForResult(popupWinIntent,1)
而不是startActivity(popupWinIntent)
啟動第二個活動startActivityForResult(popupWinIntent,1)
並在第一個Activity中覆蓋onActivityResult
方法,如下所示:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == Activity.RESULT_OK){
String result=data.getStringExtra("author");
}
}
}
您列出的第一個authorListImageView.setOnClickListener
代碼將放在onCreate
第一次活動如何獲得價值
SharedPreferences sharedPreferences;
sharedPreferences = getSharedPreferences(“ FileName”,0);
sharedPreferences.getString(“ KEY”,“ DefaultValue”); sharedPreferences.getBoolean(“ KEY”,false);
第二活動如何設置活動的價值或進行其他活動的價值
SharedPreferences sharedPreferences; SharedPreferences.Editor編輯器;
sharedPreferences = getSharedPreferences(“ FileName”,0); editor = sharedPreferences.edit();
editor.putString("KEY","Value");
editor.putBoolean("KEY",true);
editor.apply();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.