【问题标题】:How to fetch image path file to one Activity to other Activity如何将图像路径文件获取到一个活动到另一个活动
【发布时间】:2021-10-12 01:34:52
【问题描述】:

我有一个应用程序,通过点击两边的照片来验证身份证,在点击身份证正面的图片后,用户在完成这些操作后移动到另一个活动以点击身份证的背面图片处理用户重定向到另一个活动,用户在不同的 ImageView 中看到文档的两侧,但我不知道如何获取或传递 用户可以在此 Activity 上查看其 ID 卡以进行确认的那些图像。

这是我的正面扫描活动

    public class Front_Scan extends AppCompatActivity {

    ActivityResultLauncher<Intent> activityResultLauncher;

    private static final int PERMISSION_CODE = 101;

    public String currentPhotoPath;

    Button frontImgCap;
    Button frontImgCapAgain;
    Button frontNext;

    ImageView frontImg;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_front_scan);
        frontImg = findViewById(R.id.Image_id_front);
        frontImgCap = findViewById(R.id.imgCapture_front);
        frontImgCap.setVisibility(VISIBLE);
        frontImgCapAgain = findViewById(R.id.Front_imgCapture_again);
        frontImgCapAgain.setVisibility(GONE);
        frontNext = findViewById(R.id.front_next);
        frontNext.setVisibility(INVISIBLE);

        activityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult()
                , new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult result) {
                        if (result.getResultCode() == RESULT_OK) {
                            File f = new File(currentPhotoPath);
                            frontImgCapAgain.setVisibility(VISIBLE);
                            frontImgCap.setVisibility(INVISIBLE);
                            frontNext.setVisibility(VISIBLE);
                            frontImg.setImageURI(Uri.fromFile(f));
                        }
                    }
                });

        frontImgCap.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //if system os is >= marshmallow, request runtime permission

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (checkSelfPermission(Manifest.permission.CAMERA) ==
                            PackageManager.PERMISSION_DENIED ||
                            checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) ==
                                    PackageManager.PERMISSION_DENIED) {
                        //permission not enable, request it
                        String[] permission = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
                        //show popup to request permissions
                        requestPermissions(permission, PERMISSION_CODE);
                    } else {
                        //permission already given
                        dispatchTakePictureIntent();
                    }
                } else {
                    //system os < marshmallow
                    dispatchTakePictureIntent();

                }

            }
        });

    }

    public void next(View view) {
        Intent myIntent = new Intent(Front_Scan.this, back_scan.class);
        Front_Scan.this.startActivity(myIntent);
        finish();
    }

    public void scanAgain(View view) {
        clearMyFiles();
        onCreateLayouts();
        frontImg.setImageDrawable(getResources().getDrawable(R.drawable.id_front));
    }

    void clearMyFiles() {
        File imgFile = new File(currentPhotoPath);
        if (imgFile != null) {
            imgFile.delete();
        }
    }

    public void onCreateLayouts() {
        frontImgCap.setVisibility(VISIBLE);

        frontImgCapAgain.setVisibility(GONE);

        frontNext.setVisibility(INVISIBLE);

    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        switch (requestCode) {

            case PERMISSION_CODE:
                if (grantResults.length > 0 && grantResults[0] ==
                        PackageManager.PERMISSION_GRANTED) {
                    dispatchTakePictureIntent();
                } else {
                    Toast.makeText(this, "permission denied...", Toast.LENGTH_SHORT).show();
                }
                return;

        }

    }

    private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "FRONT_ID_JPEG" + timeStamp;
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );

        // Save a file: path for use with ACTION_VIEW intents
        currentPhotoPath = image.getAbsolutePath();
        return image;
    }

    private void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Ensure that there's a camera activity to handle the intent
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            // Create the File where the photo should go
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException ex) {
                // Error occurred while creating the File
            }
            // Continue only if the File was successfully created
            if (photoFile != null) {
                Uri photoURI = FileProvider.getUriForFile(this,
                        "com.example.nyabaapplication.fileprovider",
                        photoFile);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                activityResultLauncher.launch(takePictureIntent);
            }
        }
    }

}

