当前位置: 首页 > 知识库问答 >
问题:

有没有办法删除此nullobject引用错误?我正在尝试从扫描仪活动打开底部对话框

邰胤
2023-03-14

>

 E/AndroidRuntime: FATAL EXCEPTION: main
     Process: com.example.swiftpass, PID: 16875
     java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
         at com.example.swiftpass.ScanPopUpDialog.setPrompt(ScanPopUpDialog.java:47)
         at com.example.swiftpass.ScanQrActivity$MyImageAnalyzer.readerBarcodeData(ScanQrActivity.java:170)
         at com.example.swiftpass.ScanQrActivity$MyImageAnalyzer.access$200(ScanQrActivity.java:109)
         at com.example.swiftpass.ScanQrActivity$MyImageAnalyzer$3.onSuccess(ScanQrActivity.java:142)
         at com.example.swiftpass.ScanQrActivity$MyImageAnalyzer$3.onSuccess(ScanQrActivity.java:138)
         at com.google.android.gms.tasks.zzn.run(com.google.android.gms:play-services-tasks@@17.2.0:4)
         at android.os.Handler.handleCallback(Handler.java:789)
         at android.os.Handler.dispatchMessage(Handler.java:98)
         at android.os.Looper.loop(Looper.java:164)
         at android.app.ActivityThread.main(ActivityThread.java:6944)
         at java.lang.reflect.Method.invoke(Native Method)
         at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)

XML代码:

 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout
     xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:orientation="vertical">

     <RelativeLayout
         android:layout_width="match_parent"
         android:layout_height="wrap_content">

         <ImageView
             android:id="@+id/img_close"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_marginStart="10dp"
             android:layout_marginTop="10dp"
             android:src="@drawable/ic_close">
         </ImageView>

         <TextView
             android:id="@+id/txt_type"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_centerHorizontal="true"
             android:layout_marginTop="6dp"
             android:text="@string/qr_type"
             android:fontFamily="@font/roboto_black"
             android:textSize="20dp">
         </TextView>

         <TextView
             android:id="@+id/txt_prompt"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_centerHorizontal="true"
             android:layout_marginTop="50dp"
             android:layout_marginBottom="10dp"
             android:text="@string/qr_prompt"
             android:fontFamily="@font/roboto_medium"
             android:textSize="18dp">
         </TextView>

     </RelativeLayout>

 </LinearLayout>

底部对话框java:

包装com.example.swiftpass;

导入android。操作系统。捆导入android。看法拉平机;导入android。看法看法导入android。看法视图组;导入android。小装置。图像视图;导入android。小装置。文本视图;导入androidx。注释。非空;导入androidx。注释。可为空;

导入com.google.Android布料底片。底部碎片;

公共类ScanPopDialog扩展了BottomSheetDialogFragment{

 //Declaration of Variables

 TextView type;
 TextView prompt;
 ImageView close;

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

     type = view.findViewById(R.id.txt_type);
     prompt = view.findViewById(R.id.txt_prompt);
     close = view.findViewById(R.id.img_close);
     close.setOnClickListener(this::OnClick);
     return view;
 }

 //This function will listen to button clicks and will call certain functions according to what is pressed by the user
 private void OnClick(View view) {
     switch(view.getId()){
         case R.id.img_close:
             dismiss();
             break;
         case R.id.txt_prompt:
             break;
     }
 }

 public void setPrompt(String type, String prompt){
     this.type.setText(type);
     this.prompt.setText(prompt);

     if (type == "TEXT"){
         this.prompt.setOnClickListener(this::OnClick);
     }
 }

}

扫描仪活动java:

包装com.example.swiftpass;

导入androidx。注释。非空;导入androidx。appcompat。应用程序。应用程序活动;导入androidx。照相机果心摄影师;导入androidx。照相机果心图像分析;导入androidx。照相机果心图像采集;导入androidx。照相机果心图像代理;导入androidx。照相机果心预览导入androidx。照相机生命周期。过程摄像机提供器;导入androidx。照相机看法预览视图;导入androidx。果心应用程序。活动公司;导入androidx。果心所容纳之物语境相容;导入androidx。碎片应用程序。碎片管理器;

