JavaBinder FAILED BINDER TRANSACTION - android

I am getting this error in logcat when i try to upload image grom gallery. when i upload image from camera directly it works fine. Below is my code
public class OfflineMerchantRegisterActivity extends AppCompatActivity {
EditText edtUsername, edtPassword, edtConfirmPassword, edtEmail, edtMobile, edtServiceType, edtName, edtAddress, edtCity;
Button btnRegister, btnSelectImage, btnSelectCity, btnSelectType;
ImageView imgMerchant;
String offline_service_type;
LinearLayout layoutCity, layoutServiceType;
EditText edtService;
String service;
String username, password, confirmPassword, email, mobile, serviceType, name, address, city;
Context context;
private String userChoosenTask;
private static final int CAMERA_REQUEST = 1888;
private static final int GALLERY_REQUEST = 2;
Bitmap imageBitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_offline_merchant_register);
context=OfflineMerchantRegisterActivity.this;
edtUsername = (EditText) findViewById(R.id.edtUsername);
edtPassword = (EditText) findViewById(R.id.edtPassword);
edtConfirmPassword = (EditText) findViewById(R.id.edtConfirmPassword);
edtEmail = (EditText) findViewById(R.id.edtEmail);
edtMobile = (EditText) findViewById(R.id.edtMobile);
edtServiceType = (EditText) findViewById(R.id.edtServiceType);
edtName = (EditText) findViewById(R.id.edtName);
edtAddress = (EditText) findViewById(R.id.edtAddress);
edtCity = (EditText) findViewById(R.id.edtCity);
edtService = (EditText) findViewById(R.id.edtService);
edtService.setText("Offline Merchant");
btnRegister = (Button) findViewById(R.id.btnRegister);
btnSelectImage = (Button) findViewById(R.id.btnSelectImage);
btnSelectCity = (Button) findViewById(R.id.btnSelectCity);
btnSelectType = (Button) findViewById(R.id.btnSelectType);
imgMerchant = (ImageView) findViewById(R.id.imgMerchant);
layoutCity = (LinearLayout) findViewById(R.id.layoutCity);
layoutServiceType = (LinearLayout) findViewById(R.id.layoutServiceType);
btnSelectCity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(OfflineMerchantRegisterActivity.this, MerchantCityActivity.class);
startActivityForResult(intent, 3);
}
});
btnSelectType.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(OfflineMerchantRegisterActivity.this, OfflineServiceTypeListActivity.class);
startActivityForResult(intent, 1);
}
});
layoutServiceType.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
layoutCity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isValid()){
//registerOfflineMerchant();
Intent intent = new Intent(OfflineMerchantRegisterActivity.this, OfflineMerchantConfirmActivity.class);
intent.putExtra("username", edtUsername.getText().toString());
intent.putExtra("password", edtPassword.getText().toString());
intent.putExtra("email", edtEmail.getText().toString());
intent.putExtra("mobile", edtMobile.getText().toString());
intent.putExtra("serviceType", edtServiceType.getText().toString());
intent.putExtra("name", edtName.getText().toString());
intent.putExtra("address", edtAddress.getText().toString());
intent.putExtra("city", edtCity.getText().toString());
if (imageBitmap!=null){
intent.putExtra("imageString", getStringImage(imageBitmap));
intent.putExtra("fileName", username+".png");
}
else {
//do nothing
}
intent.putExtra("service", edtService.getText().toString());
startActivity(intent);
}
}
});
btnSelectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/* Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);*/
selectImage();
}
});
}
public boolean isValidMail(String email) {
// TODO Auto-generated method stub
boolean isValid = false;
String expression = "^[\\w\\.-]+#([\\w\\-]+\\.)+[A-Z]{2,4}$";
CharSequence inputStr = email;
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(inputStr);
if (matcher.matches()) {
isValid = true;
}
return isValid;
}
public boolean isValid(){
username = edtUsername.getText().toString().trim();
name = edtName.getText().toString().trim();
password = edtPassword.getText().toString().trim();
confirmPassword = edtConfirmPassword.getText().toString().trim();
email = edtEmail.getText().toString().trim();
mobile = edtMobile.getText().toString().trim();
serviceType = edtServiceType.getText().toString().trim();
address = edtAddress.getText().toString().trim();
city = edtCity.getText().toString().trim();
service = edtService.getText().toString().trim();
if (username.length() <=0){
Toast.makeText(OfflineMerchantRegisterActivity.this, "Please Enter Username", Toast.LENGTH_SHORT).show();
return false;
}
if (name.length() <=0){
Toast.makeText(OfflineMerchantRegisterActivity.this, "Please Enter Name", Toast.LENGTH_SHORT).show();
return false;
}
if (password.length() <=0){
Toast.makeText(OfflineMerchantRegisterActivity.this, "Please Enter Password", Toast.LENGTH_SHORT).show();
return false;
}
if (confirmPassword.length() <=0){
Toast.makeText(OfflineMerchantRegisterActivity.this, "Please Enter Password Again", Toast.LENGTH_SHORT).show();
return false;
}
if (!(password.equals(confirmPassword))) {
Toast.makeText(this, "Passwords Mismatch", Toast.LENGTH_SHORT).show();
return false;
}
if (email.length() <=0){
Toast.makeText(OfflineMerchantRegisterActivity.this, "Please Enter Email", Toast.LENGTH_SHORT).show();
return false;
}
if (!isValidMail(email)) {
Toast toast = Toast.makeText(this, "Please Enter Valid Email", Toast.LENGTH_SHORT);
toast.show();
return false;
}
if (mobile.length() <=9){
Toast.makeText(OfflineMerchantRegisterActivity.this, "Please Enter Mobile Number", Toast.LENGTH_SHORT).show();
return false;
}
if (serviceType.length() <=0){
Toast.makeText(OfflineMerchantRegisterActivity.this, "Please Select Service Type", Toast.LENGTH_SHORT).show();
return false;
}
if (address.length() <=0){
Toast.makeText(OfflineMerchantRegisterActivity.this, "Please Enter Address", Toast.LENGTH_SHORT).show();
return false;
}
if (city.length() <=0){
Toast.makeText(OfflineMerchantRegisterActivity.this, "Please Select City", Toast.LENGTH_SHORT).show();
return false;
}
if (service.length() <= 0){
Toast.makeText(OfflineMerchantRegisterActivity.this, "Please Enter As Offline Service", Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == 1) {
offline_service_type = data.getStringExtra("offlineServiceType");
edtServiceType.setText(offline_service_type);
}
if (resultCode == Activity.RESULT_OK){
if (requestCode == 3){
city = data.getStringExtra("city");
edtCity.setText(city);
}
}
if (resultCode == RESULT_OK && null != data) {
if (requestCode == GALLERY_REQUEST) {
Uri URI = data.getData();
String[] FILE = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(URI, FILE, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(FILE[0]);
String imageDecode = cursor.getString(columnIndex);
cursor.close();
imageBitmap = BitmapFactory.decodeFile(imageDecode);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
imgMerchant.setImageBitmap(imageBitmap);
//uploadImageToServer(getStringImage(bmp), username);
} else if (requestCode == CAMERA_REQUEST) {
imageBitmap = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
imgMerchant.setImageBitmap(imageBitmap);
//uploadImageToServer(getStringImage(thumbnail), username);
}
}
}
}
public String getStringImage(Bitmap bmp) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 90, outputStream);
byte[] imageBytes = outputStream.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case Utility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (userChoosenTask.equals("Take Photo"))
cameraIntent();
else if (userChoosenTask.equals("Choose from Library"))
galleryIntent();
} else {
//code for deny
}
break;
}
}
private void selectImage() {
final CharSequence[] items = {"Take Photo", "Choose from Library",
"Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Add Photo");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result = Utility.checkPermission(context);
if (items[item].equals("Take Photo")) {
userChoosenTask = "Take Photo";
if (result)
cameraIntent();
} else if (items[item].equals("Choose from Library")) {
userChoosenTask = "Choose from Library";
if (result)
galleryIntent();
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
private void galleryIntent() {
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, GALLERY_REQUEST);
//startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
}
private void cameraIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_REQUEST);
}
public void onBackPressed() {
OfflineMerchantRegisterActivity.this.finish();
super.onBackPressed();
}
}
How to solve this error ? after selecting image from gallery, app crash error.

This error mostly occurs when the data you are filling in the intent is more than the system is able to transfer through Intent bundle. Check to see the size of all the things you are putting in the bundle. And also check to see that the image you are selecting from gallery is not very large, as the system may not be able to transfer the image from gallery to you app. The camera code is working because the camera app transfers a low-resolution image through the Intent.

Related

How to set multiple image in multiple imageview

I am new to programming and android. I'm building an app that allows users to upload multiple images,I am using two image view, pic from camera to set one image view and another image view to set another camera pic from to set another images and same thing pic from gallery.I need to upload 2 different image in to different image view. How can I upload? i attached the my code kindly solve my issue.
public class MainActivity extends AppCompatActivity {
ImageView imageView1, imageView2;
private Button btn;
private static final String IMAGE_DIRECTORY = "/demonuts";
private int GALLERY = 1, CAMERA = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView1 = findViewById(R.id.image1);
imageView2 = findViewById(R.id.image2);
requestMultiplePermissions();
btn = findViewById(R.id.btn);
imageView1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showPictureDialog();
}
});
imageView2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showPictureDialog();
}
});
}
private void showPictureDialog() {
AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this);
pictureDialog.setTitle("Select Action");
String[] pictureDialogItems = {
"Select photo from gallery",
"Capture photo from camera"};
pictureDialog.setItems(pictureDialogItems,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
choosePhotoFromGallary();
break;
case 1:
takePhotoFromCamera();
break;
}
}
});
pictureDialog.show();
}
public void choosePhotoFromGallary() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, GALLERY);
}
private void takePhotoFromCamera() {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == this.RESULT_CANCELED) {
return;
}
switch (requestCode) {
case R.id.image1:
if (requestCode == GALLERY) {
if (data != null) {
Uri contentURI = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), contentURI);
String path = saveImage(bitmap);
Toast.makeText(MainActivity.this, "Image Saved!", Toast.LENGTH_SHORT).show();
imageView1.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Failed!", Toast.LENGTH_SHORT).show();
}
}
} else if (requestCode == CAMERA) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
imageView1.setImageBitmap(thumbnail);
saveImage(thumbnail);
Toast.makeText(MainActivity.this, "Image Saved!", Toast.LENGTH_SHORT).show();
}
break;
case R.id.image2:
if (requestCode == GALLERY) {
if (data != null) {
Uri contentURI = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), contentURI);
String path = saveImage(bitmap);
Toast.makeText(MainActivity.this, "Image Saved!", Toast.LENGTH_SHORT).show();
imageView2.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Failed!", Toast.LENGTH_SHORT).show();
}
}
} else if (requestCode == CAMERA) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
imageView2.setImageBitmap(thumbnail);
saveImage(thumbnail);
Toast.makeText(MainActivity.this, "Image Saved!", Toast.LENGTH_SHORT).show();
}
break;
}
}
public String saveImage(Bitmap myBitmap) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File wallpaperDirectory = new File(
Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);
// have the object build the directory structure, if needed.
if (!wallpaperDirectory.exists()) {
wallpaperDirectory.mkdirs();
}
try {
File f = new File(wallpaperDirectory, Calendar.getInstance()
.getTimeInMillis() + ".jpg");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
MediaScannerConnection.scanFile(this,
new String[]{f.getPath()},
new String[]{"image/jpeg"}, null);
fo.close();
Log.d("TAG", "File Saved::--->" + f.getAbsolutePath());
return f.getAbsolutePath();
} catch (IOException e1) {
e1.printStackTrace();
}
return "";
}
private void requestMultiplePermissions() {
Dexter.withActivity(this)
.withPermissions(
Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new MultiplePermissionsListener() {
#Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
// check if all permissions are granted
if (report.areAllPermissionsGranted()) {
Toast.makeText(getApplicationContext(), "All permissions are granted by user!", Toast.LENGTH_SHORT).show();
}
// check for permanent denial of any permission
if (report.isAnyPermissionPermanentlyDenied()) {
// show alert dialog navigating to Settings
//openSettingsDialog();
}
}
#Override
public void onPermissionRationaleShouldBeShown(List<com.karumi.dexter.listener.PermissionRequest> permissions, PermissionToken token) {
token.continuePermissionRequest();
}
}).
withErrorListener(new PermissionRequestErrorListener() {
#Override
public void onError(DexterError error) {
Toast.makeText(getApplicationContext(), "Some Error! ", Toast.LENGTH_SHORT).show();
}
})
.onSameThread()
.check();
}
}
public class MainActivity extends AppCompatActivity {
ImageView imageView1, imageView2;
private Button btn;
private static final String IMAGE_DIRECTORY = "/demonuts";
private int GALLERY = 1, CAMERA = 2;
**private int clickImage;**
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView1 = findViewById(R.id.image1);
imageView2 = findViewById(R.id.image2);
requestMultiplePermissions();
btn = findViewById(R.id.btn);
imageView1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
**clickImage=1;**
showPictureDialog();
}
});
imageView2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
**clickImage=2;**
showPictureDialog();
}
});
}
private void showPictureDialog() {
AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this);
pictureDialog.setTitle("Select Action");
String[] pictureDialogItems = {
"Select photo from gallery",
"Capture photo from camera"};
pictureDialog.setItems(pictureDialogItems,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
choosePhotoFromGallary();
break;
case 1:
takePhotoFromCamera();
break;
}
}
});
pictureDialog.show();
}
public void choosePhotoFromGallary() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, GALLERY);
}
private void takePhotoFromCamera() {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == this.RESULT_CANCELED) {
return;
}
switch (**clickImage**) {
case 1:
if (requestCode == GALLERY) {
if (data != null) {
Uri contentURI = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), contentURI);
String path = saveImage(bitmap);
Toast.makeText(MainActivity.this, "Image Saved!", Toast.LENGTH_SHORT).show();
imageView1.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Failed!", Toast.LENGTH_SHORT).show();
}
}
} else if (requestCode == CAMERA) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
imageView1.setImageBitmap(thumbnail);
saveImage(thumbnail);
Toast.makeText(MainActivity.this, "Image Saved!", Toast.LENGTH_SHORT).show();
}
break;
case 2:
if (requestCode == GALLERY) {
if (data != null) {
Uri contentURI = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), contentURI);
String path = saveImage(bitmap);
Toast.makeText(MainActivity.this, "Image Saved!", Toast.LENGTH_SHORT).show();
imageView2.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Failed!", Toast.LENGTH_SHORT).show();
}
}
} else if (requestCode == CAMERA) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
imageView2.setImageBitmap(thumbnail);
saveImage(thumbnail);
Toast.makeText(MainActivity.this, "Image Saved!", Toast.LENGTH_SHORT).show();
}
break;
}
}
public String saveImage(Bitmap myBitmap) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File wallpaperDirectory = new File(
Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);
// have the object build the directory structure, if needed.
if (!wallpaperDirectory.exists()) {
wallpaperDirectory.mkdirs();
}
try {
File f = new File(wallpaperDirectory, Calendar.getInstance()
.getTimeInMillis() + ".jpg");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
MediaScannerConnection.scanFile(this,
new String[]{f.getPath()},
new String[]{"image/jpeg"}, null);
fo.close();
Log.d("TAG", "File Saved::--->" + f.getAbsolutePath());
return f.getAbsolutePath();
} catch (IOException e1) {
e1.printStackTrace();
}
return "";
}
private void requestMultiplePermissions() {
Dexter.withActivity(this)
.withPermissions(
Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new MultiplePermissionsListener() {
#Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
// check if all permissions are granted
if (report.areAllPermissionsGranted()) {
Toast.makeText(getApplicationContext(), "All permissions are granted by user!", Toast.LENGTH_SHORT).show();
}
// check for permanent denial of any permission
if (report.isAnyPermissionPermanentlyDenied()) {
// show alert dialog navigating to Settings
//openSettingsDialog();
}
}
#Override
public void onPermissionRationaleShouldBeShown(List<com.karumi.dexter.listener.PermissionRequest> permissions, PermissionToken token) {
token.continuePermissionRequest();
}
}).
withErrorListener(new PermissionRequestErrorListener() {
#Override
public void onError(DexterError error) {
Toast.makeText(getApplicationContext(), "Some Error! ", Toast.LENGTH_SHORT).show();
}
})
.onSameThread()
.check();
}
}

Selected from gallery or camera photos not displaying in the ImageView

Camera taken photo or selected photo is not displaying in ImageView. I'm using the following code:
private void attachFile() {
final CharSequence[] items = {"Camera", "Gallery", "Cancel"};
AlertDialog.Builder builder;
builder = new AlertDialog.Builder(mContext);
builder.setTitle("Add Image");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if(items[i].equals("Camera")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
} else if (items[i].equals("Gallery")) {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent,"Select Photo"), SELECT_FILE);
} else if (items[i].equals("Cancel")) {
dialogInterface.dismiss();
}
}
});
builder.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Activity.RESULT_OK) {
if (requestCode == REQUEST_CAMERA && data != null) {
Log.d(TAG, "onActivityResult: done take photo");
Uri mImageCaptureUri = data.getData();
imageView.setImageURI(mImageCaptureUri);
/*Bundle bundle = data.getExtras();
final Bitmap bitmap = (Bitmap) bundle.get("data");
mOnphotoSelectedListener.getImageBitmap(bitmap);*/
} else if (requestCode == SELECT_FILE) {
Uri selectImageUri = data.getData();
mOnphotoSelectedListener.getImagePath(selectImageUri);
//imageView.setImageURI(selectImageUri);
//Picasso.with(mContext).load(selectImageUri).into(imageView);
//Picasso.with(this).load(selectImageUri).into(imageView);
}
}
}
i have this code i hope it will work for you its correct working
i set onclick for ImageProfile and i give to user picture + crop
i hope it will work for u
private void mImage_profileOnclick() {
int persmissonCheck = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA);
if (persmissonCheck == PackageManager.PERMISSION_DENIED) {
Req();
}else {
Dialog dialog = new Dialog(getActivity());
dialog.setContentView(R.layout.dialog_open_device);
Button pic, gal;
pic = (Button) dialog.findViewById(R.id.pick);
gal = (Button) dialog.findViewById(R.id.gallery);
pic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePicture, 0);
dialog.cancel();
dialog.dismiss();
}
});
gal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent pickPhoto = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto, 1);
dialog.cancel();
dialog.dismiss();
}
});
//dialog.create();
dialog.show();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent
imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case 0:
if (resultCode == RESULT_OK) {
Bundle extras = imageReturnedIntent.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
Dialog dialog = new Dialog(getActivity());
dialog.setContentView(R.layout.cropeimage);
CropImageView cropImageView = (CropImageView) dialog.findViewById(R.id.cropImageView);
Button button = (Button) dialog.findViewById(R.id.bac);
cropImageView.setImageBitmap(imageBitmap);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mImage_profile.setImageBitmap(cropImageView.getCroppedImage());
dialog.cancel();
dialog.dismiss();
}
});
//dialog.create();
dialog.show();
}
break;
case 1:
if (resultCode == RESULT_OK) {
Uri selectedImage = imageReturnedIntent.getData();
Dialog dialogs = new Dialog(getActivity());
dialogs.setContentView(R.layout.cropeimage);
CropImageView cropImageView = (CropImageView) dialogs.findViewById(R.id.cropImageView);
cropImageView.setImageUriAsync(selectedImage);
Button button = (Button) dialogs.findViewById(R.id.bac);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bitmap cropped = cropImageView.getCroppedImage();
mImage_profile.setImageBitmap(cropped);
dialogs.cancel();
dialogs.dismiss();
}
});
//dialogs.create();
dialogs.show();
}
break;
}
}
//#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void Req() {
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.CAMERA)) {
Toast.makeText(getActivity(), "شما مجوز استفاده از دوربین یا هر چیز دیگر را به برنامه نداده اید", Toast.LENGTH_SHORT).show();
}
else {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA}, 1);
mImage_profileOnclick();
} }
Used below code inside the onActivityResult
if (requestCode == Activity.RESULT_OK) {
File user_dp;
if (requestCode == REQUEST_CAMERA && data != null) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
user_dp = destination;
//update_profilepic is ImageView reference
Picasso.with(getContext()).load(user_dp).into(update_profilepic);
} else if (requestCode == SELECT_FILE) {
Bitmap bm = null;
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
//ivImage is image reference
ivImage.setImageBitmap(bm);
}
}
}
Instead of resultCode I have requestCode on the first line inside the if statement.

How to limit the item of listview in arrayadapter and use LoadPrevious header for loading more items

My Activity
public class UserComments extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_comments);
lv= (ListView) findViewById(R.id.Listview_common);
realm=Realm.getDefaultInstance();
Button btnLoadMore = new Button(this);
btnLoadMore.setText("Load Previous");
lv.addHeaderView(btnLoadMore);
btnLoadMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
realm = Realm.getDefaultInstance();
int position;
position = lv.getCheckedItemPosition();
position = position - 1;
lv.getItemAtPosition(position);
int last = lv.getLastVisiblePosition();
if (position == 1) {
System.out.println("previous is Impossilble");
setAdapter();
}
}
});
displayInputDialog();
imgattach=(ImageView) findViewById(R.id.imgattach);
imgattach.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectImage();
}
});
}
public void setAdapter()
{
lv= (ListView) findViewById(R.id.Listview_common);
final UserCommentRealmHelper helper=new UserCommentRealmHelper(realm);
helper.retrieveFromDB();
UserCommentArrayAdapter adapter=new UserCommentArrayAdapter(UserComments.this,helper.justRefresh());
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();
realmChangeListener=new RealmChangeListener() {
#Override
public void onChange() {
UserCommentArrayAdapter adapter=new UserCommentArrayAdapter(UserComments.this,helper.justRefresh());
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
};
realm.addChangeListener(realmChangeListener);
}
public void displayInputDialog()
{
descEditTxt= (EditText) findViewById(R.id.editwrite);
ImageView fab = (ImageView) findViewById(R.id.send);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String desc = descEditTxt.getText().toString();
UserComment s = new UserComment();
s.setDescription(desc);
UserCommentRealmHelper helper = new UserCommentRealmHelper(realm);
if (helper.save(s)) {
descEditTxt.setText("");
setAdapter();
}
else {
Toast.makeText(UserComments.this, "Invalid Data", Toast.LENGTH_SHORT).show();
}
}
});
}
public void cameraIntent() {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
intent.putExtra("camera",REQUEST_CAMERA);
}
public void galleryIntent() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);//
startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_FILE);
}
public void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library","Camera Video","Gallery Video",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(UserComments.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result=Utility.checkPermission(UserComments.this);
if (items[item].equals("Take Photo")) {
userChoosenTask="Take Photo";
if(result)
cameraIntent();
} else if (items[item].equals("Choose from Library")) {
userChoosenTask="Choose from Library";
if(result)
galleryIntent();
}
else if (items[item].equals("Camera Video")) {
userChoosenTask="Camera Video";
if(result)
startRecording();
}
else if (items[item].equals("Gallery Video")) {
userChoosenTask="Gallery Video";
if(result)
CaptureVideoFromGallery();
}
else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
public void CaptureVideoFromGallery()
{
Intent intent = new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Video"), SELECT_FILES);
}
public void startRecording()
{
java.util.Date date= new java.util.Date();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(date.getTime());
File mediaFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +"/"+timeStamp+".mp4");
/// File mediaFile = new File(Environment.getExternalStorageDirectory(),System.currentTimeMillis() + ".mp4");
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
fileUri = Uri.fromFile(mediaFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, VIDEO_CAPTURE);
}
/** Create a file Uri for saving an image or video */
private static Uri getOutputMediaFileUri(int type){
return Uri.fromFile(getOutputMediaFile(type));
}
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type){
// Check that the SDCard is mounted
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraVideo");
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("MyCameraVideo", "Failed to create directory MyCameraVideo.");
return null;
}
}
// Create a media file name
// For unique file name appending current timeStamp with file name
java.util.Date date= new java.util.Date();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(date.getTime());
File mediaFile;
if(type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_"+ timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case Utility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if(userChoosenTask.equals("Take Photo"))
cameraIntent();
else if(userChoosenTask.equals("Choose from Library"))
galleryIntent();
else if(userChoosenTask.equals("Video"))
startRecording();
} else {
}
break;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_FILE) {
onSelectFromGalleryResult(data);
}
else if (requestCode == REQUEST_CAMERA) {
onCaptureImageResult(data);
}
else if (requestCode == SELECT_FILES) {
onSelectFromGalleryVideoResults(data);
}
else if (requestCode == VIDEO_CAPTURE) {
Toast.makeText(this, "Video has been saved to:\n" + data.getData(), Toast.LENGTH_LONG).show();
SaveVideoData(String.valueOf(data.getData()));
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Video recording cancelled.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Failed to record video", Toast.LENGTH_LONG).show();
}
}
}
public void SaveVideoData(String data) {
try {
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
UserComment s = realm.createObject(UserComment.class);
s.setVideoUrl(data);
realm.commitTransaction();
realm.close();
UserCommentRealmHelper helper = new UserCommentRealmHelper(realm);
if (helper.save(s)) {
setAdapter();
}
else
{
Toast.makeText(UserComments.this, "Invalid Data", Toast.LENGTH_SHORT).show();
}
Log.d("path", data);
Log.d("working realm", "yes....");
Toast.makeText(getApplicationContext(),"Set Image URL"+data,Toast.LENGTH_LONG).show();
}
catch (Exception ex){
Toast.makeText(getApplicationContext(),"Nope its not done",Toast.LENGTH_LONG).show();
}
}
public String getRealPathFromURI(Uri contentUri) {
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
#SuppressWarnings("deprecation")
public void onSelectFromGalleryResult(Intent data) {
// Toast.makeText(UserComments.this,"My bm"+data,Toast.LENGTH_LONG).show();
SaveImageVideoData(String.valueOf(data.getData()),true);
}
#SuppressWarnings("deprecation")
public void onSelectFromGalleryVideoResults(Intent data) {
Toast.makeText(UserComments.this,"My bm"+data,Toast.LENGTH_LONG).show();
SaveVideoData(String.valueOf(data));
}
public void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.PNG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".png");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
//Toast.makeText(UserComments.this,"No Error",Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
//Toast.makeText(UserComments.this,"Error Arrived",Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
//Toast.makeText(UserComments.this,"Error Arrived again",Toast.LENGTH_LONG).show();
}
SaveImageVideoData(String.valueOf(destination),false);
//Toast.makeText(UserComments.this,"its done",Toast.LENGTH_LONG).show();
}
public void SaveImageVideoData(String data,boolean flag) {
try {
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
UserComment s = realm.createObject(UserComment.class);
s.setImageUrl(data);
s.setFlag(flag);
realm.commitTransaction();
realm.close();
UserCommentRealmHelper helper = new UserCommentRealmHelper(realm);
if (helper.save(s)) {
setAdapter();
}
else
{
Toast.makeText(UserComments.this, "Invalid Data", Toast.LENGTH_SHORT).show();
}
Log.d("path", data);
Log.d("working realm", "yes....");
Toast.makeText(getApplicationContext(),"Set Image URL"+data,Toast.LENGTH_LONG).show();
}
catch (Exception ex){
Toast.makeText(getApplicationContext(),"Nope its not done",Toast.LENGTH_LONG).show();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
realm.removeChangeListener(realmChangeListener);
realm.close();}
}
My Adapter Class
public class UserCommentArrayAdapter extends ArrayAdapter<UserComment> {
public UserCommentArrayAdapter(Context context, List<UserComment> objects){
super(context,0,objects);
this.context = context;
this.mInflater = LayoutInflater.from(context);
contactList = objects;
}
#Override
public UserComment getItem(int position) {
return contactList.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final UserCommentArrayAdapter.ViewHolder vh;
if (convertView == null) {
View view = mInflater.inflate(R.layout.item_commonchat, parent, false);
vh = UserCommentArrayAdapter.ViewHolder.create((LinearLayout) view);
view.setTag(vh);
} else {
vh = (UserCommentArrayAdapter.ViewHolder) convertView.getTag();
}
UserComment s = getItem(position);
if(s.getVideoUrl()!=null && s.getVideoUrl().length()>0)
{
Log.d("start error testing", "videooooooo");
vh.videoView.setVideoPath(s.getVideoUrl());
vh.videoView.setMediaController(new MediaController(context));
vh.videoView.start();
}
if(vh.txtbeencnt!=null) {
vh.txtbeencnt.setVisibility(View.VISIBLE);
vh.imageView.setVisibility(View.GONE);
vh.videoView.setVisibility(View.GONE);
vh.txtbeencnt.setText(s.getDescription());
}
if(s.getImageUrl() != null && s.getImageUrl().length()>0) {
boolean flag= s.isFlag();
if (flag == true) {
vh.imageView.setVisibility(View.VISIBLE);
vh.txtbeencnt.setVisibility(View.GONE);
vh.videoView.setVisibility(View.GONE);
Picasso.with(context).load(s.getImageUrl()).placeholder(R.mipmap.ic_launcher).into(vh.imageView);
Toast.makeText(context, "Got Gallery Image URL" + s.getImageUrl(), Toast.LENGTH_LONG).show();
} else if (flag == false) {
vh.imageView.setVisibility(View.VISIBLE);
vh.txtbeencnt.setVisibility(View.GONE);
vh.videoView.setVisibility(View.GONE);
Bitmap bitmap = BitmapFactory.decodeFile(s.getImageUrl());
vh.imageView.setImageBitmap(bitmap);
Toast.makeText(context, "Got Camera Image URL" + s.getImageUrl(), Toast.LENGTH_LONG).show();
}
}
return vh.rootView;
}
private static class ViewHolder {
public final LinearLayout rootView;
public final ImageView imageView;
public final TextView txtbeencnt;
public final VideoView videoView;
private ViewHolder(LinearLayout rootView,TextView txtbeencnt,ImageView imageView,VideoView videoView) {
this.rootView = rootView;
this.imageView = imageView;
this.txtbeencnt = txtbeencnt;
this.videoView=videoView;
}
public static UserCommentArrayAdapter.ViewHolder create(LinearLayout rootView) {
ImageView imageView = (ImageView) rootView.findViewById(R.id.img);
VideoView videoView = (VideoView) rootView.findViewById(R.id.videoView1);
TextView txtbeencnt = (TextView) rootView.findViewById(R.id.textdesc);
return new UserCommentArrayAdapter.ViewHolder(rootView,txtbeencnt,imageView,videoView);
}
}
}
Want the output like this
I searched a lot but everywhere found to use getcount() method which returns some specific integer value of item, but here I am not using custom adapter so what to do in this case?