正面扫描 XML

   <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/background"
    android:orientation="vertical"
    android:padding="30dp"
    tools:context=".Front_Scan">


    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="16dp"
        android:gravity="center"
        android:text="Scan Front Side"
        android:textAlignment="center"
        android:textAllCaps="false"
        android:textColor="@color/yellow"
        android:textSize="28sp"
        android:textStyle="bold" />

    <com.google.android.material.card.MaterialCardView
        android:layout_width="match_parent"
        android:layout_height="250dp"
        android:layout_gravity="center"
        android:layout_marginTop="60dp"
        app:cardBackgroundColor="@color/background"
        app:cardCornerRadius="22dp"
        app:cardElevation="4dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center">


            <ImageView
                android:id="@+id/Image_id_front"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_gravity="center"
                android:scaleType="fitXY"
                android:src="@drawable/id_front" />


        </LinearLayout>

    </com.google.android.material.card.MaterialCardView>

    <android.widget.Button
        android:id="@+id/Front_imgCapture_again"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:background="@drawable/flag_transparent"
        android:text="Scan Again"
        android:onClick="scanAgain"
        android:layout_marginTop="8dp"
        android:textAllCaps="false"
        android:textColor="@color/yellow"
        android:textSize="17sp"
        android:visibility="gone" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="Position your document inside the frame. Make sure that all the data is clearly visible."
        android:textAlignment="center"
        android:textColor="@color/gray"
        android:textSize="16sp"/>

    <android.widget.Button
        android:id="@+id/imgCapture_front"
        android:layout_width="220dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="60dp"
        android:background="@drawable/button_style_ylo"
        android:text="Scan Now"
        android:textAllCaps="false"
        android:textColor="@color/white"
        android:textSize="19sp"
        android:textStyle="bold"
        android:visibility="visible"/>

    <android.widget.Button
        android:id="@+id/front_next"
        android:layout_width="220dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="-50dp"
        android:background="@drawable/button_style_ylo"
        android:text="Next Step"
        android:textAllCaps="false"
        android:textColor="@color/white"
        android:textSize="19sp"
        android:textStyle="bold"
        android:onClick="next"
        android:visibility="invisible"/>

</LinearLayout>

这是背面扫描活动

 public class back_scan extends AppCompatActivity {

    ActivityResultLauncher<Intent> activityResultLauncher1;

    private static final int PERMISSION_CODE = 101;

    public String currentPhotoPath1;

    Button backImgCap;

    Button backImgCapAgain;

    Button backNext;

    ImageView backImg;

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

        backImg = findViewById(R.id.Image_id_back);

        backImgCap = findViewById(R.id.imgCapture_back);
        backImgCap.setVisibility(VISIBLE);

        backImgCapAgain = findViewById(R.id.Back_imgCapture_again);
        backImgCapAgain.setVisibility(GONE);

        backNext = findViewById(R.id.back_next);
        backNext.setVisibility(INVISIBLE);

        activityResultLauncher1 = registerForActivityResult(new ActivityResultContracts.StartActivityForResult()
                , new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult result) {
                        if (result.getResultCode() == RESULT_OK) {
                            File f1 = new File(currentPhotoPath1);
                            backImgCapAgain.setVisibility(VISIBLE);
                            backImgCap.setVisibility(INVISIBLE);
                            backNext.setVisibility(VISIBLE);
                            backImg.setImageURI(Uri.fromFile(f1));
                        }
                    }
                });

        backImgCap.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //if system os is >= marshmallow, request runtime permission

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (checkSelfPermission(Manifest.permission.CAMERA) ==
                            PackageManager.PERMISSION_DENIED ||
                            checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) ==
                                    PackageManager.PERMISSION_DENIED) {
                        //permission not enable, request it
                        String[] permission = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
                        //show popup to request permissions
                        requestPermissions(permission, PERMISSION_CODE);
                    } else {
                        //permission already given
                        dispatchTakePictureIntent1();
                    }
                } else {
                    //system os < marshmallow
                    dispatchTakePictureIntent1();
                }
            }
        });
    }

    public void next1(View view) {
        Intent myIntent = new Intent(back_scan.this, scanned_copy.class);
        back_scan.this.startActivity(myIntent);
        finish();
    }

    public void scanAgainBack(View view) {
        clearMyFiles1();
        onCreateLayouts1();
        backImg.setImageDrawable(getResources().getDrawable(R.drawable.id_back));
    }

    void clearMyFiles1() {
        File imgFile1 = new File(currentPhotoPath1);
        if (imgFile1 != null) {
            imgFile1.delete();
        }
    }

    public void onCreateLayouts1() {
        backImgCap.setVisibility(VISIBLE);

        backImgCapAgain.setVisibility(GONE);

        backNext.setVisibility(INVISIBLE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        switch (requestCode) {

            case PERMISSION_CODE:
                if (grantResults.length > 0 && grantResults[0] ==
                        PackageManager.PERMISSION_GRANTED) {
                    dispatchTakePictureIntent1();
                } else {
                    Toast.makeText(this, "permission denied...", Toast.LENGTH_SHORT).show();
                }
                return;
        }
    }

    private File createImageFile1() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "BACK_ID_JPEG_" + timeStamp;
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );

        // Save a file: path for use with ACTION_VIEW intents
        currentPhotoPath1 = image.getAbsolutePath();
        return image;
    }


    private void dispatchTakePictureIntent1() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Ensure that there's a camera activity to handle the intent
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            // Create the File where the photo should go
            File photoFile = null;
            try {
                photoFile = createImageFile1();
            } catch (IOException ex) {
                // Error occurred while creating the File
            }
            // Continue only if the File was successfully created
            if (photoFile != null) {
                Uri photoURI = FileProvider.getUriForFile(this,
                        "com.example.nyabaapplication.fileprovider",
                        photoFile);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                activityResultLauncher1.launch(takePictureIntent);
            }
        }
    }
}

