0

我在 StackOverflow 上环顾四周,但找不到像我的问题一样的东西。我在多个问题上读到了一个类似的问题,但它们都是关于一个额外的意图。我的问题是关于从第二个活动传递回主要活动的意图中的一堆额外内容。

这是与主要活动相关的片段:

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);        
fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent intent = new Intent(getApplicationContext(), addItem.class);
            startActivityForResult(intent, 1);

        }
    });

和:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    System.out.println("REQUEST CODE:" + requestCode);
    super.onActivityResult(requestCode, resultCode, data);
    Bundle extras = data.getExtras();
    String item_name = extras.getString("ITEM_NAME");
    int item_price = extras.getInt("ITEM_PRICE");
    int item_qty = extras.getInt("ITEM_QTY");


    ListView list = (ListView) findViewById(R.id.listView);
    ArrayList<String> arrayList = new ArrayList<String>();
    ArrayAdapter<String> adapter;

    adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, arrayList);

    list.setAdapter(adapter);

    arrayList.add(item_name);
    adapter.notifyDataSetChanged();

}

第二个活动截图:

public class addItem extends AppCompatActivity{

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.add_item);

    Button btn1 = (Button)findViewById(R.id.button);

    btn1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            addToList();

        }
    });

}

public void addToList(){

    Intent inty = new Intent();
    Bundle extras = new Bundle();

    EditText txt1 = (EditText)findViewById(R.id.textItem);
    String name = txt1.getText().toString();
    extras.putString("ITEM_NAME", name);

    EditText txt2 = (EditText)findViewById(R.id.textPrice);
    int price = Integer.parseInt(txt2.getText().toString());
    extras.putInt("ITEM_PRICE", price);

    EditText txt3 = (EditText)findViewById(R.id.textNum);
    int numb = Integer.parseInt(txt3.getText().toString());
    extras.putInt("ITEM_QTY", numb);

    setResult(RESULT_OK, inty);
    finish();
}

}

更具体地说,当我按下按钮发送回数据(来自三个表单)时,应用程序崩溃并且 android studio 告诉我:

java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent {  }} to activity {it.cryosec.appname/it.cryosec.appname.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference

我有什么问题吗?

4

1 回答 1

1

您必须在第二个活动中将 bundle 设置为您的意图。 intent.setExtras (bundle)

于 2015-10-01T21:16:45.193 回答