push data camera to firebase android studio

Hi i'm having trouble entering data into firebase.
I can insert image data from album to firebase but i can not put image data from camera to firebase that i just photo. Please help me :)
//activitylapor
public class Lapor extends AppCompatActivity {
private ImageButton mSelectImage;
private EditText mPostNamaPelapor;
private EditText mPostNoTelpon;
private EditText mPostLokasiKejadian;
private EditText mPostKeteranganBencana;
private EditText mPostWaktuBencana;
private Uri mImageUri = null;
//private static final int GALLERY_REQUEST = 1;
private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
private String userChoosenTask;
private ImageView ivImage;
private StorageReference mStorage;
private DatabaseReference mDatabase;
private ProgressDialog mProgress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mStorage = FirebaseStorage.getInstance().getReference();
mDatabase = FirebaseDatabase.getInstance().getReference().child("Lapor");
mSelectImage = (ImageButton) findViewById(R.id.imageSelect);
mPostNamaPelapor = (EditText) findViewById(R.id.namaPelapor);
mPostNoTelpon = (EditText) findViewById(R.id.noTelpon);
mPostLokasiKejadian = (EditText) findViewById(R.id.lokasiKejadian);
mPostKeteranganBencana = (EditText) findViewById(R.id.keteranganBencana);
ivImage = (ImageView) findViewById(R.id.ivImage);
Button mSubmitBtn = (Button) findViewById(R.id.submitBtn);
mProgress = new ProgressDialog(this);
mSelectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
mSubmitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startPosting();
}
});
}
private void startPosting() {
mProgress.setMessage("Posting Lapor");
mProgress.show();
final String namapelapor_val = mPostNamaPelapor.getText().toString().trim();
final String notelpon_val = mPostNoTelpon.getText().toString().trim();
final String lokasikejadian_val = mPostLokasiKejadian.getText().toString().trim();
final String keteranganbencana_val = mPostKeteranganBencana.getText().toString().trim();
if (!TextUtils.isEmpty(namapelapor_val) && !TextUtils.isEmpty(notelpon_val) && !TextUtils.isEmpty(lokasikejadian_val)
&& !TextUtils.isEmpty(keteranganbencana_val) && mImageUri != null) {
StorageReference filepath = mStorage.child("Foto_Lapor").child(mImageUri.getLastPathSegment());
filepath.putFile(mImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
DatabaseReference newPost = mDatabase.push();
newPost.child("namapelapor").setValue(namapelapor_val);
newPost.child("nomortelpon").setValue(notelpon_val);
newPost.child("lokasikejadian").setValue(lokasikejadian_val);
newPost.child("keteranganbencana").setValue(keteranganbencana_val);
assert downloadUrl != null;
newPost.child("foto").setValue(downloadUrl.toString());
mProgress.dismiss();
startActivity(new Intent(Lapor.this, Terimakasih.class));
finish();
}
});
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults){
switch (requestCode) {
case Utility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (userChoosenTask.equals("Ambil Foto"))
cameraIntent();
else if (userChoosenTask.equals("Ambil dari Album"))
galleryIntent();
} else {
//code for deny
}
break;
}
}
private void selectImage() {
final CharSequence[] items = {"Ambil Foto", "Ambil dari Album",
"Batal"};
AlertDialog.Builder builder = new AlertDialog.Builder(Lapor.this);
builder.setTitle("Ambil Gambar");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result = Utility.checkPermission(Lapor.this);
if (items[item].equals("Ambil Foto")) {
userChoosenTask = "Ambil Foto";
if (result)
cameraIntent();
} else if (items[item].equals("Ambil dari Album")) {
userChoosenTask = "Ambil dari Album";
if (result)
galleryIntent();
} else if (items[item].equals("Batal")) {
dialog.dismiss();
}
}
});
builder.show();
}
private void galleryIntent() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);//
startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_FILE);
}
private void cameraIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE) {
Uri mImageUri = data.getData();
CropImage.activity(mImageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(4, 3)
.start(this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
mImageUri = result.getUri();
ivImage.setImageURI(mImageUri);
}
else if (requestCode == REQUEST_CAMERA) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
ivImage.setImageBitmap(thumbnail);
}
}
}
}
Thanks
Here is how i have done,its working for me,
In OnActivity Result,
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReferenceFromUrl(AppConstants.STORAGE_BUCKET);
final String imageName = "INSTA_"+System.currentTimeMillis()+".JPEG";
StorageReference imagePathReference;
imagePathReference = storageRef.child("---your storage path---"+ imageName);
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// downsizing image as it throws OutOfMemory Exception for larger images
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(), options);
ByteArrayOutputStream bos2 = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 60, bos2);
byte[] dataNew2 = bos2.toByteArray();
uploadTask = imagePathReference2.putBytes(dataNew2);
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
if(FirebaseAuth.getInstance().getCurrentUser() != null){
initToSendMessageToFirebase(fileUri, MESSAGE_TYPE_IMAGE,taskSnapshot,"",imageName);
}
}
});
On Clicking launch Camera,
Declare Uri fileUri ; -- global
private void launchCamera() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
try {
fileUri = Uri.fromFile(createImageFile());
} catch (IOException e) {
e.printStackTrace();
}
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(takePictureIntent, RC_CAMERA);
}
}
}

