android - 将图像从 fragment 传递到 Activity - 获取空对象

标签 android android-fragments bitmap null

我有一个捕获 4 张图像的 fragment,我想向它们传递一个 activity,但我一直得到 null 对象。我不知道该怎么办。

这是我的 fragment :

    public class RegFragFour extends Fragment {

    Uri imageCaptureUri;
    ImageView imgCbOne, imgCbTwo, imgCbThree, imgCbFour;
    Button btnCbChooseOne, btnCbChooseTwo, btnCbChooseThree, btnCbChooseFour, btnCbContinueToFour;
    static final int PICK_FROM_CAMERA = 1;
    static final int PICK_FROM_FILE = 2;
    int pressedButton = 0;
    String passedPathOne, passedPathTwo, passedPathThree, passedPathFour;
    onDataPassFour dataPasser;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.reg_four, container, false);

        imgCbOne = (ImageView) view.findViewById(R.id.imgOne);
        imgCbTwo = (ImageView) view.findViewById(R.id.imgTwo);
        imgCbThree = (ImageView) view.findViewById(R.id.imgThree);
        imgCbFour = (ImageView) view.findViewById(R.id.imgFour);
        btnCbChooseOne = (Button) view.findViewById(R.id.btnChooseOne);
        btnCbChooseTwo = (Button) view.findViewById(R.id.btnChooseTwo);
        btnCbChooseThree = (Button) view.findViewById(R.id.btnChooseThree);
        btnCbChooseFour = (Button) view.findViewById(R.id.btnChooseFour);
        btnCbContinueToFour = (Button) view.findViewById(R.id.btnContinueToFour);

        btnCbChooseTwo.setEnabled(false);
        btnCbChooseThree.setEnabled(false);
        btnCbChooseFour.setEnabled(false);

        final String[] items = new String[]{"From Camera", "From Phone Memory"};

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.select_dialog_item, items);
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("Select Image");
        builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (which == 0) {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    File file = new File(Environment.getExternalStorageDirectory(), "tmp_avatar" + String.valueOf(System.currentTimeMillis()) + ".jpg");
                    imageCaptureUri = Uri.fromFile(file);
                    try {
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageCaptureUri);
                        intent.putExtra("return data", true);
                        startActivityForResult(intent, PICK_FROM_CAMERA);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                    dialog.cancel();
                } else {
                    Intent intent = new Intent();
                    intent.setType("image/*");
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE);
                }
            }
        });
        final AlertDialog dialog = builder.create();

        btnCbChooseOne.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pressedButton = 1;
                dialog.show();
            }
        });
        btnCbChooseTwo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pressedButton = 2;
                dialog.show();
            }
        });
        btnCbChooseThree.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pressedButton = 3;
                dialog.show();
            }
        });
        btnCbChooseFour.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pressedButton = 4;
                dialog.show();
            }
        });
        btnCbContinueToFour.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent Login = new Intent(getActivity(), FakeWelcome.class);
                startActivity(Login);
            }
        });
        return view;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK)
            return;
        Bitmap bitmap = null;
        String path = "";
        if (requestCode == PICK_FROM_FILE) {
            imageCaptureUri = data.getData();
            path = getRealPathFromURI(imageCaptureUri);
            if (path == null)
                path = imageCaptureUri.getPath();
            if (path != null)
                bitmap = BitmapFactory.decodeFile(path);
        } else {
            path = imageCaptureUri.getPath();
            bitmap = BitmapFactory.decodeFile(path);
        }
        switch (pressedButton){
            case 1:
                imgCbOne.setImageBitmap(bitmap);
                btnCbChooseTwo.setEnabled(true);
                passedPathOne = imageCaptureUri.getPath();;
                break;
            case 2:
                imgCbTwo.setImageBitmap(bitmap);
                btnCbChooseThree.setEnabled(true);
                passedPathTwo = imageCaptureUri.getPath();;
                break;
            case 3:
                imgCbThree.setImageBitmap(bitmap);
                btnCbChooseFour.setEnabled(true);
                passedPathThree = imageCaptureUri.getPath();;
                break;
            case 4:
                imgCbFour.setImageBitmap(bitmap);
                passedPathFour = imageCaptureUri.getPath();;
                break;
        }
        dataPasser.dataInfoRegFour(passedPathOne, passedPathTwo, passedPathThree, passedPathFour);
    }

    public String getRealPathFromURI(Uri contentUri) {
        String res = null;
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = getActivity().getContentResolver().query(contentUri, proj, null, null, null);
        if (cursor.moveToFirst()) {
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            res = cursor.getString(column_index);
        }
        cursor.close();
        return res;
    }
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try {
            dataPasser = (onDataPassFour) context;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public interface onDataPassFour {
        void dataInfoRegFour(String imgPathOne, String imgPathTwo, String imgPathThree, String imgPathFour);
    }
}

