I want to get location of picture taken in android emulator - android

Here is what I tried so far. Don't know what I am getting wrong. Works just fine for taking picture and setting it to ImageView, but crashes when I add the code that tries to get location.
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
if (resultCode == Activity.RESULT_OK && requestCode == ACTION_IMAGE_CAPTURE) {
new Thread(new Runnable() {
public void run() {
final Bitmap bm = (Bitmap) data.getExtras().get("data");
Uri uri = data.getData();
Cursor cursor = getBaseContext().getContentResolver().query(uri, new String[] {android.provider.MediaStore.Images.ImageColumns.LATITUDE,
android.provider.MediaStore.Images.ImageColumns.LONGITUDE }, null, null, null);
if(cursor.moveToFirst()){
int latIndex = cursor.getColumnIndex(android.provider.MediaStore.Images.ImageColumns.LATITUDE);
int lonIndex = cursor.getColumnIndex(android.provider.MediaStore.Images.ImageColumns.LONGITUDE);
double longitu = cursor.getDouble(lonIndex);
double latitu = cursor.getDouble(latIndex);
Log.d("picloc", longitu + " "+latitu);
}
iv.post(new Runnable() {
public void run() {
iv.setImageBitmap(bm);
}
});
}
}).start();
}

Related

About loading animations in Android

I'm using the image picking intent to get an image from the user's gallery and put it in an ImageView after I compress it.
It takes about 2 seconds on my device but it will most likely take more or less time on other devices. I was wondering how I can set a loading animation that would last for exactly the time needed to load the image (so not a pre-set duration) in the ImageView?
Here is the code where I handle the image. Everything works, I just don't know how to use the loading animation for this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
File file = new File(picturePath);
picturePath = file.getAbsolutePath();
Bitmap bitmap = BitmapFactory.decodeFile(picturePath);
Bitmap bitmapRotated = rotateBitmap(bitmap, picturePath);
if(bitmapRotated != null)
bitmap = bitmapRotated;
imageToSave = Bitmap.createScaledBitmap(bitmap, image.getWidth(), image.getHeight(), false);
image.setImageBitmap(imageToSave);
thumbnailToSave = image.getThumbnail();
space.setVisibility(View.GONE);
edit.setVisibility(View.VISIBLE);
save.setVisibility(View.GONE);
image.setEditing(false);
imageChanged = true;
thumbnailChanged = true;
image.invalidate();
}
}
You should use Android progress bar.
You can create a bar that represents how far the operation is going to take or just a spinning wheel.
You need to create a thread for your task and another thread for updating the progress bar.
public class MyAndroidAppActivity extends Activity {
Button btnStartProgress;
ProgressDialog progressBar;
private int progressBarStatus = 0;
private Handler progressBarHandler = new Handler();
private long fileSize = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addListenerOnButton();
}
public void addListenerOnButton() {
btnStartProgress = (Button) findViewById(R.id.btnStartProgress);
btnStartProgress.setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
// prepare for a progress bar dialog
progressBar = new ProgressDialog(v.getContext());
progressBar.setCancelable(true);
progressBar.setMessage("File downloading ...");
progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressBar.setProgress(0);
progressBar.setMax(100);
progressBar.show();
//reset progress bar status
progressBarStatus = 0;
//reset filesize
fileSize = 0;
new Thread(new Runnable() {
public void run() {
while (progressBarStatus < 100) {
// process some tasks
progressBarStatus = doSomeTasks();
// your computer is too fast, sleep 1 second
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Update the progress bar
progressBarHandler.post(new Runnable() {
public void run() {
progressBar.setProgress(progressBarStatus);
}
});
}
// ok, file is downloaded,
if (progressBarStatus >= 100) {
// sleep 2 seconds, so that you can see the 100%
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// close the progress bar dialog
progressBar.dismiss();
}
}
}).start();
}
});
}
// file download simulator... a really simple
public int doSomeTasks() {
while (fileSize <= 1000000) {
fileSize++;
if (fileSize == 100000) {
return 10;
} else if (fileSize == 200000) {
return 20;
} else if (fileSize == 300000) {
return 30;
}
// ...add your own
}
return 100;
}
}
Here is my solution with a ProgressDialog, using the same code.
#Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
final ProgressDialog progress = new ProgressDialog(this);
progress.setMessage(getResources().getString(R.string.loading));
progress.show();
Thread mThread = new Thread() {
#Override
public void run() {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
File file = new File(picturePath);
picturePath = file.getAbsolutePath();
Bitmap bitmap = BitmapFactory.decodeFile(picturePath);
Bitmap bitmapRotated = rotateBitmap(bitmap, picturePath);
if(bitmapRotated != null)
bitmap = bitmapRotated;
imageToSave = Bitmap.createScaledBitmap(bitmap, image.getWidth(), image.getHeight(), false);
thumbnailToSave = image.getThumbnail();
imageChanged = true;
thumbnailChanged = true;
PictureActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
image.setEditing(false);
space.setVisibility(View.GONE);
edit.setVisibility(View.VISIBLE);
save.setVisibility(View.GONE);
image.setImageBitmap(imageToSave);
image.invalidate();
}
});
progress.dismiss();
}
};
mThread.start();
}
}

pick an image from gallery in android studio?

someone can tell me what the problem, it is not working, so please help fast i really need:
imagePick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Contact Image"),1);
}
});
public void onActivityResult(int reqCode, int resCode, Intent data)
{
if(resCode==RESULT_OK)
{
if(reqCode==1) {
imageURI=data.getData();
iv.setImageURI(data.getData());
}
}
}
This is working for me.
private final static int SELECT_PHOTO = 12345;
imagePick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Here we need to check if the activity that was triggers was the Image Gallery.
// If it is the requestCode will match the LOAD_IMAGE_RESULTS value.
// If the resultCode is RESULT_OK and there is some data we know that an image was picked.
if (requestCode == SELECT_PHOTO && resultCode == RESULT_OK && data != null) {
// Let's read picked image data - its URI
Uri pickedImage = data.getData();
// Let's read picked image path using content resolver
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(pickedImage, filePath, null, null, null);
cursor.moveToFirst();
String imagePath = cursor.getString(cursor.getColumnIndex(filePath[0]));
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);
imageView.setImageBitmap(bitmap);
// Do something with the bitmap
// At the end remember to close the cursor or you will end with the RuntimeException!
cursor.close();
}
}

upload the picture from gallery or camera by alertdialogue

this is my program, I think it is no problem about the alertdialogue.
But after I select the photo in my gallery, the picture isn't changed.
It is still the original photo that I set in the ImageView.
Could someboby help me know where the problem is?
public class MainActivity extends Activity{
ImageView img_logo;<br>
protected static final int CAMERA_REQUEST = 0;
protected static final int GALLERY_PICTURE = 1;
private Intent pictureActionIntent = null;
Bitmap bitmap;
Uri selectedImageUri;
String selectedPath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img_logo= (ImageView) findViewById(R.id.homepic);
img_logo.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startDialog();
}
});
}
private void startDialog() {
AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(this);
myAlertDialog.setTitle("Upload Pictures Option");
myAlertDialog.setMessage("How do you want to set your picture?");
myAlertDialog.setPositiveButton("Gallery",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
pictureActionIntent = new Intent(
Intent.ACTION_GET_CONTENT, null);
pictureActionIntent.setType("image/*");
pictureActionIntent.putExtra("return-data", true);
startActivityForResult(pictureActionIntent,
GALLERY_PICTURE);
}
});
myAlertDialog.setNegativeButton("Camera",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
pictureActionIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(pictureActionIntent,
CAMERA_REQUEST);
}
});
myAlertDialog.show();
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if(data.getData() != null){
selectedImageUri = data.getData();
}else{
Log.d("selectedPath1 : ","Came here its null !");
Toast.makeText(getApplicationContext(), "failed to get Image!", 500).show();
}
if (requestCode == 100 && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
selectedPath = getPath(selectedImageUri);
img_logo.setImageURI(selectedImageUri);
Log.d("selectedPath1 : " ,selectedPath);
}
if (requestCode == 10)
{
selectedPath = getPath(selectedImageUri);
img_logo.setImageURI(selectedImageUri);
Log.d("selectedPath1 : " ,selectedPath);
}
}
Toast toast = Toast.makeText(MainActivity.this, "hiiiii", Toast.LENGTH_LONG);
toast.show();
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}
Try this way,hope this will help you to solve your problem.
public class MainActivity extends Activity {
ImageView img_logo;
protected static final int CAMERA_REQUEST = 0;
protected static final int GALLERY_PICTURE = 1;
private String imgPath;
private String selectedPath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img_logo = (ImageView) findViewById(R.id.homepic);
img_logo.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startDialog();
}
});
}
private void startDialog() {
AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(this);
myAlertDialog.setTitle("Upload Pictures Option");
myAlertDialog.setMessage("How do you want to set your picture?");
myAlertDialog.setPositiveButton("Gallery",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, ""), GALLERY_PICTURE);
}
}
);
myAlertDialog.setNegativeButton("Camera",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, setImageUri());
startActivityForResult(intent, CAMERA_REQUEST);
}
}
);
myAlertDialog.show();
}
public Uri setImageUri() {
// Store image in dcim
File file = new File(Environment.getExternalStorageDirectory() + "/DCIM/", "image" + new Date().getTime() + ".jpg");
Uri imgUri = Uri.fromFile(file);
this.imgPath = file.getAbsolutePath();
return imgUri;
}
public String getImagePath() {
return imgPath;
}
public String getAbsolutePath(Uri uri) {
if (Build.VERSION.SDK_INT >= 19) {
String id = uri.getLastPathSegment().split(":")[1];
final String[] imageColumns = {MediaStore.Images.Media.DATA};
final String imageOrderBy = null;
Uri tempUri = getUri();
Cursor imageCursor = managedQuery(tempUri, imageColumns,
MediaStore.Images.Media._ID + "=" + id, null, imageOrderBy);
if (imageCursor.moveToFirst()) {
return imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA));
} else {
return null;
}
} else {
String[] projection = {MediaStore.MediaColumns.DATA};
#SuppressWarnings("deprecation")
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
}
private Uri getUri() {
String state = Environment.getExternalStorageState();
if (!state.equalsIgnoreCase(Environment.MEDIA_MOUNTED))
return MediaStore.Images.Media.INTERNAL_CONTENT_URI;
return MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == CAMERA_REQUEST) {
img_logo.setImageBitmap(BitmapFactory.decodeFile(getImagePath()));
selectedPath = getImagePath();
} else if (requestCode == GALLERY_PICTURE) {
img_logo.setImageBitmap(BitmapFactory.decodeFile(getAbsolutePath(data.getData())));
selectedPath = getAbsolutePath(data.getData());
}
Toast toast = Toast.makeText(MainActivity.this, "hiiiii", Toast.LENGTH_LONG);
toast.show();
}
}
}
Add this <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> in AndroidManifest.xml

Android - ImageView won't show pic taken with camera

Please bear with me... I've been looking around for DAYS for a working, bare-bones piece of code that starts the camera activity, takes a picture, and places it on a simple ImageView >.< The code posted below fires up the activity and takes the pic alright, but the image does not show on the ImageView! Just what is missing? :'(
public class MainActivity extends Activity
{
private static final int PICK_IMAGE = 0;
private static final int PICK_IMAGE_FROM_GALLERY = 1;
private Button mBtnCamera, mBtnGallery, mBtnCancel;
private ImageView mImageView;
private Uri mURI;
private String mPhotoPath;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImageView = (ImageView) findViewById(R.id.imgDisplayImage);
mBtnCamera = (Button) findViewById(R.id.btnPhotoCamera);
mBtnGallery = (Button) findViewById(R.id.btnPhotoGallery);
mBtnCancel = (Button) findViewById(R.id.btnCancel);
mBtnCamera.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Intent camera = new Intent();
camera.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
camera.putExtra("crop", "true");
File f = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
mURI = Uri.fromFile(new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "myFile.jpg"));
camera.putExtra(MediaStore.EXTRA_OUTPUT, mURI);
startActivityForResult(camera, PICK_IMAGE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == PICK_IMAGE)
{
// Result includes a Bitmap thumbnail?
if (data != null)
{
if (data.hasExtra("data"))
{
//Bitmap thumbnail = data.getParcelableExtra("data");
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
mImageView.setImageBitmap(thumbnail);
}
}
// If there is no thumbnail data, the image will have been stored in target output URI.
else
{
Cursor cursor = getContentResolver().query(
Media.EXTERNAL_CONTENT_URI, new String[]
{
Media.DATA,
Media.DATE_ADDED,
MediaStore.Images.ImageColumns.ORIENTATION
},
Media.DATE_ADDED,
null,
"date_added ASC"
);
if (cursor != null && cursor.moveToFirst())
{
do
{
mURI = Uri.parse(cursor.getString(cursor.getColumnIndex(Media.DATA)));
mPhotoPath = mURI.toString();
}
while (cursor.moveToNext());
cursor.close();
}
// Resize full image to fit out in image view.
int width = mImageView.getWidth();
int height = mImageView.getHeight();
BitmapFactory.Options factoryOptions = new BitmapFactory.Options();
factoryOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(/*mURI.getPath()*/ mPhotoPath, factoryOptions);
int imageWidth = factoryOptions.outWidth;
int imageHeight = factoryOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(
imageWidth/width,
imageHeight/height
);
// Decode the image file into a Bitmap sized to fill view
factoryOptions.inJustDecodeBounds = false;
factoryOptions.inSampleSize = scaleFactor;
factoryOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(/*mURI.getPath()*/ mPhotoPath, factoryOptions);
mImageView.setImageBitmap(bitmap);
}
}
}
}
I had same problem in some devices of samsung android Then I implemented logic to get path of captured photo.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == PICK_IMAGE)
{
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST_CODE);
Cursor cursor = getContentResolver().query(Media.EXTERNAL_CONTENT_URI, new String[]{Media.DATA, Media.DATE_ADDED, MediaStore.Images.ImageColumns.ORIENTATION}, Media.DATE_ADDED, null, "date_added ASC");
if(cursor != null && cursor.moveToFirst())
{
do {
uri = Uri.parse(cursor.getString(cursor.getColumnIndex(Media.DATA)));
photoPath = uri.toString();
}while(cursor.moveToNext());
cursor.close();
}
if(photoPath != null) {
Bitmap bitmap = BitmapFactory.decodeFile(photoPath);
///Do Implement your logic whatever you want.
mImageView.setImageBitmap(bitmap);
}
}
}
Tried and tested to work on a Galaxy S3 phone. Credit to TGMCians for his help.
public class MainActivity extends Activity
{
private static final int PICK_IMAGE = 0;
private static final int PICK_IMAGE_FROM_GALLERY = 1;
private Button mBtnCamera, mBtnGallery, mBtnCancel;
private ImageView mImageView;
private Uri mURI;
private String mPhotoPath;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImageView = (ImageView) findViewById(R.id.imgDisplayImage);
mBtnCamera = (Button) findViewById(R.id.btnPhotoCamera);
mBtnGallery = (Button) findViewById(R.id.btnPhotoGallery);
mBtnCancel = (Button) findViewById(R.id.btnCancel);
mBtnCamera.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Intent camera = new Intent();
camera.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
camera.putExtra("crop", "true");
File f = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
mURI = Uri.fromFile(new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "myFile.jpg"));
camera.putExtra(MediaStore.EXTRA_OUTPUT, mURI);
startActivityForResult(camera, PICK_IMAGE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == Activity.RESULT_OK)
{
if (requestCode == PICK_IMAGE)
{
Cursor cursor = getContentResolver().query(
Media.EXTERNAL_CONTENT_URI, new String[]
{
Media.DATA,
Media.DATE_ADDED,
MediaStore.Images.ImageColumns.ORIENTATION
},
Media.DATE_ADDED,
null,
"date_added ASC"
);
if (cursor != null && cursor.moveToFirst())
{
do
{
mURI = Uri.parse(cursor.getString(cursor.getColumnIndex(Media.DATA)));
mPhotoPath = mURI.toString();
}
while (cursor.moveToNext());
cursor.close();
}
if (data != null)
{
if (data.hasExtra("data"))
{
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
mImageView.setImageBitmap(thumbnail);
}
else
{
System.out.println("Intent bundle does not have the 'data' Extra");
int width = mImageView.getWidth();
int height = mImageView.getHeight();
BitmapFactory.Options factoryOptions = new BitmapFactory.Options();
factoryOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(/*mURI.getPath()*/ mPhotoPath, factoryOptions);
int imageWidth = factoryOptions.outWidth;
int imageHeight = factoryOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(
imageWidth/width,
imageHeight/height
);
// Decode the image file into a Bitmap sized to fill view
factoryOptions.inJustDecodeBounds = false;
factoryOptions.inSampleSize = scaleFactor;
factoryOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(/*mURI.getPath()*/ mPhotoPath, factoryOptions);
mImageView.setImageBitmap(bitmap);
}
}
}
}
else
{
System.out.println("Picture taking activity NOT returning RESULT_OK");
}
}
}
Try adding
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
(and a slight delay) right inside the
if (requestCode == PICK_IMAGE)
block. I think the problem might be that your device isn't refreshing the Media store correctly.
(of course the better action would be to use MediaScanner to scan your file)

dismiss() method of Progress dialog is not working

May be same question is encountered to you before, I am sorry for that but I really need to ask this.I am trying to show Progress dialog and then dismissing it But I am not able to do it. I have searched a lot and tried many ways but cant really get through. I am uploading images after picking from gallery. and during upload i want to show the dialog and after uploading dialog should be dismissed here is my code.
public class FaceActivity extends Activity {
private static int RESULT_LOAD_IMAGE = 1;
private Button upbtn;
public Bitmap bm;
public ByteArrayOutputStream bos;
public byte[] bitmapdata;
public String picturePath;
private ProgressDialog pd;
private BitmapFactory.Options options;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_face);
//pd = new ProgressDialog(FaceActivity.this);
upbtn = (Button) findViewById(R.id.buttonLoadPicture);
upbtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
options = new BitmapFactory.Options();
// will results in a much smaller image than the original
options.inSampleSize = 8;
upload();
}
}
public void upload(){
// Here I am showing the dialog
pd = ProgressDialog.show(FaceActivity.this, "Please Wait", "Loading...", true, false);
bm = BitmapFactory.decodeFile(picturePath);
bos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 40 , bos);
bitmapdata = bos.toByteArray();
ParseFile file = new ParseFile("pic.jpg", bitmapdata);
file.saveInBackground();
ParseObject po = new ParseObject("Images");
po.put("Images", file);
po.saveInBackground();
ImageView imageView = (ImageView) findViewById(R.id.targetimage);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath,options));
// want to dismiss dialog here
pd.dismiss();
Toast.makeText(this, "Image Uploaded Successfully", Toast.LENGTH_LONG).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_face, menu);
return true;
}
}
try to do that in asyc task.
private class asynUpload extends AsyncTask<String, Void, Integer> {
protected Integer doInBackground(String... params) {
try {
runOnUiThread(new Runnable() {
public void run() {
pd = ProgressDialog.show(FaceActivity.this, "Please Wait", "Loading...", true, false);
}
});
bm = BitmapFactory.decodeFile(picturePath);
bos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 40 , bos);
bitmapdata = bos.toByteArray();
ParseFile file = new ParseFile("pic.jpg", bitmapdata);
file.saveInBackground();
ParseObject po = new ParseObject("Images");
po.put("Images", file);
po.saveInBackground();
ImageView imageView = (ImageView) findViewById(R.id.targetimage);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath,options));
} catch (Exception e) {
return 0;
}
return 1;
}
protected void onPostExecute(Integer result) {
try {
runOnUiThread(new Runnable() {
public void run() {
pd.dismiss();
}
});
} catch (Exception e) {}
super.onPostExecute(result);
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data)
{
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
options = new BitmapFactory.Options();
// will results in a much smaller image than the original
options.inSampleSize = 8;
// use the task here
new asynUpload().execute();
}
}
You can look here for the idea you've been looking for implementing a background process: doInBackground not working in Android fragment

Categories

Resources