我对Android很新。请给我一些帮助。我需要Image URI,在此之前我尝试了data.getData();并将其传递给getContentResolver()。query()但data.getData();总是返回null 错误发生在以下几行:
Uri SelectedImageURI = getImageUri(getApplicationContext(),SelectedImage); 返回Uri.parse(路径);
我的Android版本是5.0.2
05-10 01:55:10.712 24424-24424/com.donateblood.blooddonation E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.donateblood.blooddonation, PID: 24424
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { act=com.htc.HTCAlbum.action.ITEM_PICKER_FROM_COLLECTIONS (has extras) }} to activity {com.donateblood.blooddonation/com.donateblood.blooddonation.UploadImage}: java.lang.NullPointerException: uriString
at android.app.ActivityThread.deliverResults(ActivityThread.java:3881)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3931)
at android.app.ActivityThread.access$1300(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1408)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5696)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1028)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
Caused by: java.lang.NullPointerException: uriString
at android.net.Uri$StringUri.<init>(Uri.java:473)
at android.net.Uri$StringUri.<init>(Uri.java:463)
at android.net.Uri.parse(Uri.java:435)
at com.donateblood.blooddonation.UploadImage.getImageUri(UploadImage.java:156)
at com.donateblood.blooddonation.UploadImage.onActivityResult(UploadImage.java:102)
at android.app.Activity.dispatchActivityResult(Activity.java:6160)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3877)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3931)
at android.app.ActivityThread.access$1300(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1408)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5696)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1028)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
package com.donateblood.blooddonation;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.Rect;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.mongodb.DB;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSInputFile;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import butterknife.ButterKnife;
import butterknife.InjectView;
/**
* Created by YouCaf Iqbal on 4/26/2016.
*/
public class UploadImage extends AppCompatActivity {
public static final int RESULT_LOAD = 1;
@InjectView(R.id.imageView) ImageView ImageUpload;
@InjectView(R.id.upload) Button Btn_Upload;
@InjectView(R.id.proceed) Button Btn_Proceed;
public String bloodgroup,name,password,number,email,picturePath,encodedPhotoString;
Database dbobj = new Database();
GPSTracker gps; private DB db;
public double latitude=0;
public double longitude=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.uploadimage);
ButterKnife.inject(this);
getCurrentLatLong();
Btn_Upload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try{
Intent upload = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//Adding Croping
upload.putExtra("crop","true");
upload.putExtra("aspectX",1);
upload.putExtra("aspectY",1);
upload.putExtra("outputX",300);
upload.putExtra("outputY",300);
upload.putExtra("return-data",true);
startActivityForResult(upload,RESULT_LOAD);
} catch (ActivityNotFoundException E) {
String errorMessage = "Your device doesn't support the crop action!";
Toast toast = Toast.makeText(UploadImage.this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
});
Btn_Proceed.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Prcoess();
}
});
}
// When image is selected from Gallery
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==RESULT_LOAD && resultCode==RESULT_OK && data!=null){
Bundle extras = data.getExtras();
//Uri SelectedImageURI = (Uri)extras.get(Intent.EXTRA_STREAM);
Bitmap SelectedImage = extras.getParcelable("data");
//Make Image rounded
//Bitmap RoundedImage = getRoundedShape(SelectedImage);
// Uri SelectedImageURI = data.getData();
Uri SelectedImageURI = getImageUri(getApplicationContext(), SelectedImage);
picturePath = getRealPathFromURI(SelectedImageURI);
ImageUpload.setImageBitmap(SelectedImage);
// retrieve image path
String[] projection = {MediaStore.Images.Media.DATA};
try {
// Cursor cursor = getContentResolver().query(SelectedImageURI, projection, null, null, null);
//cursor.moveToFirst();
// int columnIndex = cursor.getColumnIndex(projection[0]);
// picturePath = cursor.getString(columnIndex);
// cursor.close();
////////////////////////////////////////////////////
String fileNameSegments[] = picturePath.split("/");
String fileName = fileNameSegments[fileNameSegments.length - 1];
try {
File f = new File(picturePath);
Bitmap myImg = decodeFile(f,720);
//myImg = getResizedBitmap(myImg,100); // Compress it
// Bitmap myImg = BitmapFactory.decodeFile(picturePath);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// Must compress the Image to reduce image size to make upload easy
// myImg = getResizedBitmap(myImg, 720);
myImg.compress(Bitmap.CompressFormat.JPEG, 50, stream);
byte[] byte_arr = stream.toByteArray();
// Encode Image to String
encodedPhotoString = Base64.encodeToString(byte_arr, 0);
// ImageUpload.setImageBitmap(myImg);
}catch (Exception e){
Toast.makeText(UploadImage.this,"Unable to Set Image Try Again",Toast.LENGTH_SHORT).show();
}
//Log.d("Picture Path", picturePath);
// Toast.makeText(getBaseContext(), ""+picturePath+"", Toast.LENGTH_LONG).show();
}
catch(Exception e) {
// Log.e("Path Error", e.toString());
Toast.makeText(getBaseContext(), "Error finding path", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
//
}
}
public void Prcoess(){
dbAsync signupThread = new dbAsync();
signupThread.execute();
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
public String getRealPathFromURI(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
public class dbAsync extends AsyncTask<Void,Void,Void> {
private ProgressDialog pDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(UploadImage.this);
pDialog.setMessage("Creating Account...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected Void doInBackground(Void... voids) {
GetUserDetails();
dbobj.insertUser(name,email,password,number,bloodgroup,latitude,longitude,encodedPhotoString);
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
pDialog.dismiss();
Toast.makeText(getBaseContext(), "Created Successfully", Toast.LENGTH_LONG).show();
// Toast.makeText(getBaseContext(), ""+encodedPhotoString+"", Toast.LENGTH_LONG).show();
onSignupSuccess();
}
}
public void onSignupSuccess() {
// btn_signup.setEnabled(true);
//setResult(RESULT_OK, null);
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
finish();
}
public void GetUserDetails(){
//mySpinner=(Spinner) findViewById(R.id.spinner);
bloodgroup = SignupActivity.bloodgroup.toString();
name = SignupActivity.name.toString();
email = SignupActivity.email.toString();
password = SignupActivity.password.toString();
number = SignupActivity.number.toString();
}
public void getCurrentLatLong(){
gps = new GPSTracker(UploadImage.this);
if (gps.canGetLocation()) {
latitude = gps.getLatitude();
longitude = gps.getLongitude();
}
}
public Bitmap decodeFile(File f,int IMAGE_MAX_SIZE){
Bitmap b = null;
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BitmapFactory.decodeStream(fis, null, o);
try {
fis.close();
int scale = 1;
if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
scale = (int) Math.pow(2, (int) Math.ceil(Math.log(IMAGE_MAX_SIZE /
(double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
}
//Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
fis = new FileInputStream(f);
b = BitmapFactory.decodeStream(fis, null, o2);
fis.close();
}catch (IOException e) {
e.printStackTrace();
}
return b;
}
}
答案 0 :(得分:0)
Intent
中的 ACTION_PICK
returns its result in the Uri
已发送至onActivityResult()
。您致电getData()
以获取此Uri
。就是这样。因此,if(requestCode==RESULT_LOAD && resultCode==RESULT_OK && data!=null)
块中的所有内容都不仅错误,而且无用。
除此之外,摆脱ACTION_PICK
Intent
上放置的所有未记录的额外内容。使用an image cropping library。