导入android。显示导入android。注释。抑制皮棉;导入android。所容纳之物下午。包装经理;导入android。图样指向导入android。图样直肠;导入android。媒体形象导入android。操作系统。捆导入android。util。大小导入android。小装置。干杯

导入com.google.Androidgms。任务。OnCompleteListener;导入com.google.Androidgms。任务。失败的听众;导入com.google.Androidgms。任务。OnSuccessListener;导入com.google.Androidgms。任务。任务导入com.google.常见的util。同时发生的可听未来;导入com.google.mlkit。视力条形码。条形码;导入com.google.mlkit。视力条形码。条形码扫描仪;导入com.google.mlkit。视力条形码。条码扫描选项;导入com.google.mlkit。视力条形码。条码扫描;导入com.google.mlkit。视力常见的输入图像;

导入java.util.列表;导入java.util.concurrent.执行例外;导入java.util.concurrent.执行服务;导入java.util.concurrent.执行人;

公共类ScanQrActivity扩展了AppCompatActivity{

 //Declaration of Variables

 private ListenableFuture cameraProviderFuture;
 private ExecutorService cameraExecutor;
 private PreviewView previewView;
 private MyImageAnalyzer analyzer;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_scan_qr);

     //Assigning of widgets and Setting up of listeners
     initializeScan();


     cameraProviderFuture.addListener(new Runnable() {
         @Override
         public void run() {
             try {
                 if (ActivityCompat.checkSelfPermission(ScanQrActivity.this, Manifest.permission.CAMERA) != (PackageManager.PERMISSION_GRANTED)){
                     ActivityCompat.requestPermissions(ScanQrActivity.this, new String [] {Manifest.permission.CAMERA}, 101);
                 }else{
                     ProcessCameraProvider processCameraProvider = (ProcessCameraProvider) cameraProviderFuture.get();
                     bindPreview(processCameraProvider);
                 }
             }catch (ExecutionException e){
                 e.printStackTrace();
             }catch (InterruptedException e){
                 e.printStackTrace();
             }
         }
     }, ContextCompat.getMainExecutor(this));
 }

 @Override
 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
     if (requestCode == 101 && grantResults.length > 0){
         ProcessCameraProvider processCameraProvider = null;
         try {
             processCameraProvider = (ProcessCameraProvider) cameraProviderFuture.get();
         } catch (ExecutionException e) {
             e.printStackTrace();
         } catch (InterruptedException e) {
             e.printStackTrace();
         }
         bindPreview(processCameraProvider);
     }
 }

 private void bindPreview(ProcessCameraProvider processCameraProvider) {

     Preview preview = new Preview.Builder().build();
     CameraSelector cameraSelector = new CameraSelector.Builder().requireLensFacing(CameraSelector.LENS_FACING_BACK).build();
     preview.setSurfaceProvider(previewView.getSurfaceProvider());
     ImageCapture imageCapture = new ImageCapture.Builder().build();
     ImageAnalysis imageAnalysis = new ImageAnalysis.Builder()
             .setTargetResolution(new Size(1280, 720))
             .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
             .build();
     imageAnalysis.setAnalyzer(cameraExecutor, analyzer);
     processCameraProvider.unbindAll();
     processCameraProvider.bindToLifecycle(this,cameraSelector, preview, imageCapture, imageAnalysis);
 }

 public class MyImageAnalyzer implements ImageAnalysis.Analyzer{
     private FragmentManager fragmentManager;
     private ScanPopUpDialog bottomDialog;

     public MyImageAnalyzer(FragmentManager fragmentManager){
         this.fragmentManager = fragmentManager;
         bottomDialog = new ScanPopUpDialog();
     }

     @Override
     public void analyze(@NonNull ImageProxy imageProxy) {
          scanBarcode(imageProxy);
     }

     private void scanBarcode(ImageProxy imageProxy) {

         BarcodeScannerOptions options =
                 new BarcodeScannerOptions.Builder()
                         .setBarcodeFormats(
                                 Barcode.FORMAT_QR_CODE)
                         .build();

         @SuppressLint("UnsafeExperimentalUsageError") Image mediaImage = imageProxy.getImage();
         assert mediaImage != null;
         InputImage inputImage =
                 InputImage.fromMediaImage(mediaImage, imageProxy.getImageInfo().getRotationDegrees());

         BarcodeScanner scanner = BarcodeScanning.getClient(options);
         Task<List<Barcode>> result = scanner.process(inputImage)
                 .addOnSuccessListener(new OnSuccessListener<List<Barcode>>() {
                     @Override
                     public void onSuccess(List<Barcode> barcodes) {
                         // Task completed successfully
                         readerBarcodeData(barcodes);
                     }
                 })
                 .addOnFailureListener(new OnFailureListener() {
                     @Override
                     public void onFailure(@NonNull Exception e) {
                         // Task failed with an exception
                         // ...
                         e.printStackTrace();
                     }
                 })
                 .addOnCompleteListener(new OnCompleteListener<List<Barcode>>() {
                     @Override
                     public void onComplete(@NonNull Task<List<Barcode>> task) {
                         imageProxy.close();
                     }
                 });
     }

     private void readerBarcodeData(List<Barcode> barcodes) {
         for (Barcode barcode: barcodes) {
             Rect bounds = barcode.getBoundingBox();
             Point[] corners = barcode.getCornerPoints();

             String rawValue = barcode.getRawValue();
             int valueType = barcode.getValueType();
             switch (valueType){
                 case Barcode.TYPE_TEXT:
                     bottomDialog.setPrompt(rawValue, "CLICK TO CONFIRM");
                     break;
                 case Barcode.TYPE_CALENDAR_EVENT:
                     bottomDialog.setPrompt("Calendar Event", "Unsupported Type");
                     break;
                 case Barcode.TYPE_CONTACT_INFO:
                     bottomDialog.setPrompt("Contact Info", "Unsupported Type");
                     break;
                 case Barcode.TYPE_DRIVER_LICENSE:
                     bottomDialog.setPrompt("Driver's License", "Unsupported Type");
                     break;
                 case Barcode.TYPE_EMAIL:
                     bottomDialog.setPrompt("E-mail", "Unsupported Type");
                     break;
                 case Barcode.TYPE_GEO:
                     bottomDialog.setPrompt("Location", "Unsupported Type");
                     break;
                 case Barcode.TYPE_ISBN:
                     bottomDialog.setPrompt("Book Number", "Unsupported Type");
                     break;
                 case Barcode.TYPE_PHONE:
                     bottomDialog.setPrompt("Phone", "Unsupported Type");
                     break;
                 case Barcode.TYPE_PRODUCT:
                     bottomDialog.setPrompt("Product", "Unsupported Type");
                     break;
                 case Barcode.TYPE_SMS:
                     bottomDialog.setPrompt("SMS", "Unsupported Type");
                     break;
                 case Barcode.TYPE_URL:
                     bottomDialog.setPrompt("Link", "Unsupported Type");
                     break;
                 case Barcode.TYPE_WIFI:
                     bottomDialog.setPrompt("Wi-Fi", "Unsupported Type");
                     break;
                 default:
                     bottomDialog.setPrompt("Uknown", "Uknown Type");
             }
             if (!bottomDialog.isAdded()){
                 bottomDialog.show(fragmentManager, "");
             }
         }
     }
 }


 private void initializeScan() {
     previewView = findViewById(R.id.previewView);
     this.getWindow().setFlags(1024,1024);
     cameraExecutor = Executors.newSingleThreadExecutor();
     cameraProviderFuture = ProcessCameraProvider.getInstance(this);
     analyzer = new MyImageAnalyzer(getSupportFragmentManager());
 }

}

