Java 尝试在空对象引用上调用虚拟方法“android.content.res.Resources$Theme android.content.Context.getTheme()”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37304906/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Attempt to invoke virtual method 'android.content.res.Resources$Theme android.content.Context.getTheme()' on a null object reference
提问by Thormgrim
I want to run some OpenCv Filters over images inside of an Android App. I've hit an Error, of which I cant seem to find the origin.
我想在 Android 应用程序内的图像上运行一些 OpenCv 过滤器。我遇到了一个错误,我似乎无法找到它的起源。
Stacktrace:
堆栈跟踪:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources$Theme android.content.Context.getTheme()' on a null object reference
at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:222)
at android.app.AlertDialog$Builder.<init>(AlertDialog.java:452)
at org.opencv.android.BaseLoaderCallback.onPackageInstall(BaseLoaderCallback.java:90)
at org.opencv.android.AsyncServiceHelper.InstallService(AsyncServiceHelper.java:117)
at org.opencv.android.AsyncServiceHelper.initOpenCV(AsyncServiceHelper.java:33)
at org.opencv.android.OpenCVLoader.initAsync(OpenCVLoader.java:100)
at project.fragment.OpenCvTestFragment.onCreateView(OpenCvTestFragment.java:94)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:742)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
at android.support.v4.app.FragmentManagerImpl.run(FragmentManager.java:517)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
My Code: ( OpenCvTestFragment.java )
我的代码:( OpenCvTestFragment.java )
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.android.Utils;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Size;
import org.opencv.imgproc.Imgproc;
import org.opencv.imgcodecs.Imgcodecs;
import java.io.IOException;
import team_excellence.growup.R;
public class OpenCvTestFragment extends Fragment implements CameraBridgeViewBase.CvCameraViewListener2, View.OnTouchListener {
private OnOpenCvTestInteractionListener mListener;
private View view;
private ImageView imgView1;
private ImageView imgView2;
public OpenCvTestFragment() {
}
public static OpenCvTestFragment newInstance(String param1, String param2) {
OpenCvTestFragment fragment = new OpenCvTestFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
private static final String TAG = "OCVSample::Activity";
private BaseLoaderCallback mOpenCVCallBack = new BaseLoaderCallback(getActivity()) {
@Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS: {
Log.i(TAG, "OpenCV loaded successfully");
}
break;
default: {
super.onManagerConnected(status);
}
break;
}
}
};
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (container == null) {
return null;
}
view = inflater.inflate(R.layout.fragment_open_cv_test, container, false);
final ImageView imgView1 = (ImageView) view.findViewById(R.id.ocvImage1);
imgView1.setImageResource(R.drawable.img1);
ImageView imgView2 = (ImageView) view.findViewById(R.id.ocvImage2);
imgView1.setImageResource(R.drawable.img2);
final Button contoursButton = (Button) view.findViewById(R.id.contoursButton);
contoursButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
try {
applyContoursFilter("img1");
} catch (IOException e) {
e.printStackTrace();
}
}
});
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_8, getContext(),
mOpenCVCallBack);
return view;
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onOpenCvTestInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnOpenCvTestInteractionListener) {
mListener = (OnOpenCvTestInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnOpenCvTestInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
@Override
public void onCameraViewStarted(int width, int height) {
}
@Override
public void onCameraViewStopped() {
}
@Override
public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
return null;
}
@Override
public boolean onTouch(View v, MotionEvent event) {
return false;
}
public interface OnOpenCvTestInteractionListener {
void onOpenCvTestInteraction(Uri uri);
}
public void applyContoursFilter(String resName) throws IOException {
Mat matImg = convertImageToMat(resName);
Mat matResult = findContours(matImg);
Bitmap bm = Bitmap.createBitmap(matResult.cols(), matResult.rows(), Bitmap.Config.ARGB_8888);
Utils.matToBitmap(matResult, bm);
imgView1.setImageBitmap(bm);
}
private Mat convertImageToMat(String resName) throws IOException {
int drawableResourceId = this.getResources().getIdentifier(resName, "drawable", getActivity().getPackageName());
Mat img = Utils.loadResource(getContext() , drawableResourceId , Imgcodecs.CV_LOAD_IMAGE_COLOR);
return img;
}
private Mat findContours (Mat image){
Mat kernel = Imgproc.getStructuringElement(Imgproc.MORPH_ELLIPSE, new Size(19,19));
Mat closed = new Mat(); // closed will have type CV_32F
Imgproc.morphologyEx(image, closed, Imgproc.MORPH_CLOSE, kernel);
Core.divide(image, closed, closed, 1, CvType.CV_32F);
Core.normalize(closed, image, 0, 255, Core.NORM_MINMAX, CvType.CV_8U);
Imgproc.threshold(image, image, -1, 255, Imgproc.THRESH_BINARY_INV
+ Imgproc.THRESH_OTSU);
return closed;
}
}
For clarification when the corresponding Button is pressed, the "applyContoursFilter" Method is called, which then converts the image from drawables ( shown in imgView1 ), into a Mat object. After that the "findContours" Method is called and the Mat-object then converted back into bmp format and set into the imgView1 again.
为了在按下相应的按钮时进行澄清,调用“applyContoursFilter”方法,然后将图像从可绘制对象(显示在 imgView1 中)转换为 Mat 对象。之后,“findContours”方法被调用,Mat-object 然后被转换回 bmp 格式并再次设置到 imgView1 中。
Well that's how it should work. But the nullpointer error posted above gets thrown and I cant figure out where its coming from or how to fix it.
嗯,这就是它应该如何工作。但是上面发布的空指针错误被抛出,我无法弄清楚它来自哪里或如何修复它。
I'm relatively new to Android and would be grateful for your Help.
我对 Android 比较陌生,非常感谢您的帮助。
采纳答案by Thormgrim
I got it solved now, by initializing OpenCV in the MainActivity of my App and only calling it in the Fragments. I moved the BaseLoaderCallBack Code from the Fragment's OnCreateView , to the MainActivity's OnCreate. Seems to be working fine now.
我现在通过在我的应用程序的 MainActivity 中初始化 OpenCV 并仅在片段中调用它来解决它。我将 BaseLoaderCallBack 代码从 Fragment 的 OnCreateView 移到 MainActivity 的 OnCreate。现在似乎工作正常。
回答by Steve
Before I used GPSTracker.this in AlertDialog.So I got an exception 'android.content.res.Resources$Theme android.content.Context.getTheme()'
在我在 AlertDialog.So 中使用 GPSTracker.this 之前,我得到了一个异常 'android.content.res.Resources$Theme android.content.Context.getTheme()'
I solved this exception by adding context like this:
我通过添加这样的上下文解决了这个异常:
private final Context mContext;
public GPSTracker(Context context) {
this.mContext = context;
}
public void showSettingsAlert(String provider) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
...........
}