java - 在 Android 中的两个 Activity 之间传递字符串数组时出现 NullPointer

标签 java android arrays string android-intent

我正在尝试发送一个 array of Strings,它基本上包括设备上文件的路径。首先,用户选择图片 1,然后选择图片 2。一旦用户完成,数组就会被加载并传递给下一个 Activity 。当尝试接收变量时返回 NullPointer

主要 Activity :

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

谁知道我做错了什么?

最佳答案

这段代码显然是错误的:

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,但这是另一回事。)

关于java - 在 Android 中的两个 Activity 之间传递字符串数组时出现 NullPointer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18934467/

相关文章:

java - 如何在 Phonegap 中使用 AudioControl?

java - Activity 已泄露窗口 - Android

android - Genymotion 2.3.0 上的 Google Play 服务和 ARM 翻译

c - typedef 定长数组

Javascript 组合数组或字符串

java - Android 上的装箱和拆箱

java.lang.NoClassDefFoundError : org/hibernate/cfg/Configuration 错误

android - 启动模拟器和安卓设备时出错

android - 如何以编程方式为 AdMob 指定 adUnitId?

java - 泛型类实例的三种声明之间的区别