1

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 + "%");
                            }
                        });
            }
        }
    
    }
  • i think [this](https://stackoverflow.com/questions/38352148/get-image-from-the-gallery-and-show-in-imageview) answer might help you. – danial iranpour Apr 03 '21 at 11:02
  • If you encounter problems, it's best to create a [MCVE](https://stackoverflow.com/help/mcve) when posting a question. You posted almost **300** lines of code for this issue. That's a lot for people to parse and try to debug online. Please edit your question and isolate the problem, in that way you increase your chances of being helped. – Alex Mamo Apr 04 '21 at 11:07

2 Answers2

1

In your onCreate you use

ImageView uploadedImageView ...

which means the global uploadedImageView is undefined and null hence the error you are getting. Inside onCreate remove ImageView and leave

uploadedImageView = view.findViewById(R.id.upload_image_view);
SABANTO
  • 1,316
  • 9
  • 24
0

You have a global variable "uploadImageView" which you are trying to use to attach your image to, however you don't define it in your onCreateView function, but rather you have created a new variable (which you didn't use) called "uploadedImageView", so you just need to swap this

ImageView uploadedImageView = view.findViewById(R.id.upload_image_view);

into:

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

and your code should work, (as now you pointed your variable into view).