Skip to content
Advertisement

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

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

Here is my 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

<?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

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

 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 + "%");
                            }
                        });
            }
        }
    
    }

Advertisement

Answer

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

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

private ImageView uploadImageView;

and even later when you are setting it you are using following

uploadImageView.setImageURI(imageUri);
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement