我有以下课程,我尝试获取上下文,以便将意图发送给其他活动。
public class CloudDocumentTextRecognitionProcessor
extends VisionProcessorBase<FirebaseVisionCloudText> {
public Context mContext;
private FirebaseVisionCloudDocumentTextDetector detector;
public CloudDocumentTextRecognitionProcessor() {
super();
detector = FirebaseVision.getInstance().getVisionCloudDocumentTextDetector();
}
public CloudDocumentTextRecognitionProcessor(Context context) {
this.mContext = context;
}
@Override
protected Task<FirebaseVisionCloudText> detectInImage(FirebaseVisionImage image) {
return detector.detectInImage(image);
}
@Override
protected void onSuccess(
@NonNull FirebaseVisionCloudText text,
@NonNull FrameMetadata frameMetadata,
@NonNull GraphicOverlay graphicOverlay) {
graphicOverlay.clear();
Intent i = new Intent(mContext, ResultActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("key", text.getText());
mContext.startActivity(i);
}
}
但是我在设置意图的那一行出现错误:
“试图在空对象引用上调用虚拟方法'java.lang.String android.content.Context.getPackageName()'”
我也尝试了MyApplication.getContext()而不是mContext,但是没有结果。
有什么想法吗?
答案 0 :(得分:2)
此类不继承任何具有Context的Android组件,因此您必须自己注入它。您必须使用将Context作为参数的构造函数实例化该类,然后将其从具有上下文/可访问应用上下文的Activity或其他Android组件中传入。
(伪代码)之类的东西
Class MyActivity
{
...
imageProcessor = new CloudDocumentTextRecognitionProcessor(this);
// or imageProcessor = new CloudDocumentTextRecognitionProcessor(this.getApplicationContext());
}
如何选择上下文?
CloudDocumentTextRecognitionProcessor
实例在您的应用的整个生命周期中都存在,请使用getApplicationContext()
; CloudDocumentTextRecognitionProcessor
实例仅在活动的生存期内存在,请使用this
。答案 1 :(得分:1)
You already have a setter for the mContext field and you can use the secondary constructor for the class that passes the context.
Initialize the class object from your activity like this:
CloudDocumentTextRecognitionProcessor imageProcessor = new CloudDocumentTextRecognitionProcessor(this);
or
CloudDocumentTextRecognitionProcessor imageProcessor = new CloudDocumentTextRecognitionProcessor(getApplicationContext());