我想将某些数据从活动转移到之前的活动。我通过首先测试数据发送来简化它,所以我创建了一个包含2个活动的项目,MainActivity
和SecondActivity
,SecondActivity
有一个文本字段和一个按钮,{{1有一个文本视图。我查找了我的问题,我找到了很多说使用MainActivity
的东西,我发现了一些帮助我编写代码的示例。但是,它似乎不起作用。我试图打印出字符串值。代码和输出发布在下面。
MainActivity:
startActivityForResult
SecondActivity:
package com.example.activitytesting;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
private static final int REQUEST_CODE_TEST = 0;
private TextView txtView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtView = (TextView) findViewById(R.id.txtView);
Intent i = new Intent(MainActivity.this, SecondActivity.class);
startActivityForResult(i, REQUEST_CODE_TEST);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQUEST_CODE_TEST) {
if(resultCode == Activity.RESULT_OK) {
String txt = data.getStringExtra("txt");
System.out.println("from main activity: \"" + txt + "\"");
txtView.setText(txt);
}
}
}
}
现在我从LogCat得到了输出,它们是:
package com.example.activitytesting;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class SecondActivity extends Activity {
private String txtStr;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
EditText txt = (EditText) findViewById(R.id.txtField);
txtStr = txt.getText().toString().isEmpty() ? "empty text field" : txt.getText().toString();
Button finishBtn = (Button) findViewById(R.id.finishBtn);
finishBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent result = new Intent();
System.out.println("from second activity: \"" + txtStr + "\"");
result.putExtra("text", txtStr);
setResult(Activity.RESULT_OK, result);
finish();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.second, menu);
return true;
}
}
为什么我无法将数据从一个活动转移到另一个活动?
答案 0 :(得分:3)
您的资源包密钥不匹配
第二项活动正在使用
result.putExtra("text", txtStr);
但MainActivity使用
检索String txt = data.getStringExtra("txt");
两个活动都应使用相同的密钥 - 在两种情况下都使用“text”或“txt”