【问题标题】:bundle is null after setting into the intent activity设置到意图活动后,bundle 为空
【发布时间】:2021-12-25 02:03:41
【问题描述】:

我正在设置在活动之间遍历的意图。但是这里的包在设置意图后为空。这是我的代码,

NewCourseActivity.java
 AdapterView.OnItemSelectedListener mItemSelectedListener = new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            CourseSelected=parent.getSelectedItem().toString();
            switch (view.getId()) {
                case R.id.BESPINNER:
                    String becourse=parent.getSelectedItem().toString();
                    Intent intent = new Intent(NewCourseActivity.this,BEViewCourseActivity.class);
                    Bundle data1 = new Bundle();
                    data1.putString("course",becourse);
                    intent.putExtras(data1);
                    startActivity(intent);
                    break; } }

BEViewCourseActivity.java:
 CourseSelected=findViewById(R.id.courseSelected);


        Intent intent = getIntent();
        Bundle data = intent.getExtras();
        if(data != null){
            String selectedcourse = data.getString("course");
            CourseSelected.setText(selectedcourse);
        }
        else{
            CourseSelected.setText("Failed");
        }

【问题讨论】:

    标签: android nullpointerexception bundle


    【解决方案1】:

    将数据从一个活动传递到另一个活动:

    // updated becourse String
    String becourse = parent.getItemAtPosition(position).toString();
    Intent intent = new Intent(NewCourseActivity.this , BEViewCourseActivity.class);
    intent.putExtra ( "course" , becourse  );
    startActivity ( intent );
    

    然后接收传递过来的数据:

    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        String stringValue = extras.getString("course"); // string must be the same as the passed one
    }
    

    【讨论】:

    • 但是没有数据通过bundle,并且接收活动中的bundle extras带有空值
    • 在开始活动之前添加一个日志来检查字符串的值:Log.i( "MyActivity" , becourse );
    • 究竟什么是“becourse”?它应该返回什么?
    • 它返回spinner中的数据,然后遍历接收活动
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多