繁体   English   中英

java.lang.IllegalArgumentException: uri 不能是 null

[英]java.lang.IllegalArgumentException: uri cannot be null

上传图像并将数据存储到 Firebase 时出现错误。我正在使用Bitmap来显示图像。 提交数据后,应用程序崩溃并返回到之前的Activity 此外,当我从设备中选取图像时,它没有显示在ImageView中。

我的错误:

D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.bloodsavelife, PID: 6642
    java.lang.IllegalArgumentException: uri cannot be null
        at com.google.android.gms.common.internal.Preconditions.checkArgument(com.google.android.gms:play-services-basement@@17.2.1:35)
        at com.google.firebase.storage.StorageReference.putFile(StorageReference.java:238)
        at com.example.bloodsavelife.Activities.MakeRequest.uploadToFirebase(MakeRequest.java:153)
        at com.example.bloodsavelife.Activities.MakeRequest.access$000(MakeRequest.java:47)
        at com.example.bloodsavelife.Activities.MakeRequest$2.onClick(MakeRequest.java:121)
        at android.view.View.performClick(View.java:7125)
        at android.view.View.performClickInternal(View.java:7102)
        at android.view.View.access$3500(View.java:801)
        at android.view.View$PerformClick.run(View.java:27336)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930) I/Process: Sending signal. PID: 6642 SIG: 9

XML 档案:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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"
tools:context=".Activities.MakeRequest">


<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:id="@+id/title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="18dp"
            android:text="Write your message and add an image for the community, somebody will 
 defintely help you if possible"
            android:textColor="@android:color/black"
            android:textSize="24sp"
            android:textStyle="bold" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/post_image"
            android:layout_width="192dp"
            android:layout_height="150dp"
            android:padding="8dp"
            android:src="@drawable/ic_launcher_background_image" />

        <Button
            android:id="@+id/browse"
            android:layout_width="141dp"
            android:layout_height="57dp"
            android:layout_marginLeft="50dp"
            android:layout_marginTop="60dp"
            android:background="@drawable/button_bg"
            android:gravity="center"
            android:text="Browse"
            android:textAlignment="gravity"
            android:textColor="@color/colorPrimary"
            android:textSize="24sp"
            android:textStyle="bold" />

    </LinearLayout>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:background="@drawable/border_background">

        <EditText
            android:id="@+id/message"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@null"
            android:cursorVisible="true"
            android:gravity="top"
            android:hint="Message to donors and mention for what purpose blood needed Include your 
 contact and location here."
            android:maxLines="15"
            android:minLines="7"
            android:padding="10dp"
            android:textAlignment="gravity"
            android:textColor="@android:color/black"
            android:textColorHint="@color/DarkGreen"
            android:textSize="15sp"
            android:textStyle="bold" />

    </FrameLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/bloodgroup"
            style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.ExposedDropdownMenu"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="10dp"
            android:layout_marginTop="20dp"
            android:layout_marginEnd="10dp"
            android:hint="Required Blood Group"
            android:inputType="text"
            android:textColor="@android:color/black"
            android:textSize="20sp"
            app:boxBackgroundMode="outline"
            app:endIconMode="dropdown_menu">

            <AutoCompleteTextView
                android:id="@+id/dropdown_text"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

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

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/quantity"
            style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="10dp"
            android:layout_marginTop="20dp"
            android:layout_marginEnd="10dp"
            android:hint="Quantity Needed(in ml)"
            android:inputType="text"
            android:textColor="@android:color/black"
            android:textSize="20sp"
            app:boxBackgroundMode="outline"
            app:endIconMode="clear_text">

            <com.google.android.material.textfield.TextInputEditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="text" />
        </com.google.android.material.textfield.TextInputLayout>


    </LinearLayout>


    <Button
        android:id="@+id/btn_post"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="30dp"
        android:background="@drawable/button_bg"
        android:text="Post Request"
        android:textAllCaps="false"
        android:textColor="@android:color/white"
        android:textSize="18sp"
        android:textStyle="bold" />

</LinearLayout>

</ScrollView>

Java 代码:

public class MakeRequest extends AppCompatActivity {

EditText message;
TextInputLayout bloodgroup, quantity;
TextView title;
ImageView image;
Uri filepath;
Bitmap bitmap;
Button postReq, browse;
private AutoCompleteTextView dropDownText;

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

