我的Android应用程序需要一些帮助。我有两个活动,首先用startActivityForResult()
开始第二个活动。当第二个关闭时,它会按原样发送意图,但是当我想从onActivityResult()
访问额外时,我得到一个null而不是我放入的。
我也尝试过使用bundle with
Bundle b = getIntent().getExtras();
b.getString(AddTable.EXTRA_NAME);
但是它导致了RuntimeException并导致失败。
这是我的代码:
public class RunnerApp extends Activity {
private ListView listView;
private static ArrayList<String> values = new ArrayList<String>();
private ArrayAdapter<String> adapter;
private Intent newTable;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_runner_app);
listView = (ListView) findViewById(R.id.mylist);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, values);
listView.setAdapter(adapter);
}
public void addTable(View v){
newTable = new Intent(this, AddTable.class);
startActivityForResult(newTable, 1);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1 && resultCode == Activity.RESULT_OK && data != null){
data = getIntent();
Log.d("add", "got intent");
String newName = data.getStringExtra(AddTable.EXTRA_NAME);
Log.d("add", "string " + newName); //always prints string null
values.add(newName);
Log.d("add", "added to list");
}
}
@Override
public void onResume(){
super.onResume();
setContentView(R.layout.activity_runner_app);
adapter.notifyDataSetChanged();
}
}
第二项活动由startActivityForResult()
public class AddTable extends Activity {
public final static String EXTRA_NAME = "com.example.runnerapp.NAME";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_table);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_add_table, menu);
return true;
}
public void addThisTable(View v) {
Intent addTable = new Intent(this, RunnerApp.class);
EditText editText = (EditText) findViewById(R.id.addTableField);
String name = editText.getText().toString();
addTable.putExtra(EXTRA_NAME, name);
Log.d("intenyt", name);
setResult(Activity.RESULT_OK, addTable);
this.finish();
}
}
答案 0 :(得分:1)
在您的第一个活动中,您的代码会显示
data = getIntent();
但您想要的实际数据是
data.getData()
答案 1 :(得分:0)
在onActivityResult函数中使用它。
data.getStringExtra(EXTRA_NAME)