简体   繁体   English

Android从非活动类问题调用cameraApp

[英]Android call cameraApp from non-activity class issue

Though I found several similar answered questions, I couldn't solve my problem: 虽然我找到了几个类似的回答问题,但我无法解决我的问题:

I use Fragment oFragment from where I want to call the Camera as a new Activity. 我使用Fragment oFragment从我想要将Camera称为新Activity。 Therefore I created a non-activity class Camera. 因此我创建了一个非活动类Camera。 When running I get the error: 运行时我收到错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.PackageManager android.app.Activity.getPackageManager()' on a null object reference

oFragment is placed in a FrameLayout in MainActivity . oFragment放置在MainActivity中的FrameLayout中。 I also tried the constructor of Camera with Context context . 我还尝试了Camera with Context context的构造函数。 Do you see any workarounds or mistakes? 你看到任何变通方法或错误吗? Thanks in advance! 提前致谢!

Edit: The code works fine if implemented directly into oFragment . 编辑:如果直接在oFragment实现,代码可以正常工作。

Class Camera: 班级相机:

public class Camera {
    static final int REQUEST_IMAGE_CAPTURE = 1;
    Activity activity;

    public Camera(Activity activity) {
        this.activity = activity;
    }

    public void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(activity.getPackageManager()) != null) {
            activity.startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
    }
}

Snipped from oFragment: 从oFragment剪掉:

public class OFragment extends Fragment {

    Camera cam = new Camera(getActivity());
    ...
    @Override
    public void onClick(View v) {
    cam.dispatchTakePictureIntent();
    }

I just solved it. 我刚刚解决了 I had to add the line super(); 我不得不添加行super(); to my constructer and it works fine! 我的建设者,它工作正常!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM