Android Firebase upload image not working - java

I am trying to use the following code to have a user select an image, and after the image is selected, it is automatically uploaded to my Firebase storage. I initialized the variable storageReference in the OnCreate function
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo"))
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
startActivityForResult(intent, 1);
}
else if (options[item].equals("Choose from Gallery"))
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(intent.createChooser(intent, "Select Image"), 2);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#SuppressLint("LongLogTag")
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// If the image is uploaded properly and the resultcode is OK
// The imagePreview is updated and the image is uploaded
if(requestCode == 1 || requestCode == 2) {
if (resultCode == Activity.RESULT_OK && data != null && data.getData() == null) {
filePath = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(requireContext().getContentResolver(), filePath);
imagePreview.setImageBitmap(bitmap);
uploadImage();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private void uploadImage()
{
if (filePath != null) {
// Code for showing progressDialog while uploading
ProgressDialog progressDialog = new ProgressDialog(getContext());
progressDialog.setTitle("Uploading...");
progressDialog.show();
// Defining the child of storageReference
StorageReference ref = storageReference.child(mAuth.getCurrentUser().toString());
// adding listeners on upload
// or failure of image
ref.putFile(filePath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Image uploaded successfully
// Dismiss dialog
progressDialog.dismiss();
Toast.makeText(getActivity(), "Image Uploaded!!", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
// Error, Image not uploaded
progressDialog.dismiss();
Toast.makeText(getContext(),"Failed " + e.getMessage(),Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
// Progress Listener for loading
// percentage on the dialog box
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
progressDialog.setMessage("Uploaded " + (int)progress + "%");
}
});
}
}
My guess is that the uploadImage function is not being called but I am not sure why.

I figured it out, the issue was with this line
if (resultCode == Activity.RESULT_OK && data != null && data.getData() == null)
data.getData() == null
should be:
data.getData() != null

Related

Cant load picture from Firebase Storage to an Imageview

I am uploading a picture to Firebase storage in my app. It uploads fine and can be viewed in firebase storage online. When i'm trying to fetch it and show it in an image view, it does not show up in the image view instead the image view vanishes as well. I have tried this with Piccaso and glide and nothing is working. The code is attached below
Uploading Code:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE && resultCode == RESULT_OK && data != null && data.getData() != null) {
uri = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
profile_image = findViewById(R.id.profileimage);
profile_image.setImageBitmap(bitmap);
imageRef=storageReference.child(userID);
imageRef.putFile(uri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//if the upload is successful
//hiding the progress dialog
//and displaying a success toast
//dismissDialog();
profilePicUrl = taskSnapshot.getMetadata().getReference().getDownloadUrl().toString();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
//if the upload is not successful
//hiding the progress dialog
// dismissDialog();
//and displaying error message
Toast.makeText(profile.this, exception.getCause().getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
Download and loading into image view Code:
fbstorage=FirebaseStorage.getInstance();
storageReference=fbstorage.getReference();
imageRef=storageReference.child(userID);
final String h=imageRef.getDownloadUrl().toString();
storageReference.child(userID).getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Toast.makeText(profile.this, "hello", Toast.LENGTH_SHORT).show();
Picasso.with(profile.this).load(h).into(profile_image);
}
});
try it with glide .. this code works fine with me
StorageReference storageReference = FirebaseStorage.getInstance().getReference().child("folderName"+"/"+thePicName);
Glide.with(context.getApplicationContext())
.using(new FirebaseImageLoader())
.load(storageReference)
.asBitmap()
.diskCacheStrategy(DiskCacheStrategy.NONE)
.priority(Priority.IMMEDIATE)
.into(new BitmapImageViewTarget(pic) {
#Override
protected void setResource(Bitmap resource) {
RoundedBitmapDrawable drawable = RoundedBitmapDrawableFactory.create(context.getResources(),
Bitmap.createScaledBitmap(resource, 150, 150, false));
drawable.setCircular(false);
pic.setImageDrawable(drawable);
}
});

Insert a picture into an imageview

In my app, I insert two pictures into two image-views and I use activity for result to fetch the photo from gallery.
private void showFileChooser () {
mHandler.post(new Runnable() {
#Override
public void run() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
});
}
private void showFileChooser2 () {
mHandler.post(new Runnable() {
#Override
public void run() {
Intent intent2 = new Intent();
intent2.setType("image/*");
intent2.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent2, "Select Picture"), PICK_IMAGE_REQUEST2);
}
});
}
#Override
protected void onActivityResult ( int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
//Getting the Bitmap from Gallery
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
rbitmap = getResizedBitmap(bitmap, 1000);//Setting the Bitmap to ImageView
imageViewUserImage.setImageBitmap(rbitmap);
imageViewUserImage.requestFocus();
} catch (IOException e) {
e.printStackTrace();
}
}else if (requestCode == PICK_IMAGE_REQUEST2 && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath2 = data.getData();
try {
//Getting the Bitmap from Gallery
bitmap2 = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath2);
rbitmap2 = getResizedBitmap(bitmap2, 1000);//Setting the Bitmap to ImageView
imageViewUserImage2.setImageBitmap(rbitmap2);
imageViewUserImage2.requestFocus();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The app is doing well but sometimes a weird thing happens.Sometimes once I click the desired photo in gallery, the app returns to the main activity and I find the previous loaded image in the other image-view is deleted.In other words, sometimes loading a picture in one of them deletes the loaded image in the other.
That glitch doesn't happen always, it sometimes happens and sometimes the app works well without any problem.
How can I fix that?
Place a break point in the catch on the 'e.printStackTrace();' line.
Play with the app, and see the reason for failure.
Without any stack trace we can only guess the reason.
I found the problem.The size of the images are kind of large so a "memory is out" error appears.To avoid such problem, I recycled each bitmap within its if case.
private void showFileChooser () {
mHandler.post(new Runnable() {
#Override
public void run() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
});
}
private void showFileChooser2 () {
mHandler.post(new Runnable() {
#Override
public void run() {
Intent intent2 = new Intent();
intent2.setType("image/*");
intent2.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent2, "Select Picture"), PICK_IMAGE_REQUEST2);
}
});
}
#Override
protected void onActivityResult ( int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
//Getting the Bitmap from Gallery
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
rbitmap = getResizedBitmap(bitmap, 1000);//Setting the Bitmap to ImageView
imageViewUserImage.setImageBitmap(rbitmap);
bitmap.recycle;
imageViewUserImage.requestFocus();
} catch (IOException e) {
e.printStackTrace();
}
}else if (requestCode == PICK_IMAGE_REQUEST2 && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath2 = data.getData();
try {
//Getting the Bitmap from Gallery
bitmap2 = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath2);
rbitmap2 = getResizedBitmap(bitmap2, 1000);//Setting the Bitmap to ImageView
imageViewUserImage2.setImageBitmap(rbitmap2);
bitmap2.recycle;
imageViewUserImage2.requestFocus();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Replacing a button to go a paid layout with a swiping motion

I am building an app. One of the features I have is a paid option in which the user has access to an additional layout. Right now, the user can get there by clicking a button. Instead, I would like to have a swiping motion- if the user swipes down, it will ask for permission for the paid layout. If they do pay, when they swipe up, they can access the original layout.
Here is my main activity :
public class MainActivity extends AppCompatActivity {
EditText editText2;
Button btn_purchase;
ImageView imageView2;
String skuId;
SessionManager sessionManager;
// create new Person
private BillingClient mBillingClient;
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sessionManager=new SessionManager(MainActivity.this);
if(sessionManager.getPurchased()){
Intent intent = new Intent(MainActivity.this, PaidActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
btn_purchase=findViewById(R.id.btn_purchase);
imageView2 = (ImageView) findViewById(R.id.imageView2);
mBillingClient = BillingClient.newBuilder(MainActivity.this).setListener(new PurchasesUpdatedListener() {
#Override
public void onPurchasesUpdated(int responseCode, #Nullable List<Purchase> purchases) {
if (responseCode == BillingClient.BillingResponse.OK
&& purchases != null) {
for (Purchase purchase : purchases) {
//TODO: Handle purchase
// handlePurchase(purchase);
Log.e("Main", "handle Purchase ");
Log.e("MainAct", "onPurchasesUpdated() response: " + responseCode);
Log.e("dev", "successful purchase...");
String purchasedSku = purchase.getSku();
Log.e("dev", "Purchased SKU: " + purchasedSku);
String purchaseToken = purchase.getPurchaseToken();
sessionManager.savePurchased(true);
Intent intent = new Intent(MainActivity.this, PaidActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
} else if (responseCode == BillingClient.BillingResponse.USER_CANCELED) {
// Handle an error caused by a user cancelling the purchase flow.
} else {
// Handle any other error codes.
}
}
}).build();
List<String> skuList = new ArrayList <> ();
skuList.add("appsubscription2018");
SkuDetailsParams.Builder params = SkuDetailsParams.newBuilder();
params.setSkusList(skuList).setType(BillingClient.SkuType.INAPP);
mBillingClient.querySkuDetailsAsync(params.build(),
new SkuDetailsResponseListener() {
#Override
public void onSkuDetailsResponse(int responseCode, List<SkuDetails> skuDetailsList) {
// Process the result.
if (responseCode == BillingClient.BillingResponse.OK && skuDetailsList != null) {
Log.e("MainActivity", "onSkuDetailsResponse: success");
for (SkuDetails skuDetails : skuDetailsList) {
Log.e("MainActivity", "products: "+skuDetailsList);
String sku = skuDetails.getSku();
skuId = skuDetails.getSku();
String price = skuDetails.getPrice();
if ("appsubscription2018 ".equals(sku)) {
Log.e("MainActivity", "product is appsubscription2018 ");
// mPremiumUpgradePrice = price;
}
}
}
}
});
btn_purchase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mBillingClient.startConnection(new BillingClientStateListener() {
#Override
public void onBillingSetupFinished(#BillingClient.BillingResponse int billingResponseCode) {
if (billingResponseCode == BillingClient.BillingResponse.OK) {
// The billing client is ready. You can query purchases here.
// The billing client is ready. You can query purchases here.
BillingFlowParams flowParams = BillingFlowParams.newBuilder()
.setSku("appsubscription2018")
.setType(BillingClient.SkuType.INAPP)
.build();
int responseCode = mBillingClient.launchBillingFlow(MainActivity.this, flowParams);
if (responseCode != BillingClient.BillingResponse.OK) {
Log.e("Main", "launchBillingFlow ok");
}
}
}
#Override
public void onBillingServiceDisconnected() {
// Try to restart the connection on the next request to
// Google Play by calling the startConnection() method.
}
});
}
});
imageView2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (checkFilePermission(MainActivity.this)){
getPhoto();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode ==1 && resultCode == RESULT_OK && data != null) {
Uri selectedImage = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
imageView2.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static boolean checkFilePermission(final Context context) {
int currentAPIVersion = Build.VERSION.SDK_INT;
if(currentAPIVersion>= Build.VERSION_CODES.M)
{
if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.READ_EXTERNAL_STORAGE)) {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
alertBuilder.setCancelable(true);
alertBuilder.setTitle("Permission necessary");
alertBuilder.setMessage("External storage permission is necessary");
alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
}
});
AlertDialog alert = alertBuilder.create();
alert.show();
} else {
ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
}
return false;
} else {
return true;
}
} else {
return true;
}
}
public void getPhoto() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent,1);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode ==1){
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED);{
getPhoto();
}
}
}
}

