传递给新Activity的数据为空

时间:2019-06-23 04:24:25

标签: java android android-studio

我在将数据传递到新活动时遇到问题。传递的数据不是 <DropdownItem onClick={()=> ChosenSize(id)} className="bg-info">{this.props.size}</DropdownItem> ,但是当从新活动中调用.getExtras()时,它不包含任何数据。当我调试时,新活动中的数据为null。这是我的实现方式-

FirstActivity.java

null

SecondActivity.java

Cursor cursor = databaseAccess.getData("SELECT * FROM TYPE");
    imageList.clear();
    while (cursor.moveToNext()) {
        String id = cursor.getString(0);
        String name = cursor.getString(1);
        byte[] image = cursor.getBlob(2);

        imageList.add(new Food(id, name, image));
    }
    adapter.notifyDataSetChanged();

    //button to click to next page
    gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
            view.setSelected(true);
            Food labels = imageList.get(position);
            String no = labels.getId();
            Intent passIntent = new Intent(FirstActivity.this, SecondActivity.class);
            passIntent.putExtra("keyid", no);//pass id to next activity
            startActivity(passIntent);

        }
    });

databaseAcces.java

//declaration for gridview and implement adapter
    gridView = (GridView) findViewById(R.id.gridView2);
    imageList = new ArrayList<>();
    adapter = new CustomGridAdapter1(this, R.layout.second_list, imageList);
    gridView.setAdapter(adapter);

    Bundle data = getIntent().getExtras();
    rowId = data.getString("keyid");
    cursor = databaseAccess.getImage(rowId);
    while (cursor.moveToNext()) {
        String id = cursor.getString(0);
        String name = cursor.getString(1);
        byte[] image = cursor.getBlob(2);

        imageList.add(new Recipe(id, name, image));
    }
    adapter.notifyDataSetChanged();
}

2 个答案:

答案 0 :(得分:0)

发生这种情况是因为您直接将数据放入了额外的数据,但是在接收时却想通过捆绑获得它!

替换

Bundle data = getIntent().getExtras();
rowId = data.getString("keyid");

 rowId = getIntent().getStringExtra("keyid");

答案 1 :(得分:0)

erfan的答案也是正确的,但将密钥和数据仅传递给其他活动不是很好的做法使用Bundle

Bundle的主要目的是在活动之间传递数据。将要传递的值映射到String键,以后在下一个活动中将其用于检索值。

Sending data between activities section of Android Developer site says:

  

我们建议您使用Bundle类来设置已知的   Intent对象上的OS。 Bundle类针对以下情况进行了高度优化   使用包裹进行编组和解组。

要解决此问题,请使用Bundle从调用活动中放入数据,并使用Bundle从被调用活动中获取数据。

因此替换

String no = labels.getId();
Intent passIntent = new Intent(FirstActivity.this, SecondActivity.class);
passIntent.putExtra("keyid", no);//pass id to next activity

使用

String no = labels.getId();
Bundle bundle = new Bundle();
bundle.putString("keyid", no);
Intent passIntent = new Intent(FirstActivity.this, SecondActivity.class);
passIntent.putExtras(bundle);//pass id to next activity

并保持第二个活动不变。