Back Scan XML 文件与前端 XML 几乎相同

这是同时显示身份证两面的活动

    public class scanned_copy extends AppCompatActivity {

    Button finishBtn;

    ImageView scanIDBack;

    ImageView scanIDFront;

    String storeFrontScan;
    String storeBackScan="BACK_ID_JPEG.jpg";

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

        readFrontImgFromFile();
        readBackImgFromFile();

        scanIDBack = findViewById(R.id.Scan_id_back);

        scanIDFront = findViewById(R.id.Scan_id_front);

        finishBtn = findViewById(R.id.ScanfinishBtn);
        finishBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(scanned_copy.this, WellDone.class);
                startActivity(intent);
                finish();
            }
        });


    }

    public void readFrontImgFromFile()
    {
        File imgFileFront = new  File(getExternalFilesDir(Environment.DIRECTORY_PICTURES)+storeFrontScan);
        if(imgFileFront.exists())
        {
            scanIDFront.setImageURI(Uri.fromFile(imgFileFront));

        }
    }

    public void readBackImgFromFile()
    {
        File imgFileBack = new  File(getExternalFilesDir(Environment.DIRECTORY_PICTURES)+storeBackScan);
        if(imgFileBack.exists())
        {
            scanIDBack.setImageURI(Uri.fromFile(imgFileBack));

        }
    }


}

