首页 > 解决方案 > 无法在片段中显示图像

问题描述

我无法在片段中的图像视图内显示图像。我已授予所有存储权限。代码执行没有任何错误,但不显示图像。我做错了什么请帮忙。我在这里显示了整个代码。

公共类 PrescriptionUploadFragment 扩展 Fragment 实现 View.OnClickListener {

private static final int REQUEST_PERMISSION_CODE = 111;
private static final int PICK_IMAGE_REQUEST = 1;

private ExtendedFloatingActionButton eFabUpload, eFabChooseFile;
private EditText etDescriptionUpload;
private ImageView imgPrescriptionUploads;
private ProgressBar pbPrescriptionUpload;

private ChangeFragment changeFragment;
private InternetCheck internetCheck;

private FirebaseAuth mAuth;
private FirebaseUser mUser;
private DatabaseReference mDatabaseReference;
private StorageReference mStorageReference, ref;

private String UserID = "";
private Uri mImageUri;

private  String id;

public PrescriptionUploadFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mAuth = FirebaseAuth.getInstance();
    mUser = mAuth.getCurrentUser();

    UserID = mUser.getUid();

    mDatabaseReference = FirebaseDatabase.getInstance().getReference("Prescription").child(UserID);
    mStorageReference = FirebaseStorage.getInstance().getReference("Prescription").child(UserID);

    internetCheck = new InternetCheck(getActivity());
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_prescription_upload, container, false);
}

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    InitializeViews(view);
}

private void InitializeViews(View view) {
    eFabUpload = (ExtendedFloatingActionButton) view.findViewById(R.id.fabUploadPrescription);
    eFabUpload.setOnClickListener(this);

    eFabChooseFile = (ExtendedFloatingActionButton) view.findViewById(R.id.fabChooseFile);
    eFabChooseFile.setOnClickListener(this);

    etDescriptionUpload = (EditText) view.findViewById(R.id.etDescriptionUplaod);

    pbPrescriptionUpload = (ProgressBar) view.findViewById(R.id.pbPrescriptionUpload);

    imgPrescriptionUploads = (ImageView) view.findViewById(R.id.imgPrescriptionUploads);

}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    try {
        changeFragment = (ChangeFragment) context;
    } catch (ClassCastException e) {
        throw new ClassCastException(context.toString() + " must implement MyInterface");
    }
}

@Override
public void onDetach() {
    super.onDetach();
}

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.fabChooseFile:
            onClickChooseFile();
            break;

        case R.id.fabUploadPrescription:
            onClickUploadPrescription();
            break;
    }
}

private void onClickChooseFile() {
    if (CheckingPermissionIsEnabled()) {
        Intent intentCamera = new Intent();
        intentCamera.setType("image/*");
        intentCamera.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intentCamera, PICK_IMAGE_REQUEST);
    } else {
        RequestMultiplePermission();
    }
}

private void onClickUploadPrescription() {

    if (mImageUri != null && internetCheck.checkConnection()){

        id = mDatabaseReference.push().getKey();

        ref = mStorageReference.child(id).child(System.currentTimeMillis() +"." + getExtension(mImageUri) );

        ref.putFile(mImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                PrescriptionUpload prescriptionUpload = new PrescriptionUpload(id ,mImageUri ,
                        etDescriptionUpload.getText().toString().trim());

                mDatabaseReference.child(id).setValue(prescriptionUpload).addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {
                        changeFragment.changeFrag("PRESCRIPTION_MAIN_FRAGMENT");
                    }
                }).addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onProgress(@NonNull UploadTask.TaskSnapshot taskSnapshot) {
                double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
                pbPrescriptionUpload.setProgress((int) progress);
            }
        });
    } else {
        Toast.makeText(getActivity(), "Not an Image !", Toast.LENGTH_SHORT).show();
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
            && data != null && data.getData() != null) {

        mImageUri = data.getData();
        if (mImageUri != null){
            imgPrescriptionUploads.setImageURI(mImageUri);
        } else {
            Toast.makeText(getActivity(), "Image not selected !", Toast.LENGTH_SHORT).show();
        }
    }
}

private String getExtension(Uri uri) {
    ContentResolver cr = getActivity().getContentResolver();
    MimeTypeMap mime = MimeTypeMap.getSingleton();
    return mime.getExtensionFromMimeType(cr.getType(uri));
}