Wont be able to upload image into the server

I want to upload image into the database(c panel) in File format.For doing this at first I select an image from gallery or capture an image,set the image in an imageview and try to pass the image as an input parameter through api. But wont be able to send the image file.
Select image
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case Utility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if(userChoosenTask.equals("Take Photo"))
cameraIntent();
else if(userChoosenTask.equals("Choose from Library"))
galleryIntent();
} else {
//code for deny
}
break;
}
}
private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library", "Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(ProfileActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result=Utility.checkPermission(ProfileActivity.this);
if (items[item].equals("Take Photo")) {
userChoosenTask ="Take Photo";
if(result)
cameraIntent();
} else if (items[item].equals("Choose from Library")) {
userChoosenTask ="Choose from Library";
if(result)
galleryIntent();
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
private void galleryIntent()
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select File"),SELECT_FILE);
}
private void cameraIntent()
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
iv_profile.setImageBitmap(thumbnail);
ProfileImageAPI api = new ProfileImageAPI(this,this);
api.processProfileImage(AppController.getInstance().userId,destination,"photo.jpg");
}
#SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
Bitmap bm=null;
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
iv_profile.setImageBitmap(bm);
}
}
api.php
function process_updateUserProfileImage()
{
$user_id = isset($_REQUEST['user_id'])?$_REQUEST['user_id']:"";
if($user_id == "" ){
echo json_encode(array("error"=>"1", "error_type"=>"user updateUserProfile", "error_no" => "1009", "error_message" => "Input validation"));
exit;
}
$file_name = "";
$file_url = "";
if($_FILES["profile_image"]["name"]!="")
{
$file_name=time().$_FILES["profile_image"]["name"];
$tmp_name=$_FILES["profile_image"]["tmp_name"];
$file_type=$_FILES['profile_image']['type'];
$file_size=$_FILES['profile_image']['size'];
$upload_dir="../profile_image/";
fileUpload($upload_dir,$file_name,$tmp_name,$file_size,"image");
MakeThumbnail($upload_dir, $file_name ,100,100);
$file_url = SITE_URL.'profile_image/'.$file_name;
}
$sql = "update user set
`profile_image` = '".trim($file_url)."'
where user_id = '".$user_id."'
";
$rs = mysql_query($sql);
/*$userArr = array("success"=>"1", "sucess_type"=>"user registration", "success_message" => "User successfully registered");*/
$userInfo = mysql_fetch_array(mysql_query("select * from user where user_id = ".$user_id));
$userArr = array();
$userArr = array('user_id'=>$userInfo['user_id'],'profile_image'=>$userInfo['profile_image'],"success_message" => "profile image updated successfully");
echo json_encode($userArr);
exit();
}
ProfileImageApi class
public class ProfileImageAPI extends BaseAPI {
private Context mContext;
private NetworkCallback mCallback;
public ProfileImageAPI(Context context, NetworkCallback callback) {
super(context);
this.mContext = context;
this.mCallback = callback;
}
public void processProfileImage(final String userId, final File profileImg, final String imgName){
showProgressDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
ApiUtil.BASE_EDIT_PROFILE_IMAGE, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(ApiUtil.TAG_EDIT_PROFILE_IMAGE, response.toString());
mCallback.updateScreen(response,ApiUtil.TAG_EDIT_PROFILE_IMAGE);
hideProgressDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(ApiUtil.TAG_EDIT_PROFILE_IMAGE, "Error: " + error.getMessage());
mCallback.updateScreen("ERROR",ApiUtil.TAG_EDIT_PROFILE_IMAGE);
hideProgressDialog();
}
}){
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put(ApiUtil.PARAM_USER_ID,userId);
params.put(ApiUtil.PARAM_PROFILE_IMG,profileImg.toString());
params.put(ApiUtil.PARAM_IMG_NAME,imgName);
return params;
}
};
// Adding request to request queue
AppController ctrl = AppController.getInstance();
ctrl.addToRequestQueue(strReq, ApiUtil.TAG_EDIT_PROFILE_IMAGE);
}
}
Which library you have used for api calls.
1. Retrofit
2. Okhttp.
Retrofit MultiPartWebservice : "Retrofit" multiple images attached in one multipart request
OKHttp MultiPartWebservice :
how to use okhttp to upload a file?

Categories

Resources