此活动的 XML 文件

 <?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/background"
    android:scrollbars="none"
    tools:context=".scanned_copy">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">


        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="16dp"
            android:gravity="center"
            android:text="Scanned ID Card"
            android:textAlignment="center"
            android:textAllCaps="false"
            android:textColor="@color/yellow"
            android:textSize="28sp"
            android:textStyle="bold" />

        <ProgressBar
            android:id="@+id/progressBar4"
            style="?android:attr/progressBarStyleHorizontal"
            android:layout_width="174dp"
            android:layout_height="26dp"
            android:layout_gravity="center"
            android:layout_marginTop="16dp"
            android:progress="85"
            android:progressTint="@color/yellow" />


        <com.google.android.material.card.MaterialCardView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:layout_marginHorizontal="20dp"
            app:cardBackgroundColor="@color/primary_gray"
            app:cardCornerRadius="22dp"
            app:cardElevation="4dp">


            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="30dp"
                    android:padding="10dp"
                    android:text="Have a final check if all data is clearly visible and that it matches the information you have entered in previous steps."
                    android:textAlignment="center"
                    android:textColor="@color/gray"
                    android:textSize="16sp" />


                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:layout_gravity="center_horizontal"
                    android:text="Front Side"
                    android:textSize="26dp"
                    android:textStyle="bold"
                    android:textColor="@color/light_gray"
                    android:layout_marginTop="30dp"/>


                <com.google.android.material.card.MaterialCardView
                    android:layout_width="match_parent"
                    android:layout_height="250dp"
                    android:layout_gravity="center"
                    android:layout_marginTop="10dp"
                    android:layout_marginHorizontal="10dp"
                    app:cardBackgroundColor="@color/primary_gray"
                    app:cardCornerRadius="22dp">

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:layout_gravity="center">


                        <ImageView
                            android:id="@+id/Scan_id_front"
                            android:layout_width="match_parent"
                            android:layout_height="match_parent"
                            android:layout_gravity="center"
                            android:scaleType="fitXY"
                            android:src="@drawable/id_front" />


                    </LinearLayout>

                </com.google.android.material.card.MaterialCardView>

                  <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:layout_gravity="center_horizontal"
                    android:text="Back Side"
                    android:textSize="26dp"
                    android:textStyle="bold"
                    android:textColor="@color/light_gray"
                    android:layout_marginTop="30dp"/>


                <com.google.android.material.card.MaterialCardView
                    android:layout_width="match_parent"
                    android:layout_height="250dp"
                    android:layout_gravity="center"
                    android:layout_marginTop="10dp"
                    android:layout_marginBottom="10dp"
                    android:layout_marginHorizontal="10dp"
                    app:cardBackgroundColor="@color/primary_gray"
                    app:cardCornerRadius="22dp">

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:layout_gravity="center">


                        <ImageView
                            android:id="@+id/Scan_id_back"
                            android:layout_width="match_parent"
                            android:layout_height="match_parent"
                            android:layout_gravity="center"
                            android:scaleType="fitXY"
                            android:src="@drawable/id_back" />


                    </LinearLayout>

                </com.google.android.material.card.MaterialCardView>

            </LinearLayout>

        </com.google.android.material.card.MaterialCardView>

        <android.widget.Button
            android:id="@+id/ScanfinishBtn"
            android:layout_width="220dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:layout_marginBottom="40dp"
            android:background="@drawable/button_style_ylo"
            android:text="Finish Verification"
            android:textAllCaps="false"
            android:textColor="@color/white"
            android:layout_gravity="center_horizontal"
            android:textSize="19sp"
            android:textStyle="bold"/>

    </LinearLayout>


</ScrollView>

【问题讨论】:

  • 如何将这些图像保存在缓存中,然后您只需要传递 url。在用户确认步骤之后,我认为您需要将这些图像发送到服务器,对吗?只需将其保存在缓存中,然后稍后再获取。一切完成后记得清除它。
  • 实际我是这个领域的新手,您能否阐明如何将这些图像保存在缓存中并通过 URL 以及如何实现这一点
  • 这里我不会提供代码示例,但是您可以看到:stackoverflow.com/questions/23606202/… 用于保存图像,developer.android.com/reference/android/content/… 用于访问缓存目录。然后你将拥有像 /data/data/com.your.packagename/app_data/imageDir... 这样的 uri,然后你使用意图或任何你想要的东西将它传递给其他活动。在新活动中,您可以访问上述 uri 并获取图像。然后将其显示到您的视图中。
  • 如果您遇到问题,最好在发布问题时创建MCVE。您为此问题发布了近 700(七百)行行代码。人们需要解析和尝试在线调试的内容很多。请编辑您的问题并隔离问题,这样可以增加获得帮助的机会。

标签: java android firebase android-studio android-layout


【解决方案1】:

您有已保存文件的路径。将它们作为意图附加内容传递到最后一个活动。

https://developer.android.com/training/basics/firstapp/starting-activity

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-05
    相关资源
    最近更新 更多