简体   繁体   中英

Image Doesn't show in Image view and shows following error

It takes me to the gallery to select the image but doesn't shown in the app and when clicked on upload button its just a blank image view

  1. My Java Code
package com.example.stdio9;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.android.gms.tasks.OnSuccessListener;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.single.PermissionListener;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

public class update_profile extends AppCompatActivity {

    ImageView uimage;
    EditText uname;
    Button btnupdate;

    DatabaseReference dbreference;
    StorageReference storageReference;

    Uri filepath;
    Bitmap bitmap;
    String UserId="";

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

        uimage=(ImageView)findViewById(R.id.uimage);
        uname=(EditText)findViewById(R.id.uname);
        btnupdate=(Button)findViewById(R.id.btnupdate);

        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
        UserId=user.getUid();
        dbreference = FirebaseDatabase.getInstance().getReference().child("userprofile");
        storageReference = FirebaseStorage.getInstance().getReference();

        uimage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Dexter.withContext(getApplicationContext())
                        .withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
                        .withListener(new PermissionListener() {
                            @Override
                            public void onPermissionGranted(PermissionGrantedResponse permissionGrantedResponse) {
                                Intent intent = new Intent();
                                intent.setType("image/*");
                                intent.setAction(Intent.ACTION_GET_CONTENT);
                                startActivityForResult(Intent.createChooser(intent,"Please select file"),101);

                            }

                            @Override
                            public void onPermissionDenied(PermissionDeniedResponse permissionDeniedResponse) {

                            }

                            @Override
                            public void onPermissionRationaleShouldBeShown(PermissionRequest permissionRequest, PermissionToken permissionToken) {
                                permissionToken.continuePermissionRequest();

                            }
                        }).check();

            }
        });

        btnupdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                updatetofirebase();

            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==101 &&requestCode==RESULT_OK)
        {
            filepath=data.getData();
            try
            {
                InputStream inputStream = getContentResolver().openInputStream(filepath);
                bitmap= BitmapFactory.decodeStream(inputStream);
                uimage.setImageBitmap(bitmap);
            }catch(Exception ex)
            {
                Toast.makeText(getApplicationContext(), ex.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }
    }

    public void updatetofirebase()
    {
        final ProgressDialog pd = new ProgressDialog(this);
        pd.setTitle("Uploading");
        pd.show();

        final StorageReference uploader =  storageReference.child("profileimages/"+"img"+System.currentTimeMillis());
        uploader.putFile(filepath)
                .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        uploader.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                            @Override
                            public void onSuccess(Uri uri) {
                                {
                                    final Map<String,Object> map = new HashMap<>();
                                    map.put("uimage",uri.toString());
                                    map.put("uname",uname.getText().toString());

                                    dbreference.child(UserId).addValueEventListener(new ValueEventListener() {
                                        @Override
                                        public void onDataChange(@NonNull DataSnapshot snapshot) {
                                            if(snapshot.exists())
                                                dbreference.child(UserId).updateChildren(map);
                                            else
                                                dbreference.child(UserId).setValue(map);
                                        }

                                        @Override
                                        public void onCancelled(@NonNull DatabaseError error) {

                                        }
                                    });

                                    pd.dismiss();
                                    Toast.makeText(getApplicationContext(), "Updated Successfully", Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                    }
                })
                .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onProgress(@NonNull UploadTask.TaskSnapshot snapshot) {
                        float percent = (100*snapshot.getBytesTransferred())/snapshot.getTotalByteCount();
                        pd.setMessage("Uploaded :"+(int)percent+"%");

                    }
                });
    }

    @Override
    protected void onStart() {
        super.onStart();

        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
        UserId=user.getUid();
        dbreference.child(UserId).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                if(snapshot.exists()){
                    uname.setText(snapshot.child("uname").getValue().toString());
                    Glide.with(getApplicationContext()).load(snapshot.child("uimage").getValue().toString()).into(uimage);
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        });
    }
}

  1. XML Code

<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat 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:orientation="vertical"
    tools:context=".update_profile">

    <ImageView
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:id="@+id/uimage"
        android:layout_marginTop="100dp"
        android:layout_gravity="center"
        android:src="@drawable/ic_person"/>

    <EditText
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:id="@+id/uname"
        android:textSize="20sp"
        android:layout_gravity="center"
        android:layout_marginTop="20dp"
        android:hint="Enter your name"/>
    
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Update"
        android:id="@+id/btnupdate"
        android:layout_gravity="center"
        android:textSize="25sp"
        android:layout_marginTop="20sp"
        android:padding="12dp"/>

</androidx.appcompat.widget.LinearLayoutCompat>

This error shows on running

java.lang.IllegalArgumentException: uri cannot be null

Lines giving error Following two places were showing the uri error


  public void onSuccess(Uri uri) {
                                {
                                    final Map<String,Object> map = new HashMap<>();
                                    map.put("uimage",uri.toString());
                                    map.put("uname",uname.getText().toString());

 Dexter.withContext(getApplicationContext())
                        .withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
                        .withListener(new PermissionListener() {
                            @Override
                            public void onPermissionGranted(PermissionGrantedResponse permissionGrantedResponse) {
                                Intent intent = new Intent();
                                intent.setType("image/*");
                                intent.setAction(Intent.ACTION_GET_CONTENT);
                                startActivityForResult(Intent.createChooser(intent,"Please select file"),101);

You just need to update your if statement like below.

if(requestCode == 101 && resultCode == RESULT_OK){
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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