这是我的 Activity :

    public class FakeWelcome extends AppCompatActivity implements RegFragFour.onDataPassFour {
    ImageView imgCbOne, imgCbTwo, imgCbThree, imgCbFour;
    Button btnCbChooseOne, btnChooseTwo, btnChooseThree, btnChooseFour;
    String _imgPathOne, _imgPathTwo, _imgPathThree, _imgPathFour;
    Bitmap bitmap = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fake_welcome);
        imgCbOne = (ImageView) findViewById(R.id.imgOne);
        imgCbTwo = (ImageView) findViewById(R.id.imgTwo);
        imgCbThree = (ImageView) findViewById(R.id.imgThree);
        imgCbFour = (ImageView) findViewById(R.id.imgFour);
        btnCbChooseOne = (Button) findViewById(R.id.btnChooseOne);
        btnChooseTwo = (Button) findViewById(R.id.btnChooseTwo);
        btnChooseThree = (Button) findViewById(R.id.btnChooseThree);
        btnChooseFour = (Button) findViewById(R.id.btnChooseFour);

        btnCbChooseOne.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bitmap = BitmapFactory.decodeFile(_imgPathOne);
                imgCbOne.setImageBitmap(bitmap);
            }
        });
        btnChooseTwo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bitmap = BitmapFactory.decodeFile(_imgPathTwo);
                imgCbTwo.setImageBitmap(bitmap);
            }
        });
        btnChooseThree.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bitmap = BitmapFactory.decodeFile(_imgPathThree);
                imgCbThree.setImageBitmap(bitmap);
            }
        });
        btnChooseFour.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bitmap = BitmapFactory.decodeFile(_imgPathFour);
                imgCbFour.setImageBitmap(bitmap);
            }
        });

    }

    @Override
    public void dataInfoRegFour(String imgPathOne, String imgPathTwo, String imgPathThree, String imgPathFour) {
        _imgPathOne = imgPathOne;
        _imgPathTwo = imgPathTwo;
        _imgPathThree = imgPathThree;
        _imgPathFour = imgPathFour;
    }
}

这是我的错误:

Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'void com.example.shaka.myparselogin.RegistrationFragments.RegFragFour$onDataPassFour.dataInfoRegFour(android.graphics.Bitmap, android.graphics.Bitmap, android.graphics.Bitmap, android.graphics.Bitmap)' on a null object reference
                                                   at com.example.shaka.myparselogin.RegistrationFragments.RegFragFour.onActivityResult(RegFragFour.java:168)
                                                   at android.support.v4.app.FragmentActivity.onActivityResult(FragmentActivity.java:156)

它指向这一行:

dataPasser.dataInfoRegFour(passedPathOne, passedPathTwo, passedPathThree, passedPathFour);

有什么想法吗?

最佳答案

很明显 dataPasser 对象是空的。在显示的代码 fragment 中,它仅在 FragmentsonAttach() 方法中被赋予一个值。因此,您可以在 onAttach() 中放置一个断点,调试您的应用程序并确认它实际上从未被调用过。

至于为什么没有调用它:您似乎正在使用某个版本的 AppCompat 库。有例如关于 StackOverflow 的这两个讨论涵盖了 onAttach() 方法签名已从 onAttach(Activity) 更改为 onAttach(Context) 的事实:

onAttach() not called in Fragment

Android Fragment onAttach() deprecated

所以问题可能在于您已经实现了将 Context 作为参数的那个,而您的 Activity 试图调用那个将 Activity 作为参数的 作为参数。

您可以查看例如这两个链接,您可能只需要相应地更改您的 onAttach() 方法签名。

代码更改:

来自...

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    try {
        dataPasser = (onDataPassFour) context;
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

...到...

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        dataPasser = (onDataPassFour) activity;
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

关于android - 将图像从 fragment 传递到 Activity - 获取空对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35839945/

相关文章:

c# - Diamond-Square 算法不产生 "smooth"噪声

php - 在 Android 中对字符串进行编码,以便 PHP 能够对其进行 gz 解压缩?

java - BottomSheet 在 styles.xml 中声明的 "android:background"上不透明

java - 无法在抽屉导航 fragment 中包含 RecyclerView

android - 滑动时 ViewPager 菜单图标延迟

java - 何时 "native pixel object"仍将在方法 nativeRecycle() 中的 native 级别使用?

java - 无法在 Marathon 应用程序中将 java.lang.String 类型的值转换为 double

android OneSignal 导入错误

android - 添加到 FragmentTransaction 的 addSharedElement api 如何工作?

java - 将位图设置为 TextView 的背景 - Android