1

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

主要活动:

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;

修改图像类:

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]);
    }
}

有谁知道我做错了什么?

4

2 回答 2

2

这段代码显然被破坏了:

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

如果你进入 if 语句的主体,你知道_imagesPath是 null - 但是你在循环中取消引用它,而没有为变量分配一个新值。在我看来,您只想克隆数组:

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

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

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

我怀疑你想为每个适当的值无条件地执行这行代码i- 为什么你只想_imagesPath在以前为空的情况下这样做?

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

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

于 2013-09-21T15:44:25.257 回答
1

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

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

如果 _imagesPath 为空,那么您在代码中对 _imagesPath 所做的每个操作都会引发NPE

只需添加一个不'!' 改变一切

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]);
    }
}
于 2013-09-21T15:44:14.943 回答