public boolean CheckingPermissionIsEnabled() {

    int FirstPermissionResult = ContextCompat.checkSelfPermission(getActivity().getApplicationContext(), INTERNET);
    int FifthPermissionResult = ContextCompat.checkSelfPermission(getActivity().getApplicationContext(), ACCESS_WIFI_STATE);
    int EighthPermissionResult = ContextCompat.checkSelfPermission(getActivity().getApplicationContext(), READ_EXTERNAL_STORAGE);
    int NinthPermissionResult = ContextCompat.checkSelfPermission(getActivity().getApplicationContext(), WRITE_EXTERNAL_STORAGE);

    return FirstPermissionResult == PackageManager.PERMISSION_GRANTED &&
            FifthPermissionResult == PackageManager.PERMISSION_GRANTED &&
            EighthPermissionResult == PackageManager.PERMISSION_GRANTED &&
            NinthPermissionResult == PackageManager.PERMISSION_GRANTED;
}

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

    switch (requestCode) {

        case REQUEST_PERMISSION_CODE:

            if (grantResults.length > 0) {

                boolean INTERNET = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                boolean ACCESS_WIFI_STATE = grantResults[1] == PackageManager.PERMISSION_GRANTED;
                boolean READ_EXTERNAL_STORAGE = grantResults[2] == PackageManager.PERMISSION_GRANTED;
                boolean WRITE_EXTERNAL_STORAGE = grantResults[3] == PackageManager.PERMISSION_GRANTED;


                if (INTERNET && ACCESS_WIFI_STATE && READ_EXTERNAL_STORAGE && WRITE_EXTERNAL_STORAGE) {

                    Toast.makeText(getActivity(), "Permission Granted", Toast.LENGTH_LONG).show();
                } else {

                    Toast.makeText(getActivity(), "Permission Denied", Toast.LENGTH_LONG).show();

                }
            }

            break;
    }
}

private void RequestMultiplePermission() {
    // Creating String Array with Permissions.
    ActivityCompat.requestPermissions(getActivity(), new String[]
            {
                    INTERNET,
                    ACCESS_WIFI_STATE,
                    READ_EXTERNAL_STORAGE,
                    WRITE_EXTERNAL_STORAGE
            }, REQUEST_PERMISSION_CODE);

}

}

和xml代码

<androidx.constraintlayout.widget.ConstraintLayout 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:theme="@style/Theme.MaterialComponents"
tools:context=".PrescriptionUploadFragment">

<ImageView
    android:id="@+id/imgPrescriptionUploads"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_marginStart="24dp"
    android:layout_marginTop="24dp"
    android:layout_marginEnd="24dp"
    android:layout_marginBottom="24dp"
    android:scaleType="centerCrop"
    app:layout_constraintBottom_toTopOf="@+id/DescriptionUpload"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<com.google.android.material.textfield.TextInputLayout
    android:id="@+id/DescriptionUpload"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginStart="24dp"
    android:layout_marginEnd="24dp"
    android:layout_marginBottom="16dp"
    android:gravity="center"
    app:layout_constraintBottom_toTopOf="@+id/pbPrescriptionUpload"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent">

    <EditText
        android:id="@+id/etDescriptionUplaod"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/et_description" />

</com.google.android.material.textfield.TextInputLayout>

<ProgressBar
    android:id="@+id/pbPrescriptionUpload"
    style="@style/Widget.MaterialProgressBar.ProgressBar.Horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginStart="24dp"
    android:layout_marginEnd="24dp"
    android:layout_marginBottom="16dp"
    android:indeterminate="true"
    app:layout_constraintBottom_toTopOf="@+id/linearLayout3"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent" />

<LinearLayout
    android:id="@+id/linearLayout3"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginStart="24dp"
    android:layout_marginEnd="24dp"
    android:layout_marginBottom="16dp"
    android:gravity="center"
    android:orientation="horizontal"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent">

    <com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton
        android:id="@+id/fabChooseFile"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="start"
        android:layout_marginEnd="20dp"
        android:background="@color/colorPrimaryDark"
        android:backgroundTint="@color/colorPrimaryDark"
        android:shadowColor="@color/colorPrimary"
        android:text="@string/fabChooseFile"
        android:textAlignment="center"
        android:textColor="@color/colorText"
        android:textColorLink="@color/colorPrimaryDark"
        app:rippleColor="@color/colorText"
        app:tint="@color/colorPrimaryDark" />

    <com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton
        android:id="@+id/fabUploadPrescription"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="20dp"
        android:background="@color/colorPrimaryDark"
        android:backgroundTint="@color/colorPrimaryDark"
        android:shadowColor="@color/colorPrimary"
        android:text="@string/fabUpload"
        android:textAlignment="center"
        android:textColor="@color/colorText"
        android:textColorLink="@color/colorPrimaryDark"
        app:rippleColor="@color/colorText"
        app:tint="@color/colorPrimaryDark" />

</LinearLayout>

enter code here

标签: androidfirebaseandroid-fragmentsandroid-imageview

解决方案


推荐阅读