How to crop two different images in the same activity with different parameters in Android?

I am using this Crop library by SoundCloud. Selecting one imageview, slecting image, cropping and showing the result in the imageview works fine. But now I am trying to do it with two different imageviews with different specifications. I am not getting any errors nor am I seeing any results. Here's what I have tried:
//My click listeners
regCoverPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Crop.pickImage(getActivity(), EditProfileDialog.this, REQUEST_CODE_COVER);
}
});
regUserProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Crop.pickImage(getActivity(), EditProfileDialog.this, REQUEST_CODE_PROFILE);
}
});
//Handling the result
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_PROFILE && resultCode == Activity.RESULT_OK) {
beginCropProfile(data.getData());
}else if(requestCode == REQUEST_CODE_COVER && resultCode == Activity.RESULT_OK){
beginCropCover(data.getData());
} else if (requestCode == Crop.REQUEST_CROP) {
handleCrop(requestCode, resultCode, data);
}
}
private void beginCropProfile(Uri source) {
Uri destination = Uri.fromFile(new File(getActivity().getCacheDir(), "cropped"));
Crop.of(source, destination).withAspect(ASPECT_X, ASPECT_Y).start(getActivity(), EditProfileDialog.this, REQUEST_CODE_COVER);
}
private void beginCropCover(Uri source) {
Uri destination = Uri.fromFile(new File(getActivity().getCacheDir(), "cropped"));
Crop.of(source, destination).asSquare().start(getActivity(), EditProfileDialog.this, REQUEST_CODE_PROFILE);
}
private void handleCrop(int requestCode, int resultCode, Intent result) {
if (requestCode == REQUEST_CODE_COVER && resultCode == Activity.RESULT_OK) {
regCoverPhoto.setImageURI(Crop.getOutput(result));
mCoverPhotoUri = Crop.getOutput(result);
uploadCoverToStorage();
Log.d(TAG,"ResultCover: " + Crop.getOutput(result).toString());
}else if(requestCode == REQUEST_CODE_PROFILE && resultCode == Activity.RESULT_OK){
regUserProfile.setImageURI(Crop.getOutput(result));
mProfilePhotoUri = Crop.getOutput(result);
uploadProfileToStorage();
Log.d(TAG,"ResultProfile: " + Crop.getOutput(result).toString());
} else if (resultCode == Crop.RESULT_ERROR) {
Snackbar.make(getView(), Crop.getError(result).getMessage(), Snackbar.LENGTH_LONG).show();
}
}
I haven't used this library particularly, but custom request codes seem to be the problem.
Use different request codes for picking and cropping (total of 4 request codes) as you will need to handle them differently, and update onActivityResult(), handleCrop() to reflect that.
See https://gist.github.com/vibinr/fcf54c5e7ab63b9184432cc44c9a1494
List item
Here is a complete code of the images selection to crop and uploading to server using rest client with retrofit library Here few variables are used extra as for my use please ignore them
Also i'm using these library inside gradel
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.theartofdev.edmodo:android-image-cropper:2.4.+'
compile 'com.squareup.retrofit:retrofit:1.6.1'
And inside Mainfrest i have specifed this as <activity
android:name="com.theartofdev.edmodo.cropper.CropImageActivity"
android:screenOrientation="portrait" />
side2Image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
image_name = "image_side_2";
image_number_5 = "image_side_2";
imagePath = Environment.getExternalStorageDirectory().toString();
new File(imagePath).mkdir();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
String name = dateFormat.format(new Date());
savedFileDestination = new File(imagePath, name + ".jpg");
CropImage.activity(Uri.fromFile(savedFileDestination));
CropImage.startPickImageActivity(TradeAddProduct.this);
}
backImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
image_name = "image_back";
image_number_6 = "image_back";
imagePath = Environment.getExternalStorageDirectory().toString();
new File(imagePath).mkdir();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
String name = dateFormat.format(new Date());
savedFileDestination = new File(imagePath, name + ".jpg");
CropImage.activity(Uri.fromFile(savedFileDestination));
CropImage.startPickImageActivity(TradeAddProduct.this);
}
#Override
#SuppressLint("NewApi")
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CropImage.PICK_IMAGE_CHOOSER_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
imageUri = CropImage.getPickImageResultUri(this, data);
// For API >= 23 we need to check specifically that we have permissions to read external storage.
if (CropImage.isReadExternalStoragePermissionsRequired(this, imageUri)) {
// request permissions and handle the result in onRequestPermissionsResult()
mCropImageUri = imageUri;
requestPermissions(new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
} else {
// no permissions required or already grunted, can start crop image activity
startCropImageActivity(imageUri);
}
}
// handle result of CropImageActivity
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
if (image_name.equals("image_front")) {
image.setImageURI(result.getUri());
} else if (image_name.equals("image_top")) {
topImage.setImageURI(result.getUri());
} else if (image_name.equals("image_bottom")) {
bottomImage.setImageURI(result.getUri());
} else if (image_name.equals("image_side_1")) {
side1Image.setImageURI(result.getUri());
} else if (image_name.equals("image_side_2")) {
side2Image.setImageURI(result.getUri());
} else if (image_name.equals("image_back")) {
backImage.setImageURI(result.getUri());
}
cropped = result.getUri();
File path = getExternalCacheDir();
new File(String.valueOf(path)).mkdir();
imagePath = Environment.getExternalStorageDirectory().toString();
new File(imagePath).mkdir();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
String name22 = dateFormat.format(new Date());
// String helloWorld = cropped.toString();
// String hhhh=helloWorld.substring(helloWorld.indexOf(":")+1,helloWorld.indexOf("/"));
// String name="snehal_go";
savedFileDestination = new File(imagePath, name22 + ".jpg");
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/yourapp/app_data/imageDir
File directory = cw.getDir("Webmirchi..", Context.MODE_PRIVATE);
String ALLOWED_CHARACTERS = "QWERTYUIOPASDFGHJKLZXCVBNM0123456789qwertyuiopasdfghjklzxcvbnm";
Random generator = new Random();
randomStringBuilder = new StringBuilder();
int randomLength = 10;
for (int i = 0; i < randomLength; i++) {
randomStringBuilder.append(ALLOWED_CHARACTERS.charAt(generator.nextInt(ALLOWED_CHARACTERS.length())));
}
// Create imageDir
mypath = new File(directory, sessionMail + "-" + ProductId + ".jpg");
FileOutputStream fos = null;
try {
Bitmap bitmapImage = MediaStore.Images.Media.getBitmap(this.getContentResolver(), cropped);
fos = new FileOutputStream(mypath);
// Use the compress method on the BitMap object to write image to the OutputStream
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
Log.i("File", mypath.toString());
if (image_name.equals("image_front")) {
uploadImage_front();
} else if (image_name.equals("image_top")) {
uploadImage_top();
} else if (image_name.equals("image_bottom")) {
uploadImage_bottom();
} else if (image_name.equals("image_side_1")) {
uploadImage_side1();
} else if (image_name.equals("image_side_2")) {
uploadImage_side2();
} else if (image_name.equals("image_back")) {
uploadImage_back();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
// Toast.makeText(this, "Cropping failed: " + result.getError(), Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
if (mCropImageUri != null && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// required permissions granted, start crop image activity
startCropImageActivity(mCropImageUri);
} else {
Toast.makeText(this, "Cancelling, required permissions are not granted", Toast.LENGTH_LONG).show();
}
}
*/
private void startCropImageActivity(Uri imageUri) {
CropImage.activity(imageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setMultiTouchEnabled(false)
.setMinCropWindowSize(600, 600)
.setAspectRatio(2, 2)
.setRequestedSize(500, 500)
.start(this);
}
Please refer the following url.This may help you. "https://www.bignerdranch.com/blog/understanding-androids-layoutinflater-inflate/"
I'm not good in english...
// took extra int
static int a=0;
private void onClickData() {
cover_imgBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// change the value
a=1;
CropImage.activity()
.setAspectRatio(10,15)
.start(AddNewBooks_Images.this);
}
});
author_imgBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// change the value
a=2;
CropImage.activity()
.setAspectRatio(10,15)
.start(AddNewBooks_Images.this);
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//here used the value
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK && data!=null && a==1){
// change the value again
a=0;
}
//here used the value
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK && data!=null && a==2){
// change the value again
a=0;
}
}

Attempt to invoke virtual method 'android.os.Parcelable android.os.Bundle.getParcelable(java.lang.String)' null object reference

I am making an app in which a feature that user can upload images and video to server
it was working well on activity but now I want to use it in a fragment. I try to code effectively, efficiently and I am not getting any error during compiling and my app runs successfully but when I click on fragment it shows "unfortunately app has stopped " and in log cat I am getting this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Parcelable android.os.Bundle.getParcelable(java.lang.String)' on a null object reference
and its points this line:
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
this line ➦ fileUri = savedInstanceState.getParcelable("file_uri");
}
i don't know whats wrong
my code:
public class TabFragment4 extends Fragment implements View.OnClickListener{
View parentHolder;
private static final String TAG = MainActivity.class.getSimpleName();
int req_code = 100;
int video_code = 20;
String path;
Uri selectedImageUri;
// Camera activity request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 10;
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
Context mContext;
private Uri fileUri; // file url to store image/video
private ImageButton btnCapturePicture, btnRecordVideo,gallerybtn , videobtn,b1,location;
public TabFragment4() {
// Required empty public constructor
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
parentHolder = inflater.inflate(R.layout.fragment_tab_fragment4, container, false);
final LocationManager manager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
AlertDialog.Builder mAlertDialog = new AlertDialog.Builder(getActivity());
// Setting Dialog Title
mAlertDialog.setTitle("Location not available, Open GPS?")
.setMessage("Activate GPS to use Location Service ?")
.setPositiveButton("Open Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
})
.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
}).show();
// Call your Alert message
}
btnCapturePicture = (ImageButton)parentHolder.findViewById(R.id.btnCapturePicture);
btnRecordVideo = (ImageButton)parentHolder. findViewById(R.id.btnRecordVideo);
gallerybtn=(ImageButton)parentHolder.findViewById(R.id.imagegallery);
videobtn = (ImageButton)parentHolder.findViewById(R.id.videogallery);
location=(ImageButton)parentHolder.findViewById(R.id.location);
videobtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
video();
}
});
gallerybtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// record video
galleryimage();
}
});
btnCapturePicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// record video
captureImage();
}
});
/**
* Capture image button click event
*/
btnRecordVideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// record video
recordVideo();
}
});
/**
* Record video button click event
*/
btnRecordVideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// record video
recordVideo();
}
});
return parentHolder;
}
public void video(){
Intent intent = new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select file to upload "), video_code);
}
public void galleryimage(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select file to upload "), req_code);
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
/**
* Launching camera app to record video
*/
private void recordVideo() {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
// set video quality
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file
// name
// start the video capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
}
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on screen orientation
// changes
outState.putParcelable("file_uri", fileUri);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
fileUri = savedInstanceState.getParcelable("file_uri");
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == req_code) {
selectedImageUri = data.getData();
if (resultCode ==Activity. RESULT_OK) {
path = getPath(selectedImageUri);
launchUpload(true);
System.out.println("selectedPath1 : " + path);
}
}
if (requestCode == video_code) {
selectedImageUri = data.getData();
if (resultCode == Activity. RESULT_OK) {
path = getPath(selectedImageUri);
launchUpload(false);
System.out.println("selectedPath1 : " + path);
}
}
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
//successfully captured the image
// launching upload activity
launchUploadActivity(true);
//Intent intent = new Intent(this,UploadActivity.class);
//startActivity(intent);
} else if (resultCode ==Activity. RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getActivity(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getActivity(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
} else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
// video successfully recorded
// launching upload activity
launchUploadActivity(false);
} else if (resultCode == Activity.RESULT_CANCELED) {
// user cancelled recording
Toast.makeText(getActivity(),
"User cancelled video recording", Toast.LENGTH_SHORT)
.show();
} else {
// failed to record video
Toast.makeText(getActivity(),
"Sorry! Failed to record video", Toast.LENGTH_SHORT)
.show();
}
}
}
private void launchUploadActivity(boolean isImage) {
Intent i = new Intent(getActivity(), UploadActivity.class);
i.putExtra("filePath", fileUri.getPath());
i.putExtra("isImage", isImage);
startActivity(i);
}
private void launchUpload(boolean isImage) {
Intent i = new Intent(getActivity(), UploadActivity.class);
i.putExtra("filePath", path);
i.putExtra("isImage", isImage);
startActivity(i);
}
/**
* ------------ Helper Methods ----------------------
* */
/**
* Creating file uri to store image/video
*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/**
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
Config.IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(TAG, "Oops! Failed create "
+ Config.IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else if (type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "VID_" + timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
#Override
public void onClick(View v) {
}
}
Uri imageUri = data.getData();
Bitmap bitmap= null;
try {
bitmap = MediaStore.Images.Media.getBitmap(getContext().getContentResolver(), imageUri);
} catch (IOException e) {
e.printStackTrace();
}
Seems savedInstanceState == null so use something like this:
if (savedInstanceState != null) {
fileUri = savedInstanceState.getParcelable("file_uri");
} else {
fileUri = ??? - what You want do to in else case;
}

Categories