传回捆绑到mainactivity具有null附加功能

时间:2015-10-01 21:07:22

标签: android android-intent onactivityresult android-bundle

我在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

我弄错了什么?

1 个答案:

答案 0 :(得分:1)

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