简体   繁体   English

从图库意图中选择后,图像未显示在图像视图中

[英]image are not showing in image view after selecting from gallery intent

I'm trying to select images from the gallery and upload them to firebase storage but after selecting the image it doesn't show in the image view and the app get crash我正在尝试从图库中获取 select 图像并将它们上传到 firebase 存储,但是在选择图像后它没有显示在图像视图中并且应用程序崩溃

Note I'm using a fragment and not an activity注意我使用的是片段而不是活动

Here is the Error Message这是错误消息

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageURI(android.net.Uri)' on a null object reference Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageURI(android.net.Uri)' on a null object reference

Here is my MainActivity.xml这是我的 MainActivity.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:background="@color/black">

    <include
        android:id="@+id/tool_bar"
        layout="@layout/tool_bar" />

    <include
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        layout="@layout/fragment_container"
        android:layout_below="@+id/tool_bar"
        android:layout_above="@id/bottom_navigation_view" />

    <include
        android:id="@+id/bottom_navigation_view"
        layout="@layout/bottom_navigation_view" />


</RelativeLayout>

Here is my fragment_upload.XML file这是我的 fragment_upload.XML 文件

<?xml version="1.0" encoding="utf-8"?>
<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:background="@color/black">

    <ImageView
        android:id="@+id/upload_image_view"
        android:layout_width="match_parent"
        android:layout_height="600dp"
        app:layout_constraintBottom_toTopOf="@+id/done_button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />


    <Button
        android:id="@+id/done_button"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:backgroundTint="@color/grey"
        android:text="@string/done"
        android:textColor="@color/white"
        app:layout_constraintBottom_toTopOf="@+id/upload_image_button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <Button
        android:id="@+id/upload_image_button"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:backgroundTint="@color/grey"
        android:text="@string/upload"
        android:textColor="@color/white"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Here is MainActivity.java这是 MainActivity.java

public class MainActivity extends AppCompatActivity {
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation_view);
        bottomNavigationView.setOnNavigationItemSelectedListener(navigationItemSelectedListener);
        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                new Home_Fragment()).commit();
        Window window = this.getWindow();
        window.setStatusBarColor(this.getResources().getColor(R.color.black));



    }

    private final BottomNavigationView.OnNavigationItemSelectedListener navigationItemSelectedListener =
            item -> {
                Fragment selectedFragment = null;
                switch (item.getItemId()) {
                    case R.id.nav_home:
                        selectedFragment = new Home_Fragment();
                        break;
                    case R.id.nav_following:
                        selectedFragment = new Following_Fragment();
                        break;
                    case R.id.nav_upload:
                        selectedFragment = new Upload_Fragment();
                        break;
                    case R.id.nav_notification:
                        selectedFragment = new Notification_Fragment();
                        break;
                    case R.id.nav_profile:
                        selectedFragment = new Profile_Fragment();
                        break;
                }
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        selectedFragment).commit();
                return true;
            };
}

Here is Upload_Fragment.java这是 Upload_Fragment.java

 import android.app.ProgressDialog;
    import android.content.Intent;
    import android.net.Uri;
    import android.os.Bundle;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.Button;
    import android.widget.ImageView;
    
    import androidx.annotation.NonNull;
    import androidx.annotation.Nullable;
    import androidx.fragment.app.Fragment;
    
    import com.example.myappnotfinal.R;
    import com.google.android.gms.tasks.OnFailureListener;
    import com.google.android.gms.tasks.OnSuccessListener;
    import com.google.firebase.storage.FirebaseStorage;
    import com.google.firebase.storage.OnProgressListener;
    import com.google.firebase.storage.StorageReference;
    import com.google.firebase.storage.UploadTask;
    
    import java.util.UUID;
    
    import static android.app.Activity.RESULT_OK;
    
    public class Upload_Fragment extends Fragment {
        private static final int PICK_IMAGE_REQUEST = 1;
        private Button choseImageButton;
        private Button uploadImageButton;
        private ImageView uploadImageView;
        private Uri imageUri;
        private FirebaseStorage storage;
        private StorageReference storageReference;
    
        @Nullable
        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.fragment_upload, container, false);
            Button chooseImageButton = view.findViewById(R.id.upload_image_button);
            Button uploadImageButton = view.findViewById(R.id.done_button);
            uploadeImageView = view.findViewById(R.id.upload_image_view);
            storage = FirebaseStorage.getInstance();
            storageReference = storage.getReference();
            chooseImageButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    openFileChooser();
    
                }
            });
            uploadImageButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
    
                    uploadToFirebase();
    
    
                }
            });
    
            return view;
        }
    
        private void openFileChooser() {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(intent, PICK_IMAGE_REQUEST);
        }
    
        @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) {
                imageUri = data.getData();
                uploadImageView.setImageURI(imageUri);
            }
        }
    
        private void uploadToFirebase() {
            if (imageUri != null) {
                final ProgressDialog progressDialog = new ProgressDialog(getActivity());
                progressDialog.setTitle("Uploading...");
                progressDialog.show();
    
                StorageReference ref = storageReference.child("images/" + UUID.randomUUID().toString());
                ref.putFile(imageUri)
                        .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                            @Override
                            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                                progressDialog.dismiss();
                            }
                        })
                        .addOnFailureListener(new OnFailureListener() {
                            @Override
                            public void onFailure(@NonNull Exception e) {
                                progressDialog.dismiss();
                            }
                        })
                        .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                            @Override
                            public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                                double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot
                                        .getTotalByteCount());
                                progressDialog.setMessage("Uploaded " + (int) progress + "%");
                            }
                        });
            }
        }
    
    }

From what I can understand is that your image_view is null rather than your URI since you have already put a check for that, and after reading your code inside the onCreateView() method, there is this line据我了解,您的 image_view 是 null 而不是您的 URI,因为您已经对此进行了检查,并且在onCreateView()方法中阅读了您的代码后,有这一行

uploadeImageView = view.findViewById(R.id.upload_image_view);

This might just be a typo, there is an extra 'e' at the end while your top variable is这可能只是一个错字,最后有一个额外的 'e' 而你的 top 变量是

private ImageView uploadImageView;

and even later when you are setting it you are using following甚至稍后当你设置它时,你正在使用以下

uploadImageView.setImageURI(imageUri);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM