Unable to set image on Image view after uploading finish - android

public class FragProfile extends SherlockFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
root = inflater.inflate(R.layout.frag_profile, container, false);
Profile_image = (ImageView) root.findViewById(R.id.frag_imgProfile);
texusername = (TextView) root.findViewById(R.id.textView);
editbutton = (ImageView) root.findViewById(R.id.imageView1);
textcityname = (TextView) root.findViewById(R.id.textView1);
// ((HomeActivity) getActivity()).notifcationbadge
// .setVisibility(View.GONE);
// ((HomeActivity) getActivity()).badgeicon.setVisibility(View.GONE);
// ((HomeActivity) getActivity()).EditProfileimage
// .setVisibility(View.VISIBLE);
((HomeActivity) getActivity()).posttext.setVisibility(View.GONE);
editbutton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent editnameandcity = new Intent(getActivity(),
EditnameandCity.class);
startActivity(editnameandcity);
}
});
SharedPreferences preferences = getActivity().getSharedPreferences(
AppConstants.LOGIN_PREFS, Context.MODE_PRIVATE);
member_id = preferences.getString("Member_id", "");
// member_id = "409";
image_Url = "http://api.lociiapp.com/TransientStorage/" + member_id
+ ".jpg";
Profile_image.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
final String[] items = new String[] { "Take from camera",
"Select from gallery" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getActivity(), android.R.layout.select_dialog_item,
items);
AlertDialog.Builder builder = new AlertDialog.Builder(
getActivity());
builder.setTitle("Select Image");
builder.setAdapter(adapter,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) { // pick
// from
// camera
if (item == 0) {
Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
mImageCaptureUri = Uri.fromFile(new File(
Environment
.getExternalStorageDirectory(),
"tmp_avatar_"
+ String.valueOf(System
.currentTimeMillis())
+ ".jpg"));
intent.putExtra(
android.provider.MediaStore.EXTRA_OUTPUT,
mImageCaptureUri);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent,
PICK_FROM_CAMERA);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
} else { // pick from file
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent
.createChooser(intent,
"Complete action using"),
PICK_FROM_FILE);
}
}
});
final AlertDialog dialog = builder.create();
dialog.show();
return false;
}
});
return root;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK)
return;
switch (requestCode) {
case PICK_FROM_CAMERA:
doCrop();
break;
case PICK_FROM_FILE:
mImageCaptureUri = data.getData();
doCrop();
break;
case CROP_FROM_CAMERA:
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap photo = extras.getParcelable("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.PNG, 90, stream);
byte[] byte_arr = stream.toByteArray();
String image_str = Base64.encodeToString(byte_arr,
Base64.DEFAULT);
new Uploadimage().execute(image_str);
}
File f = new File(mImageCaptureUri.getPath());
if (f.exists())
f.delete();
break;
}
}
private void doCrop() {
final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setType("image/*");
List<ResolveInfo> list = getActivity().getPackageManager()
.queryIntentActivities(intent, 0);
int size = list.size();
if (size == 0) {
Toast.makeText(getActivity(), "Can not find image crop app",
Toast.LENGTH_SHORT).show();
return;
} else {
intent.setData(mImageCaptureUri);
intent.putExtra("outputX", 50);
intent.putExtra("outputY", 50);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
intent.putExtra("return-data", true);
if (size == 1) {
Intent i = new Intent(intent);
ResolveInfo res = list.get(0);
i.setComponent(new ComponentName(res.activityInfo.packageName,
res.activityInfo.name));
startActivityForResult(i, CROP_FROM_CAMERA);
} else {
for (ResolveInfo res : list) {
final CropOption co = new CropOption();
co.title = getActivity().getPackageManager()
.getApplicationLabel(
res.activityInfo.applicationInfo);
co.icon = getActivity().getPackageManager()
.getApplicationIcon(
res.activityInfo.applicationInfo);
co.appIntent = new Intent(intent);
co.appIntent
.setComponent(new ComponentName(
res.activityInfo.packageName,
res.activityInfo.name));
cropOptions.add(co);
}
CropOptionAdapter adapter = new CropOptionAdapter(
getActivity(), cropOptions);
AlertDialog.Builder builder = new AlertDialog.Builder(
getActivity());
builder.setTitle("Choose Crop App");
builder.setAdapter(adapter,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
startActivityForResult(
cropOptions.get(item).appIntent,
CROP_FROM_CAMERA);
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
if (mImageCaptureUri != null) {
getActivity().getContentResolver().delete(
mImageCaptureUri, null, null);
mImageCaptureUri = null;
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
}
#Override
public void onResume() {
super.onResume();
new username().execute();
// MtDrawableManager.getInstance().fetchBitmapOnThread(image_Url,
// Profile_image);
AQuery aq = new AQuery(context);
aq.id(Profile_image).image(image_Url, true, false, 0,
R.drawable.imge);
}
class Uploadimage extends AsyncTask<String, Void, Void> {
InputStream inputStream;
private static final String ALLOWED_URI_CHARS = "##&=*+-_.,:!?()/~'%";
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setTitle("Updating...");
pDialog.setMessage("Please wait...");
pDialog.setCanceledOnTouchOutside(false);
pDialog.show();
}
#Override
protected Void doInBackground(String... params) {
try {
String Url = Uri.encode(
"http://api.lociiapp.com/api/registration/ProfilePictureSaved?imageFile="
+ params[0] + "&member_id=" + member_id
+ "&picture_path=" + member_id + ".jpg",
ALLOWED_URI_CHARS);
HttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = new HttpGet(Url);
httppost.setHeader(
"Accept",
"text/html,application/xhtml+xml,application/xml,application/json;q=0.9,/;q=0.8");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
System.out.println("15aug " + result);
} catch (Exception e) {
pDialog.dismiss();
pDialog.cancel();
System.out.println("Error in http connection " + e.toString());
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
pDialog.dismiss();
pDialog.cancel();
// MtDrawableManager.getInstance().fetchBitmapOnThread(image_Url,
// Profile_image);
AQuery aq = new AQuery(context);
aq.id(Profile_image).image(image_Url, true, false, 0,
R.drawable.imge);
Log.e("Image Url**************", image_Url);
}
}
this is my code fro Uploading image to server Using camera and gallery . i am able to Upload image in both case successfully but there is Profile_image is image view where i have print that image after uploading to server i am getting image_url correctly in postexcute method but its displaying image on image view Profile_image please tell me where amd doing i am able to find issue even in on resume method i have putted same code for display image .

You can try image load through image loader.
Download image loader through below link.
http://www.androidhive.info/2012/07/android-loading-image-from-url-http/

Related

I have an image from ImageView and then i want to set to PDF, so how to use that?

I am new to Android application development. Using iText I had done the PDF creation and write on that created file now I want to create image to PDF from my `ImageView. Here's my code :
public class PdfCreatorActivity extends AppCompatActivity {
private static final String TAG = "PdfCreatorActivity";
private EditText mContentEditText;
private Button mCreateButton;
private File pdfFile;
final private int REQUEST_CODE_ASK_PERMISSIONS = 111;
Intent intent;
Uri fileUri;
Button btn_choose_image;
ImageView imageView;
Bitmap bitmap, decoded;
public final int REQUEST_CAMERA = 0;
public final int SELECT_FILE = 1;
int bitmap_size = 40; // image quality 1 - 100;
int max_resolution_image = 800;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pdfcreator);
btn_choose_image = (Button) findViewById(R.id.btn_choose_image);
imageView = (ImageView) findViewById(R.id.image_view);
btn_choose_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
mContentEditText = (EditText) findViewById(R.id.edit_text_content);
mCreateButton = (Button) findViewById(R.id.button_create);
mCreateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mContentEditText.getText().toString().isEmpty()){
mContentEditText.setError("Body is empty");
mContentEditText.requestFocus();
return;
}
try {
createPdfWrapper();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
}
});
}
private void selectImage() {
imageView.setImageResource(0);
final CharSequence[] items = {"Take Photo", "Choose from Library", "Cancel"};
android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(PdfCreatorActivity.this);
builder.setTitle("Add Photo!");
builder.setIcon(R.mipmap.ic_launcher);
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri();
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, REQUEST_CAMERA);
} else if (items[item].equals("Choose from Library")) {
intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_FILE);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.e("onActivityResult", "requestCode " + requestCode + ", resultCode " + resultCode);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == REQUEST_CAMERA) {
try {
Log.e("CAMERA", fileUri.getPath());
bitmap = BitmapFactory.decodeFile(fileUri.getPath());
setToImageView(getResizedBitmap(bitmap, max_resolution_image));
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == SELECT_FILE && data != null && data.getData() != null) {
try {
// mengambil gambar dari Gallery
bitmap = MediaStore.Images.Media.getBitmap(PdfCreatorActivity.this.getContentResolver(), data.getData());
setToImageView(getResizedBitmap(bitmap, max_resolution_image));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
// Untuk menampilkan bitmap pada ImageView
private void setToImageView(Bitmap bmp) {
//compress image
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, bitmap_size, bytes);
decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(bytes.toByteArray()));
//menampilkan gambar yang dipilih dari camera/gallery ke ImageView
imageView.setImageBitmap(decoded);
}
// Untuk resize bitmap
public Bitmap getResizedBitmap(Bitmap image, int maxSize) {
int width = image.getWidth();
int height = image.getHeight();
float bitmapRatio = (float) width / (float) height;
if (bitmapRatio > 1) {
width = maxSize;
height = (int) (width / bitmapRatio);
} else {
height = maxSize;
width = (int) (height * bitmapRatio);
}
return Bitmap.createScaledBitmap(image, width, height, true);
}
public Uri getOutputMediaFileUri() {
return Uri.fromFile(getOutputMediaFile());
}
private static File getOutputMediaFile() {
// External sdcard location
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "DeKa");
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.e("Monitoring", "Oops! Failed create Monitoring directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_DeKa_" + timeStamp + ".jpg");
return mediaFile;
}
}
This Code for Create PDF
private void createPdfWrapper() throws FileNotFoundException,DocumentException{
int hasWriteStoragePermission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (hasWriteStoragePermission != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!shouldShowRequestPermissionRationale(Manifest.permission.WRITE_CONTACTS)) {
showMessageOKCancel("You need to allow access to Storage",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_CODE_ASK_PERMISSIONS);
}
}
});
return;
}
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_CODE_ASK_PERMISSIONS);
}
return;
}else {
createPdf();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_ASK_PERMISSIONS:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission Granted
try {
createPdfWrapper();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
} else {
// Permission Denied
Toast.makeText(this, "WRITE_EXTERNAL Permission Denied", Toast.LENGTH_SHORT)
.show();
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new AlertDialog.Builder(this)
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", null)
.create()
.show();
}
private void createPdf() throws FileNotFoundException, DocumentException {
File docsFolder = new File(Environment.getExternalStorageDirectory() + "/Documents");
if (!docsFolder.exists()) {
docsFolder.mkdir();
Log.i(TAG, "Created a new directory for PDF");
}
pdfFile = new File(docsFolder.getAbsolutePath(),"HelloWorld.pdf");
OutputStream output = new FileOutputStream(pdfFile);
Document document = new Document();
PdfWriter.getInstance(document, output);
document.open();
document.add(new Paragraph(mContentEditText.getText().toString()));
document.close();
previewPdf();
}
private void previewPdf() {
PackageManager packageManager = getPackageManager();
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
if (list.size() > 0) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(pdfFile);
intent.setDataAndType(uri, "application/pdf");
startActivity(intent);
}else{
Toast.makeText(this,"Download a PDF Viewer to see the generated PDF",Toast.LENGTH_SHORT).show();
}
}
I don't know how to implement image can generates to PDF using iText,
Examples will be appreciable...
thanks in advance.
Use PdfDocument to generate pdf form View.
This class enables generating a PDF document from native Android content
Sample code:
// Create a new document
PdfDocument document = new PdfDocument();
// crate a page description
PageInfo pageInfo = new PageInfo.Builder(view.getWidth(), view.getHeight(), 1).create();
// start a page
Page page = document.startPage(pageInfo);
// draw on page
view.draw(page.getCanvas());
// finish the page
document.finishPage(page);
// generate pdf
new PdfGenerationTask().execute();
Use AsyncTask to generate pdf form document
private class PdfGenerationTask extends AsyncTask<Void, Void, File> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected File doInBackground(Void... params) {
return generatePdf();
}
#Override
protected void onPostExecute(File file) {
/* Dismiss the progress dialog after sharing */
}
}
generatePdf method
private File generatePdf(){
SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyyhhmmss");
String pdfName = "pdf"
+ sdf.format(Calendar.getInstance().getTime()) + ".pdf";
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pdf";
File dir = new File(path);
if(!dir.exists())
dir.mkdirs();
File file = new File(dir, pdfName);
if( document != null ){
// write the document content
try {
OutputStream out = new FileOutputStream(file);
if( out != null ){
document.writeTo(out);
// close the document
document.close();
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return file;
}
PdfDocument is easy and simple to use. PdfDocument required min sdk 19

Activity associated with image cropping libraries does not destroy

I have tried to solve this problem from many different links but does not worked for me.I am using Android Image Cropper library for cropping images. Whenever i click on the button "upload image" it start the cropping activity and when i am done the cropped image is set in an imageview in "upload image" activity and after clicking "Proceed" button login is successful and i am directed to login activity but when i back press the login activity the "Upload image" activity is still there and is not destroyed. I have another activity called Update Activity that uses this Cropping activity and that activity also behaves in the same manner. So i want the "Upload image" to destroy. Thanks in advance
package com.donateblood.blooddonation;
public class CroppingActivity extends AppCompatActivity {
private CropImageView mCropImageView;
public static Bitmap finalImage = null;
public static Bitmap newImage = null;
private Uri mCropImageUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crop);
mCropImageView = (CropImageView) findViewById(R.id.CropImageView);
}
/**
* On load image button click, start pick image chooser activity.
*/
public void onLoadImageClick(View view) {
startActivityForResult(getPickImageChooserIntent(), 200);
}
public void onSetImageClick(View view) {
if(UpdateActivity.UpdatingPhoto){
newImage = mCropImageView.getCroppedImage(200, 200);
try {
Intent intent = new Intent(getApplicationContext(), UpdateActivity.class);
startActivity(intent);
finish();
} catch (Exception e) {
Toast.makeText(CroppingActivity.this, "Oppss..Error occured.", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}else {
finalImage = mCropImageView.getCroppedImage(200, 200);
try {
Intent intent = new Intent(getApplicationContext(), UploadImage.class);
startActivity(intent);
finish();
} catch (Exception e) {
Toast.makeText(CroppingActivity.this, "Oppss..Error occured.", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}
/**
* Crop the image and set it back to the cropping view.
*/
public void onCropImageClick(View view) {
Bitmap cropped = mCropImageView.getCroppedImage(500, 500);
if (cropped != null)
mCropImageView.setImageBitmap(cropped);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
Uri imageUri = getPickImageResultUri(data);
// For API >= 23 we need to check specifically that we have permissions to read external storage,
// but we don't know if we need to for the URI so the simplest is to try open the stream and see if we get error.
boolean requirePermissions = false;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED &&
isUriRequiresPermissions(imageUri)) {
// request permissions and handle the result in onRequestPermissionsResult()
requirePermissions = true;
mCropImageUri = imageUri;
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
}
if (!requirePermissions) {
mCropImageView.setImageUriAsync(imageUri);
}
}
}
#Override
public void onBackPressed() {
UpdateActivity.UpdatingPhoto = false;
super.onBackPressed();
finish();
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
if (mCropImageUri != null && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mCropImageView.setImageUriAsync(mCropImageUri);
} else {
Toast.makeText(this, "Required permissions are not granted", Toast.LENGTH_LONG).show();
}
}
/**
* Create a chooser intent to select the source to get image from.<br/>
* The source can be camera's (ACTION_IMAGE_CAPTURE) or gallery's (ACTION_GET_CONTENT).<br/>
* All possible sources are added to the intent chooser.
*/
public Intent getPickImageChooserIntent() {
// Determine Uri of camera image to save.
Uri outputFileUri = getCaptureImageOutputUri();
List<Intent> allIntents = new ArrayList<>();
PackageManager packageManager = getPackageManager();
// collect all camera intents
Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
for (ResolveInfo res : listCam) {
Intent intent = new Intent(captureIntent);
intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage(res.activityInfo.packageName);
if (outputFileUri != null) {
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
}
allIntents.add(intent);
}
// collect all gallery intents
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
List<ResolveInfo> listGallery = packageManager.queryIntentActivities(galleryIntent, 0);
for (ResolveInfo res : listGallery) {
Intent intent = new Intent(galleryIntent);
intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage(res.activityInfo.packageName);
allIntents.add(intent);
}
// the main intent is the last in the list (Foolish android) so pickup the useless one
Intent mainIntent = allIntents.get(allIntents.size() - 1);
for (Intent intent : allIntents) {
if (intent.getComponent().getClassName().equals("com.android.documentsui.DocumentsActivity")) {
mainIntent = intent;
break;
}
}
allIntents.remove(mainIntent);
// Create a chooser from the main intent
Intent chooserIntent = Intent.createChooser(mainIntent, "Select source");
// Add all other intents
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, allIntents.toArray(new Parcelable[allIntents.size()]));
return chooserIntent;
}
/**
* Get URI to image received from capture by camera.
*/
private Uri getCaptureImageOutputUri() {
Uri outputFileUri = null;
File getImage = getExternalCacheDir();
if (getImage != null) {
outputFileUri = Uri.fromFile(new File(getImage.getPath(), "pickImageResult.jpeg"));
}
return outputFileUri;
}
/**
* Get the URI of the selected image from {#link #getPickImageChooserIntent()}.<br/>
* Will return the correct URI for camera and gallery image.
*
* #param data the returned data of the activity result
*/
public Uri getPickImageResultUri(Intent data) {
boolean isCamera = true;
if (data != null && data.getData() != null) {
String action = data.getAction();
isCamera = action != null && action.equals(MediaStore.ACTION_IMAGE_CAPTURE);
}
return isCamera ? getCaptureImageOutputUri() : data.getData();
}
/**
* Test if we can open the given Android URI to test if permission required error is thrown.<br>
*/
public boolean isUriRequiresPermissions(Uri uri) {
try {
ContentResolver resolver = getContentResolver();
InputStream stream = resolver.openInputStream(uri);
stream.close();
return false;
} catch (FileNotFoundException e) {
if (e.getCause() instanceof ErrnoException) {
return true;
}
} catch (Exception e) {
}
return false;
}
}
package com.donateblood.blooddonation;
public double longitude;
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.uploadimage);
code = (EditText) findViewById(R.id.code);
ButterKnife.inject(this);
myimage = CroppingActivity.finalImage;
CheckImage();
// Upload image ====================================
Btn_Upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), CroppingActivity.class);
startActivity(intent);
}
});
Btn_Proceed.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(code.length()==0){
Toast.makeText(getBaseContext(), "Enter verification code", Toast.LENGTH_LONG).show();
}
else {
Prcoess();
}
}
});
}
public void CheckImage(){
if(myimage!=null){
// set the image
// myimage = getRoundedShape(myimage);
Uri uri = getImageUri(myimage);
String url = getRealPathFromURI(uri);
File file = new File(url);
Picasso.with(UploadImage.this).load(file).resize(200,200).placeholder(R.drawable.user).error(R.drawable.error)
.transform(new CircleTransform()).centerCrop()
.into(ImageUpload);
}else {
encodedPhotoString= null;
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
public String getRealPathFromURI(Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = UploadImage.this.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
public Uri getImageUri( Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(UploadImage.this.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
// Processing and adding user to database from here ====================================
public void Prcoess(){
String userentered=code.getText().toString();
String sentcode = SignupActivity.Code;
// resize the image to store to database
//myimage= getResizedBitmap(myimage,200,200);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
myimage.compress(Bitmap.CompressFormat.JPEG, 50, stream);
byte[] byte_arr = stream.toByteArray();
encodedPhotoString = Base64.encodeToString(byte_arr, 0);
if(userentered.equals(sentcode) && encodedPhotoString!=null ){
new AddUserAsync().execute();
}
else {
Toast.makeText(getBaseContext(), "Wrong code or No image uploaded", Toast.LENGTH_LONG).show();
}
}
public class AddUserAsync extends AsyncTask<Void,Void,Void> {
JSONObject json =null;
boolean added = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(UploadImage.this);
pDialog.setMessage("Creating Account...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... voids) {
GetUserDetails();
GenerateGCMID();
email= email.trim().toLowerCase();
HashMap<String ,String> userDetails = new HashMap<>();
latitude = GPSTracker.getLatitude();
longitude = GPSTracker.getLongitude();
userDetails.put("ID",ID);
userDetails.put("Name",name);
userDetails.put("email",email);
userDetails.put("password",password);
userDetails.put("age",age);
userDetails.put("number",number);
userDetails.put("bloodgroup",bloodgroup);
userDetails.put("lat",latitude+"");
userDetails.put("longi",longitude+"");
userDetails.put("image",encodedPhotoString);
json = new HttpCall().postForJSON("http://abdulbasit.website/blood_app/Adduser.php",userDetails);
if(json!=null){
added = true;
}else {
added = false;
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
pDialog.dismiss();
if(added==true){
Toast.makeText(getBaseContext(), "Created Successfully", Toast.LENGTH_LONG).show();
onSignupSuccess();
}else {
Toast.makeText(getBaseContext(), "Error creating account. Try again", Toast.LENGTH_LONG).show();
}
}
}
public void GenerateGCMID(){
GCMClientManager pushClientManager = new GCMClientManager(this, "921544902369");
pushClientManager.registerIfNeeded(new GCMClientManager.RegistrationCompletedHandler() {
#Override
public void onSuccess(String registrationId, boolean isNewRegistration) {
Log.d("Registration id", registrationId);
ID = registrationId;
Log.e("reg",ID);
}
#Override
public void onFailure(String ex) {
super.onFailure(ex);
}
});
}
// Go to another activity on success ====================================
public void onSignupSuccess() {
// stop the service we got the latitude and longitude now
stopService(new Intent(this, GPSTracker.class));
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
finish();
}
// fetch user details ====================================
public void GetUserDetails(){
bloodgroup = SignupActivity.bloodgroup.toString();
name = SignupActivity.name.toString();
email = SignupActivity.email.toString();
password = SignupActivity.password.toString();
number = SignupActivity.number.toString();
age = SignupActivity.age.toString();
}
// Resize the image ====================================
public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth)
{
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// create a matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
// recreate the new Bitmap
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
return resizedBitmap;
}
}
check this method you are not finishing the UploadActivity here:-
Btn_Upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), CroppingActivity.class);
startActivity(intent);
UploadActivity.this.finish();
}
});

Return to MainActivity from another activity with error message

I am a bit new in android and I want to return to main activity from current activity with error message in dialog box.
I have written a script which make a call to rest api and if there is no data or error from response then i want to return to main activity with that error in dialog box.
Here is what i am doing
txtScan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
private void selectImage(){
final CharSequence[] items = { "Take Photo", "Choose from Library",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
} else if (items[item].equals("Choose from Library")) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(
Intent.createChooser(intent, "Select File"),
SELECT_FILE);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#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) {
byte[] b;
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
String fileName = File.separator + System.currentTimeMillis() + ".jpg";
filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + fileName;
System.out.println(filePath);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
/*FileInputStream fis = null;
try{
fis = new FileInputStream(filePath);
}catch (FileNotFoundException e){
e.printStackTrace();
}*/
b = bytes.toByteArray();
encode_string = Base64.encodeToString(b, Base64.DEFAULT);
System.out.println(b);
System.out.println(encode_string);
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();
}
try{
obj = new JSONObject();
obj.put("image",encode_string);
obj.put("api_key",API_SECRET);
System.out.println(obj.toString());
}catch (Throwable t){
t.printStackTrace();
}
new Image().execute();
//new LongRunningGetIO().execute();
//ivImage.setImageBitmap(thumbnail);
}
This function is In Image class
#Override
protected void onPostExecute(Void r) {
progressDialog.dismiss();
if(responseBody == "Api key does not found/match"){
//here i want to return to main activity with error
}else {
byte[] imageAsBytes = Base64.decode(encode_string.getBytes(), Base64.DEFAULT);
//System.out.println(imageAsBytes);
Intent intent = new Intent(getActivity().getApplicationContext(), ViewActivity.class);
intent.putExtra("filePath", imageAsBytes);
//intent.putExtra("data", text);
startActivity(intent);
}
}
Any idea thanks in advance
use startActivityForResults for passing value from current activity to previous activity
call Activity
Intent intent=new Intent(MainActivity.this,CurrentActivity.class);
startActivityForResult(intent, 2);
Handle result on MainActivity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 2
if(requestCode==2)
{
String error=data.getStringExtra("MESSAGE");
//display error
}
}
Async
#Override
protected void onPostExecute(Void r) {
progressDialog.dismiss();
if(responseBody == "Api key does not found/match"){
Intent intent=new Intent();
intent.putExtra("Error",message);
setResult(2,intent);
finish();
}else {
byte[] imageAsBytes = Base64.decode(encode_string.getBytes(), Base64.DEFAULT);
//System.out.println(imageAsBytes);
Intent intent = new Intent(getActivity().getApplicationContext(), ViewActivity.class);
intent.putExtra("filePath", imageAsBytes);
//intent.putExtra("data", text);
startActivity(intent);
}
}

Camera app gets closed in android marshmallow

I have created an app in which the user can take pics using their default camera.It works fine in older versions that is till lollipop but when i try to run the app in marshmallow the app gets closed.
So i have added some codes to give permission for the camera app by the user but even it is not working.
public class Cam extends Activity{
String receivingdata;
TextView namecat;
String amount,vat;
private static final String TAG = Cam.class.getSimpleName();
ImageButton imgview,imgchart,imgexit;
Boolean isInternetPresent = false;
ConnectionDetector cd;
AlertDialog alert;
ImageButton btgoback,btcaptureagain,btnpreview;
static TextView tv;
private ImageView imgPreview;
private ProgressDialog pDialog;
public static final int progress_bar_type = 0;
public static Bitmap bitmap;
final Context context=this;
ConnectionClass connectionClass;
private static final String IMAGE_CAPTURE_FOLDER = "Receipt";
private static final int CAMERA_PIC_REQUEST = 1111;
private static File file;
private Uri ImagefileUri;
private static final String PREF_FIRSTLAUNCH_HELP = "helpcmaera";
private boolean helpDisplayed = false;
private static final String LOGIN_URL = "http://balajee2777-001-site1.1tempurl.com/backup-07032016/Receiptphp/receipts.php";
#Override
public void onBackPressed() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
alertDialogBuilder.setTitle("Receipt");
alertDialogBuilder
.setMessage("Would you Like to go previous Page!")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
Intent i=new Intent(Cam.this,ListAct.class);
startActivity(i);
Cam.this.finish();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camcod);
cd = new ConnectionDetector(getApplicationContext());
isInternetPresent = cd.isConnectingToInternet();
Bundle b = getIntent().getExtras();
receivingdata = b.getString("key");
tv = (TextView)findViewById(R.id.camcodname);
tv.setText(receivingdata);
tv.setVisibility(View.INVISIBLE);
String[] bits=receivingdata.split("_");
String catname = bits[0];
String vatname= bits[1];
connectionClass= new ConnectionClass();
imgPreview = (ImageView) findViewById(R.id.imgpreview);
namecat=(TextView)findViewById(R.id.tvcatnamess);
namecat.setText(catname);
imgview=(ImageButton)findViewById(R.id.camlinearrecep);
imgchart=(ImageButton)findViewById(R.id.camlinearchart);
imgexit=(ImageButton)findViewById(R.id.camlinearexit);
btgoback=(ImageButton)findViewById(R.id.bgoback);
btnpreview=(ImageButton)findViewById(R.id.btnpreview);
btcaptureagain=(ImageButton)findViewById(R.id.bcaptureagain);
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
showcamera();
}else {
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
ImagefileUri = Uri.fromFile(getFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, ImagefileUri);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}
showHelpForFirstLaunch();
btgoback.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isInternetPresent) {
showreceipt();
}else{
neti();
}
}
});
btnpreview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(Cam.this,DeleteMainAct.class);
startActivity(i);
}
});
btcaptureagain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
showcamera();
}else {
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
ImagefileUri = Uri.fromFile(getFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, ImagefileUri);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}
}
});
imgview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set title
alertDialogBuilder.setTitle("Receipt");
// set dialog message
alertDialogBuilder
.setMessage("Would you Like to view receipts!")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
Intent i =new Intent(Cam.this,Viewreceipt.class);
startActivity(i);
Cam.this.finish();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
imgchart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set title
alertDialogBuilder.setTitle("Receipt");
// set dialog message
alertDialogBuilder
.setMessage("Would you Like to see report!")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
Intent i =new Intent(Cam.this,Chartboy.class);
startActivity(i);
Cam.this.finish();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
imgexit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set title
alertDialogBuilder.setTitle("Receipt");
// set dialog message
alertDialogBuilder
.setMessage("Would you Like to exit!")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if(requestCode==CAMERA_PIC_REQUEST){
if(grantResults[0]==PackageManager.PERMISSION_GRANTED){
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
ImagefileUri = Uri.fromFile(getFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, ImagefileUri);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}else{
Toast.makeText(this,"Camera permission not granted",Toast.LENGTH_SHORT).show();
}
}else{
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
private void showcamera() {
if(checkSelfPermission(android.Manifest.permission.CAMERA)== PackageManager.PERMISSION_GRANTED){
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
ImagefileUri = Uri.fromFile(getFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, ImagefileUri);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}else{
if(shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)){
Toast.makeText(this,"Camera permission is needed to show the preview",Toast.LENGTH_SHORT).show();
}
requestPermissions(new String[]{Manifest.permission.CAMERA}, CAMERA_PIC_REQUEST);
}
}
private void showHelpForFirstLaunch() {
helpDisplayed = getPreferenceValue(PREF_FIRSTLAUNCH_HELP, false);
if (!helpDisplayed) {
showHelp();
savePreference(PREF_FIRSTLAUNCH_HELP, true);
}else if(helpDisplayed){
return;
}
}
private void showHelp() {
final View instructionsContainer = findViewById(R.id.container_help);
instructionsContainer.setVisibility(View.VISIBLE);
instructionsContainer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
instructionsContainer.setVisibility(View.INVISIBLE);
}
});
}
private boolean getPreferenceValue(String key, boolean defaultValue) {
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
return preferences.getBoolean(key, defaultValue);
}
private void savePreference(String key, boolean value) {
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(key, value);
editor.commit();
}
private File getFile() {
String filepath = Environment.getExternalStorageDirectory().getPath();
file = new File(filepath, IMAGE_CAPTURE_FOLDER);
if (!file.exists()) {
file.mkdirs();
}
String names=tv.getText().toString();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
return new File(file + File.separator + names+"_"+timeStamp
+ ".jpg");
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_PIC_REQUEST) {
imgPreview.setVisibility(View.VISIBLE);
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int dw = size.x;
int dh = size.y;
// Load up the image's dimensions not the image itself
BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inJustDecodeBounds = true;
Bitmap bmp = BitmapFactory.decodeFile(ImagefileUri.getPath(),
bmpFactoryOptions);
int heightRatio = (int) Math.ceil(bmpFactoryOptions.outHeight
/ (float) dh);
int widthRatio = (int) Math.ceil(bmpFactoryOptions.outWidth
/ (float) dw);
Log.v("HEIGHTRATIO", "" + heightRatio);
Log.v("WIDTHRATIO", "" + widthRatio);
if (heightRatio > 1 && widthRatio > 1) {
if (heightRatio > widthRatio) {
// Height ratio is larger, scale according to it
bmpFactoryOptions.inSampleSize = heightRatio;
} else {
// Width ratio is larger, scale according to it
bmpFactoryOptions.inSampleSize = widthRatio;
}
}
// Decode it for real
bmpFactoryOptions.inJustDecodeBounds = false;
bmp = BitmapFactory.decodeFile(ImagefileUri.getPath(),
bmpFactoryOptions);
imgPreview.setImageBitmap(bmp);
}
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT).show();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
}
private void neti() {
final LayoutInflater layoutInflater = LayoutInflater.from(Cam.this);
final View promptView = layoutInflater.inflate(R.layout.connectionlost, null);
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Cam.this);
alertDialogBuilder.setView(promptView);
alertDialogBuilder.setCancelable(false);
final Button retry=(Button)promptView.findViewById(R.id.btnretry);
retry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent=getIntent();
finish();
startActivity(intent);
}
});
alert= alertDialogBuilder.create();
alert.show();
}
private void showreceipt() {
LayoutInflater repcard=LayoutInflater.from(Cam.this);
View promptView=repcard.inflate(R.layout.moneyreceipt,null);
AlertDialog.Builder alertDialogBuilder=new AlertDialog.Builder(Cam.this);
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setView(promptView);
final EditText amt=(EditText)promptView.findViewById(R.id.edamt);
final EditText vta=(EditText)promptView.findViewById(R.id.edvat);
final TextView tvs=(TextView)promptView.findViewById(R.id.tvamount);
final TextView tvat=(TextView)promptView.findViewById(R.id.tvvat);
tvs.setVisibility(View.INVISIBLE);
tvat.setVisibility(View.INVISIBLE);
amt.setRawInputType(Configuration.KEYBOARD_12KEY);
vta.setRawInputType(Configuration.KEYBOARD_12KEY);
final Button save=(Button)promptView.findViewById(R.id.btnmoneysave);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
tvs.setText(amt.getText().toString());
tvat.setText(vta.getText().toString());
amount=tvs.getText().toString();
vat=tvat.getText().toString();
// Toast.makeText(Cam.this, amount, Toast.LENGTH_LONG).show();
//Toast.makeText(Cam.this, vat, Toast.LENGTH_LONG).show();
detailsreceiptupload();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
private void detailsreceiptupload() {
String[] bits=receivingdata.split("_");
String catname = bits[0];
String cdte=bits[1];
String[] nyte=cdte.split("#");
String email=nyte[0];
String cdate=nyte[1];
String cimagetag=tv.getText().toString();
//String amt=tvs.getText().toString();
userLogin(catname, cdate,email,cimagetag,amount,vat);
}
private void userLogin(String catname, String cdate, String email, String cimagetag, String amount, String vat) {
class UserLoginClass extends AsyncTask<String,Void,String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(Cam.this, "Connecting to Cloud", null, true, true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
if(s.equalsIgnoreCase("success")) {
DoLogin dologin=new DoLogin();
dologin.execute("");
}
else
{
Toast.makeText(Cam.this,s,Toast.LENGTH_LONG).show();
}
}
#Override
protected String doInBackground(String... params) {
HashMap<String,String> data = new HashMap<>();
data.put("catname",params[0]);
data.put("cdate",params[1]);
data.put("email",params[2]);
data.put("cimagetag",params[3]);
data.put("amount",params[4]);
data.put("vat",params[5]);
RegisterUserClass ruc = new RegisterUserClass();
String result = ruc.sendPostRequest(LOGIN_URL,data);
return result;
}
}
UserLoginClass ulc = new UserLoginClass();
ulc.execute(catname,cdate,email,cimagetag,amount,vat);
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type:
pDialog = new ProgressDialog(this);
pDialog.setMessage("Processing...");
pDialog.setIndeterminate(true);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setProgressNumberFormat(null);
pDialog.setProgressPercentFormat(null);
pDialog.setCancelable(false);
pDialog.show();
return pDialog;
default:
return null;
}
}
class DoLogin extends AsyncTask<String,String,String> {
String z="";
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
#Override
protected String doInBackground(String... params) {
String ExternalStorageDirectoryPath = Environment
.getExternalStorageDirectory()
.getAbsolutePath();
String targetPath = ExternalStorageDirectoryPath + "/Receipt";
File targetDirector = new File(targetPath);
File[] files = targetDirector.listFiles();
File destinationdir = new File(Environment.getExternalStorageDirectory() ,"/CompressedImage");
if (!destinationdir.exists()) {
destinationdir.mkdirs();
}
for(File file1:files){
FileOutputStream fos=null;
try{
File file=new File(destinationdir,file1.getName());
fos=new FileOutputStream(file);
Bitmap bm = BitmapFactory.decodeFile(file1.getAbsolutePath());
bm.compress(Bitmap.CompressFormat.JPEG, 25, fos);
fos.flush();
fos.close();
MediaStore.Images.Media.insertImage(getContentResolver(), destinationdir.getPath(), file.getName(), file.getName());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return z;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
String ExternalStorageDirectoryPath = Environment
.getExternalStorageDirectory()
.getAbsolutePath();
String targetPath = ExternalStorageDirectoryPath + "/Receipt";
File targetDirector = new File(targetPath);
File[] files = targetDirector.listFiles();
for (File file : files) {
file.delete();
}
Intent i=new Intent(Cam.this,ReceiptGrid.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
Cam.this.finish();
dismissDialog(progress_bar_type);
}
protected void onProgressUpdate(String... progress) {
pDialog.setProgress(Integer.parseInt(progress[0]));
}
}}
I have used an condition to check the phones version.If it is marshmallow then i have given a method name showcamera to do the functions for marshmallow
ShowCamera:
private void showcamera() {
if(checkSelfPermission(android.Manifest.permission.CAMERA)== PackageManager.PERMISSION_GRANTED){
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
ImagefileUri = Uri.fromFile(getFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, ImagefileUri);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}else{
if(shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)){
Toast.makeText(this,"Camera permission is needed to show the preview",Toast.LENGTH_SHORT).show();
}
requestPermissions(new String[]{Manifest.permission.CAMERA}, CAMERA_PIC_REQUEST);
}
}

Android Send only 1 image via email in app

I have created a "Contact Us" page on my app and the idea is you have the option to send a picture to an already predetermind email address. The problem I have is its taking all the images from the gallery of the phone and sending them all in the email. All I want to do is send one picture. I cant seem to work out what to change to be able to just send one image. Is there anyone who could help?
Here is my code:
public class EmailActivity extends Activity {
Button send;
EditText address, subject, emailtext;
protected static final int CAMERA_PIC_REQUEST = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.email);
send=(Button) findViewById(R.id.emailsendbutton);
address=(EditText) findViewById(R.id.emailaddress);
subject=(EditText) findViewById(R.id.emailsubject);
emailtext=(EditText) findViewById(R.id.emailtext);
send.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if
(!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()))
{
}
File pngDir = new File(
Environment.getExternalStorageDirectory(),
"Android/data/com.random.jbrefurb/quote");
if (!pngDir.exists())
pngDir.mkdirs();
Uri pngUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{ "random#yahoo.co.uk"});
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject.getText());
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, emailtext.getText());
emailIntent.putExtra(android.content.Intent.EXTRA_STREAM, pngUri);
emailIntent.setType("image/jpeg");
EmailActivity.this.startActivity(Intent.createChooser(emailIntent, "Send mail..."));
}
});
Button back = (Button) findViewById(R.id.button1);
back.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// fire intent
finish(); // finish current activity
Intent austinIntent = new Intent(view.getContext(),
ContactActivity.class);
startActivityForResult(austinIntent, 0);
}
});
Button camera = (Button) findViewById(R.id.button2);
camera.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
;
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode== 0 && resultCode == Activity.RESULT_OK){
Bitmap x = (Bitmap) data.getExtras().get("data");
((ImageView)findViewById(R.id.imageView1)).setImageBitmap(x);
ContentValues values = new ContentValues();
values.put(Images.Media.TITLE, "title");
values.put(Images.Media.BUCKET_ID, "test");
values.put(Images.Media.DESCRIPTION, "test Image taken");
values.put(Images.Media.MIME_TYPE, "image/jpeg");
Uri uri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, values);
OutputStream outstream;
try {
outstream = getContentResolver().openOutputStream(uri);
x.compress(Bitmap.CompressFormat.JPEG, 100, outstream);
outstream.close();
} catch (FileNotFoundException e) {
//
}catch (IOException e){
//
}
} }
}
Many thanks in advance
this is code i used in my application try if you need help..
private OnClickListener shareemail=new OnClickListener(){
#Override
public void onClick(View v) {
String address = "your emailaddress";
File filee;
if(address.length()==0)
{
AlertDialog.Builder ab=new AlertDialog.Builder(null);
ab.setMessage("Email Address must not be empty!");
ab.setPositiveButton("OK", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
ab.show();
}
else
{
ArrayList<Uri> uris = new ArrayList<Uri>();
Uri u;
Intent emailSession = new Intent(Intent.ACTION_SEND_MULTIPLE);
emailSession.putExtra(Intent.EXTRA_SUBJECT,"your subject");
emailSession.setType("images/*");
emailSession.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] {address});
emailSession.putExtra(android.content.Intent.EXTRA_TEXT,"body text");
FileWriter fw;
BufferedWriter bw;
try{
filee = new File(path of image you want to send);
if(filee.exists())
{
Uri u1 = Uri.fromFile(filee);
uris.add(u1);
emailSession.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
startActivity(emailSession);
}
}
catch (ActivityNotFoundException e)
{
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}}
};

Categories

Resources