Uri到位图压缩显示nullpointerexception

时间:2018-06-22 16:37:55

标签: java android bitmap firebase-storage image-compression

这是完整的代码:

public class AddNewItem extends AppCompatActivity {

private static final int CHOOSE_IMAGE = 177;
private ImageView imageViewAdd;
private EditText titleEditText, descriptionEditText, priceEditText, cityEditText;
private String titleString, descriptionString, priceString, uploadID;
private Button buttonAdd, buttonRotateImage;
private ProgressBar progressBarImage;
private Uri uriSelectedImage;
private String downloadUriImage;
private FirebaseAuth mAuth;
private int imageRotation=0;
private AlertDialog.Builder mbuilder;
private StorageReference mStorageRef;
private DatabaseReference mDatabaseRef, mDatabaseRefUser;
private StorageTask mUploadTask;
private byte[] imageFileByte;
private Bitmap compressedImageBitmap;
int x = -10;

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

    imageViewAdd = findViewById(R.id.select_image_id);
    titleEditText = findViewById(R.id.title_edittext_id);
    descriptionEditText = findViewById(R.id.description_edittext_id);
    priceEditText = findViewById(R.id.price_edittext_id);
    cityEditText = findViewById(R.id.city_textview_id);
    buttonAdd = findViewById(R.id.add_item_button_id);
    buttonRotateImage = findViewById(R.id.rotate_image_id);
    progressBarImage = findViewById(R.id.progressbar_id);
    mAuth = FirebaseAuth.getInstance();
    mbuilder = new AlertDialog.Builder(this);

    mStorageRef = FirebaseStorage.getInstance().getReference("uploads");
    mDatabaseRef = FirebaseDatabase.getInstance().getReference("uploads");
    mDatabaseRefUser = FirebaseDatabase.getInstance().getReference("Users");
}

public void selectImage(View view) {
    Intent selectImageIntent = new Intent();
    selectImageIntent.setType("image/*");
    selectImageIntent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(selectImageIntent, "select image to show n upload"), CHOOSE_IMAGE);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == CHOOSE_IMAGE && resultCode == RESULT_OK && data != null && data.getData() != null) {

        uriSelectedImage = data.getData();

        File imageFile = new File(uriSelectedImage.getPath());
        Log.e("Filepath", imageFile+"");

    try {
            compressedImageBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uriSelectedImage);
            Log.e("Bitmap one: ", compressedImageBitmap+"");
        } catch (IOException e) {
            e.printStackTrace();
        }   

        compressedImageBitmap = new Compressor(this).compressToBitmap(imageFile);
        Log.e("Bitmap: ", compressedImageBitmap+"");
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        compressedImageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] imageByte = baos.toByteArray();
        imageFileByte = imageByte;


        Picasso.with(this).load(uriSelectedImage).into(imageViewAdd);


    }
}

private String getFileExtension(Uri uri) {
    ContentResolver cR = getContentResolver();
    MimeTypeMap mime = MimeTypeMap.getSingleton();
    return mime.getExtensionFromMimeType(cR.getType(uri));

}

//new code
public void uploadFile(View view) {

    if (mUploadTask != null && mUploadTask.isInProgress()) {
        Toast.makeText(this, "is in progress", Toast.LENGTH_SHORT).show();
        return;
    }
    if (titleEditText.getText().toString().isEmpty() || titleEditText.getTextSize() < 5) {
        titleEditText.setError("Title is short, minimum 5 characters");
        titleEditText.requestFocus();
        return;
    }
    if (descriptionEditText.getText().toString().isEmpty() || descriptionEditText.getTextSize() < 20) {
        descriptionEditText.setError("Description is short, minimum 20 characters");
        descriptionEditText.requestFocus();
        return;
    }

    if (cityEditText.getText().toString().isEmpty() || cityEditText.length() < 3) {
        cityEditText.setError("City/Location is short, minimum 3 characters");
        cityEditText.requestFocus();
        return;
    }
    if (priceEditText.getText().toString().isEmpty()) {
        priceEditText.setError("Price is needed");
        priceEditText.requestFocus();
        return;
    }
        else {
        if (uriSelectedImage != null) {
            StorageReference fileReference = mStorageRef.child(System.currentTimeMillis() +
                    "." + getFileExtension(uriSelectedImage));

            mUploadTask = fileReference.putBytes(imageFileByte)
                    .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                            //Delays the progressbar with 0.5 secs before it shows 0
                            //user has 0.5 secs to see the 100% bar, code is not necenssary
                            Handler handler = new Handler();
                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    progressBarImage.setProgress(0);
                                }
                            }, 500);
                            Toast.makeText(AddNewItem.this, "Upload succesful", Toast.LENGTH_SHORT).show();
                            //Upload image is a java class.
                            uploadID = mDatabaseRef.push().getKey();
                            UploadImage uploadImage = new UploadImage(titleEditText.getText().toString(),
                                    taskSnapshot.getDownloadUrl().toString(), descriptionEditText.getText().toString(),
                                    cityEditText.getText().toString(), priceEditText.getText().toString(),
                                    imageRotation, lanButton.getText().toString(), mAuth.getCurrentUser().getUid(),
                                    uploadID, mAuth.getCurrentUser().getEmail());

                            mDatabaseRef.child(uploadID).setValue(uploadImage);

                        }
                    })
                    .addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Toast.makeText(AddNewItem.this, e.getMessage(), Toast.LENGTH_SHORT).show();

                        }
                    })
                    .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                            double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
                            progressBarImage.setProgress((int) progress);

                        }
                    });
        } else {
            Toast.makeText(this, "no file selected", Toast.LENGTH_SHORT).show();
        }
    }

}

public void rotateImage(View view) {

    imageViewAdd.setRotation(imageViewAdd.getRotation() + 90);
    imageRotation = (int) imageViewAdd.getRotation();

}



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

    if(mAuth.getCurrentUser() == null){
        Intent mainActivityIntent = new Intent(this, MainActivity.class);
        startActivity(mainActivityIntent);
        finish();
    }
    else {
        mDatabaseRefUser.child(mAuth.getCurrentUser().getUid()).child("Online").setValue(true);


    }
}



}

这是我得到的错误原因:java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference

我在compressedImageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);行的onActivityResult中得到它

我不知道问题是什么,为什么我会得到Nullpointerexception。无论如何,我能解决这个问题吗?我正在尝试从图库中选择一个图像,然后对其进行压缩。之后,我想将其上传到Firebase存储。我已经寻找了好几个小时的解决方案,但似乎没有任何效果。

如何解决此问题?我如何将compressedImageBitmap设置为某种值,使其不显示null并可以进行压缩。因为目前我是从图库中选取图片,但仍然显示为Null。我确实拥有<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

的权限

在Logcat中,它还会显示E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /document/image:1204 (No such file or directory) when I chose an image from gallery.

这是来自Logcat的

E/Filepath: /document/image:1204
E/Bitmap one:: android.graphics.Bitmap@8d6ccc1
E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /document/image:1204 (No such file or directory)
E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException:  /document/image:1204 (No such file or directory)
E/Bitmap: null

0 个答案:

没有答案