共有1个答案

柴彬
2023-03-14

我解决了它,代码如下:

package com.example.swiftpass;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.google.android.material.bottomsheet.BottomSheetDialogFragment;


public class ScanPopUpDialog extends BottomSheetDialogFragment {

    //Declaration of Variables

    TextView type;
    TextView prompt;
    ImageView close;
    String stringType;
    String stringPrompt;

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

        type = view.findViewById(R.id.txt_type);
        type.setText(getStringType());
        prompt = view.findViewById(R.id.txt_prompt);
        prompt.setText(getStringPrompt());
        if (stringPrompt == "CLICK TO CONFIRM"){
            prompt.setOnClickListener(this::OnClick);
        }
        close = view.findViewById(R.id.img_close);
        close.setOnClickListener(this::OnClick);
        return view;
    }

    //This function will listen to button clicks and will call certain functions according to what is pressed by the user
    private void OnClick(View view) {
        switch(view.getId()){
            case R.id.img_close:
                dismiss();
                break;
            case R.id.txt_prompt:
                break;
        }
    }

    public void setDialog(String type, String prompt){
        /**
         * This method is public because it is being called fron the scan qr activity
         * this will set the value for the objects stringType and stringPrompt
         * this does not return any value thus, the values will be accessed through
         * get method
         */
        stringType = type;
        stringPrompt = prompt;
    }

    /**
     *These methods are used to access the value set by the setDialog method
     *
     */
    private String getStringType(){
        return stringType;
    }

    private String getStringPrompt(){
        return stringPrompt;
    }
}
 类似资料:
  • 这个程序应该输出 但是如果我输入的大小是4,我只输入这些值,但是如果我写的大小是4。。。它不需要我提供4个参数,而是需要3个参数并打印('',1,2,3) 请帮帮忙

  • 我有一个扫描仪,它读入字符串作为坐标输入。我必须将这些字符串转换成整数,并将它们存储在坐标的Arraylist中,但我输入的最后一个值没有存储在Arraylist中。 我尝试在for-loop之外使用,但仍然没有变化。在存储和解析字符串时,我也尝试使用while循环而不是for循环,但得到了相同的结果。 预期结果: 点:[1,2,3,4] 实际结果 点:[1,2]

  • 问题内容: 我的PC上没有太多内存,处理器也很弱。尽管到目前为止,netbeans是我最喜欢的IDE,但在我现有的计算机上使用它几乎是难以忍受的,因为打开程序时,项目扫描会自动开始。 有没有办法防止Netbeans扫描项目? 问题答案: 嗨,乔治,我不知道这是否是答案,但是我右键单击并在不需要打开的项目上选择“关闭”。将您过去的所有项目都列出在那里是没有意义的。只需将您正在开发的那个打开。您始终可

  • 它在do while循环内的第三行崩溃,不等待我的输入: 堆栈跟踪: 线程“main”java中出现异常。util。非接触性异常 在爪哇。util。扫描仪。throwFor(未知来源) 在爪哇。util。扫描仪。下一个(未知源) java.util.canner.next国际(来源不明) java.util.canner.next国际(来源不明) 在主。river.main(river.java:

  • 下面是抛出异常的代码的简化版本。 线程“main”java.util出现异常。NoSuchElementException:在temp.temp.getString(temp.java:13)的java.util.Scanner.nextLine(Scanner.java:1540)中找不到行 我两次调用方法,在第二次调用时它会中断: 现在,我明白删除行可以解决问题(并且可能也使成为静态变量)。我

  • 对于作业,我必须编写以下代码: 当我尝试编译它时,它在命令提示符下给了我3个错误,说“无法解析符号,符号:类扫描仪,位置:类单词,扫描仪用户输入=新扫描仪(System.in)”。我不确定错误在哪里。我应该使用BufferedReader作为输入吗?