    message = findViewById(R.id.message);
    bloodgroup = findViewById(R.id.bloodgroup);
    quantity = findViewById(R.id.quantity);
    browse = findViewById(R.id.browse);
    title = findViewById(R.id.title);
    image = findViewById(R.id.image);
    postReq = findViewById(R.id.btn_post);
    dropDownText = findViewById(R.id.dropdown_text);

    String[] item = new String[]{
            "A+Ve",
            "A-Ve",
            "B+Ve",
            "B-Ve",
            "AB+Ve",
            "AB-Ve",
            "O+Ve",
            "O-Ve"

    };
    ArrayAdapter<String> adapter = new ArrayAdapter<>(
            MakeRequest.this,
            R.layout.dropdown_item,
            item
    );
    dropDownText.setAdapter(adapter);


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

            Dexter.withActivity(MakeRequest.this)
                    .withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
                    .withListener(new PermissionListener() {
                        @Override
                        public void onPermissionGranted(PermissionGrantedResponse response) {
                            Intent intent = new Intent(Intent.ACTION_PICK);
                            intent.setType("image/*");
                            startActivityForResult(Intent.createChooser(intent, "select image"), 1);
                        }

                        @Override
                        public void onPermissionDenied(PermissionDeniedResponse response) {

                        }

                        @Override
                        public void onPermissionRationaleShouldBeShown(PermissionRequest permission, 
PermissionToken token) {
                            token.continuePermissionRequest();
                        }
                    }).check();
        }
    });

    postReq.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            uploadToFirebase();
        }
    });
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    if (requestCode == 1 && requestCode == RESULT_OK) {
        filepath = data.getData();
        try {
            InputStream inputStream = getContentResolver().openInputStream(filepath);
            bitmap = BitmapFactory.decodeStream(inputStream);
            image.setImageBitmap(bitmap);
        } catch (Exception ex) {

        }
    }
    super.onActivityResult(requestCode, resultCode, data);
}

private void uploadToFirebase() {

    ProgressDialog dialog = new ProgressDialog(this);
    dialog.setTitle("File Uploader");
    dialog.show();
enter code here
    message = findViewById(R.id.message);
    bloodgroup = findViewById(R.id.bloodgroup);
    quantity = findViewById(R.id.quantity);

    FirebaseStorage storage = FirebaseStorage.getInstance();
    //need improvement by using date and time instead of random method.
    StorageReference uploader = storage.getReference("Image1" + new Random().nextInt(100));
    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) {
                            dialog.dismiss();
                            FirebaseDatabase db = FirebaseDatabase.getInstance();
                            DatabaseReference root = db.getReference("RequestPost");

                            RequestHelper obj = new RequestHelper(message.getText().toString(), 
bloodgroup.getEditText().getText().toString(), quantity.getEditText().getText().toString(), 
uri.toString());
                            root.child(bloodgroup.getEditText().getText().toString()).setValue(obj);
                            message.setText("");
                            bloodgroup.getEditText().setText("");
                            quantity.getEditText().setText("");
                            image.setImageResource(R.drawable.ic_image_black_24dp);
                            Toast.makeText(getApplicationContext(), "Uploaded", 
Toast.LENGTH_LONG).show();

                        }
                    });
                }
            })
            .addOnProgressListener(snapshot -> {
                float percent = (100 * snapshot.getBytesTransferred()) / 
 snapshot.getTotalByteCount();
                dialog.setMessage("Uploaded:" + (int) percent + "%");
            });

}

尝试使用此代码

  • 从图库中选择图像
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT)
startActivityForResult(intent, 1001);

  • onActivityforresult 获取Uri
 protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data){
    super.onActivityResult(requestCode, resultCode, data);
   if (requestCode == 1001 && requestCode == RESULT_OK) {
       filepath = data.getData();
       try {
           InputStream inputStream = getContentResolver().openInputStream(filepath);
           bitmap = BitmapFactory.decodeStream(inputStream);
           image.setImageBitmap(bitmap);
       } catch (Exception ex) {
           // You can catch the exception here 
       }
   }
  
}

暂无
暂无

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

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