在Android中的两个活动之间传递String Array时的NullPointer

时间:2013-09-21 15:39:31

标签: java android arrays string android-intent

我正在尝试发送一个array of Strings,它基本上包含设备上文件的路径。首先是用户Selects Picture 1,然后是Select Picture 2。一旦用户完成该数组然后加载并传递给下一个活动。尝试接收变量时返回NullPointer

MainActivity:

case SELECT_PICTURE1:
    if (resultCode == RESULT_OK) {
        // code here that gets the image path
        // String leftImagePath contains the path of selected Image
        // Used toast to display the image path and it is not null
        finished = true;
    }
    break;

case SELECT_PICTURE2:
    if (resultCode == RESULT_OK) {
        //similar to Select Picture 1
        // String rightImagePath contains the path of selected Image
        if (finished == true) {
            Bundle b = new Bundle();
            b.putStringArray("stringArray", new String[] {
                LeftImageString, RightImageString });
            Intent i = new Intent(MainActivity.this, modifiedImage.class);
            i.putExtras(b);
            // finished = false;
        }
    }
    break;

ModifiedImage类:

Intent intent = getIntent();
_imagesPath = intent.getStringArrayExtra("IMAGES_PATH");
Bundle b= this.getIntent().getExtras();
_userImagePath = b.getStringArray("stringArray");


if (_imagesPath == null) {
    for (int i = 0; i <= 1; i++) {
         //null pointer on the following line because _userImagePath contains nothing.
        _imagesPath[i] = _userImagePath[i];
        _originalBitmaps[i] = BitmapFactory.decodeFile(_imagesPath[i]);
    }
}

有谁知道我做错了什么?

2 个答案:

答案 0 :(得分:2)

此代码明显被破坏:

if (_imagesPath == null) {
    for (int i = 0; i <= 1; i++) {
        _imagesPath[i] = _userImagePath[i];
        _originalBitmaps[i] = BitmapFactory.decodeFile(_imagesPath[i]);
    }
}

如果你进入if语句的主体,你知道 _imagesPath为空 - 然而你在循环中取消引用它,而没有为变量赋值。在我看来,你想要克隆数组:

if (_imagesPath == null) {
    _imagesPath = _userImagePath.clone();
}

...甚至只是复制参考:

if (_imagesPath == null) {
    _imagesPath = _userImagePath;
}

我怀疑您希望无条件地i的每个适当值执行此行代码 - 为什么您只想在_imagesPath先前已执行此操作时执行此操作空?

_originalBitmaps[i] = BitmapFactory.decodeFile(_imagesPath[i]);

(我不清楚你在哪里初始化_originalBitmaps,但这是另一回事。)

答案 1 :(得分:1)

你没有在Extra中传递任何IMAGES_PATH,那么为什么你期望目标活动中的值

  Intent intent = getIntent();
    _imagesPath = intent.getStringArrayExtra("IMAGES_PATH"); 
    Bundle b= this.getIntent().getExtras();
    _userImagePath = b.getStringArray("stringArray");

如果_imagesPath为null,那么你在代码中跟随的_imagesPath所做的每一次都会抛出 NPE

只需添加一个&#39;!&#39;改变一切

if (_imagesPath != null) {

    for (int i = 0; i <= 1; i++) {
         //null pointer on the following line because _userImagePath contains nothing.
        _imagesPath[i] = _userImagePath[i];
        _originalBitmaps[i] = BitmapFactory.decodeFile(_imagesPath[i]);
    }
}