1

我需要一些关于我的 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();
    }

}
4

2 回答 2

1

在您的第一个活动中,您的代码读取

data = getIntent();

但你想要的实际数据在

data.getData()
于 2013-01-17T22:49:27.213 回答
0

在 onActivityResult 函数中使用它..

data.getStringExtra(EXTRA_NAME)
于 2016-12-10T03:01:59.113 回答