About loading animations in Android - 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();
}
}

Related

Can't display image on ImageView in fragment

I am working on an android application in which I want to display the user details which includes the user's profile picture. Right now I was just trying to display the chosen image from the gallery on the ImageView. I searched over the Internet and found the following code but it doesn't seems to work for me. Here's the code:
public class UserProfile extends android.support.v4.app.Fragment {
UserLocalStore userLocalStore;
TextView etUsername, etGender, etMob, etMail;
Button bLogout;
ImageView imageView;
private static final int RESULT_LOAD = 999;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.user_profile_layout,container,false);
imageView = (ImageView) view.findViewById(R.id.userImage);
etUsername = (TextView) view.findViewById(R.id.etUsername);
etGender = (TextView) view.findViewById(R.id.etGender);
etMob = (TextView) view.findViewById(R.id.etMob);
etMail = (TextView) view.findViewById(R.id.etMail);
bLogout = (Button) view.findViewById(R.id.bLogout);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Create intent to Open Image applications like Gallery, Google Photos
Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start the Intent
startActivityForResult(galleryIntent, RESULT_LOAD);
}
});
bLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
userLocalStore.clearUserData();
userLocalStore.setUserLoggedIn(false);
Intent loginIntent = new Intent(getActivity(), SplashScreenTabbed.class);
startActivity(loginIntent);
}
});
try {
userLocalStore = new UserLocalStore(getActivity());
User user = userLocalStore.getLoggedInUser();
etUsername.setText(user.username);
etGender.setText(user.gender);
etMob.setText(user.mobile);
etMail.setText(user.email);
}catch (Exception e){e.printStackTrace();Toast.makeText(getActivity(),"Can't Connect To Server",Toast.LENGTH_SHORT).show();}
return view;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try{
// When an Image is picked
if (requestCode == RESULT_LOAD && resultCode == Activity.RESULT_OK && data != null) {
String path = getPathFromCameraData(data, this.getActivity());
Bitmap bitmap = BitmapFactory.decodeFile(path);
// Set the Image in ImageView after decoding the String
imageView.setImageBitmap(bitmap);
}
else
{
Toast.makeText(getActivity(), "Hey pick your image first",Toast.LENGTH_LONG).show();
}
} catch (Exception e)
{
Toast.makeText(getActivity(), "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
public static String getPathFromCameraData(Intent data, Context context) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = context.getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
return picturePath;
}
}
This code works when I am using it in an activity but it doesn't works in a fragment. If I pick the image from gallery then it goes into to catch() block or else it prints the message from the else part. Please help me out guys!
Here is my example. This is the tested code.
public class ImageSelector extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.createevent,container,false);
imgcover = (ImageView) view.findViewById(R.id.newcover_img);
btnupload = (Button) view.findViewById(R.id.newcover_upload);
btnupload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RESULT_LOAD_IMAGE);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data)
{
Uri selectedImg = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImg,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
imgcover = (ImageView) findViewById(R.id.newcover_img);
imgcover .setImageBitmap(BitmapFactory.decodeFile(picturePath));
cursor.close();
}
}
It help's you.
private static int RESULT_LOAD_IMG = 1;
imageView_profilepic = (ImageView).findViewById(R.id.imageView_Profile_Pic);
imageView_profilepic.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 Picture"), RESULT_LOAD_IMG);
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
try {
// When an Image is picked
if (requestCode == RESULT_LOAD_IMG && resultCode == getActivity().RESULT_OK
&& null != data) {
// Get the Image from data
decodeUri(data.getData());
} else {
Toast.makeText(getActivity(), "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(getActivity(), "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
public void decodeUri(Uri uri) {
ParcelFileDescriptor parcelFD = null;
try {
parcelFD = getActivity().getContentResolver().openFileDescriptor(uri, "r");
FileDescriptor imageSource = parcelFD.getFileDescriptor();
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFileDescriptor(imageSource, null, o);
// the new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE) {
break;
}
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
Bitmap bitmap = BitmapFactory.decodeFileDescriptor(imageSource, null, o2);
imageView_profilepic.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
// handle errors
} catch (IOException e) {
// handle errors
} finally {
if (parcelFD != null)
try {
parcelFD.close();
} catch (IOException e) {
// ignored
}
}
}
Well, it was a silly error/exception:
09-17 21:09:46.381 2292-2292/app.usrete.jayant.delvemitt W/System.errīš• java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media/16 from pid=2292, uid=10062 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
, I didn't added the read permission in the manifest. Adding it resolved the issue. By the way, Thank you guys for helping me out.

Unable To Pass Image Data Back To Android Application

I have been trying to pass the image data back to the app after capturing it. However, it always crash while trying to return to the my app.
The Code for starting the intent is:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgView = (ImageView) findViewById(R.id.ImageView);
upload = (Button) findViewById(R.id.Upload);
snap = (Button) findViewById(R.id.Snap);
select = (Button) findViewById(R.id.Select);
subject = (EditText) findViewById(R.id.Subject);
msg = (EditText) findViewById(R.id.Message);snap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String imageFilePath = Environment.getExternalStorageDirectory().
getAbsolutePath() + "/picture.jpg";
File imageFile = new File(imageFilePath);
Uri imageFileUri = Uri.fromFile(imageFile); // convert path to Uri
Intent it = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
it.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageFileUri);
startActivityForResult(it, CAMERA_RESULT);
}
});
}
The code to receive the intent is:
case CAMERA_RESULT:
if (resultCode == Activity.RESULT_OK) {
// Get Extra from the intent
Bundle extras = data.getExtras();
// Get the returned image from extra
Bitmap bmp = (Bitmap) extras.get("data");
imgView = (ImageView) findViewById(R.id.ImageView);
imgView.setImageBitmap(bmp);
}
break;
I also receive the following exceptions when the app crash occurred:
java.lang.RuntimeException: Unable to resume activity {com.NYP.estatemanagement/com.NYP.estatemanagement.MainActivity}: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=100, result=-1, data=null} to activity {com.NYP.estatemanagement/com.NYP.estatemanagement.MainActivity}: java.lang.NullPointerException
Try this is working like charm with me
private String selectedImagePath = "";
final private int PICK_IMAGE = 1;
final private int CAPTURE_IMAGE = 2;
public Uri setImageUri() {
// Store image in dcim
File file = new File(Environment.getExternalStorageDirectory() + "/DCIM/", "image" + new Date().getTime() + ".png");
Uri imgUri = Uri.fromFile(file);
this.imgPath = file.getAbsolutePath();
return imgUri;
}
public String getImagePath() {
return imgPath;
}
btnGallery.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, ""), PICK_IMAGE);
}
});
btnCapture.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, setImageUri());
startActivityForResult(intent, CAPTURE_IMAGE);
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_CANCELED) {
if (requestCode == PICK_IMAGE) {
selectedImagePath = getAbsolutePath(data.getData());
imgUser.setImageBitmap(decodeFile(selectedImagePath));
} else if (requestCode == CAPTURE_IMAGE) {
selectedImagePath = getImagePath();
imgUser.setImageBitmap(decodeFile(selectedImagePath));
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
public Bitmap decodeFile(String path) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 70;
// Find the correct scale value. It should be the power of 2.
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_SIZE && o.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeFile(path, o2);
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
public String getAbsolutePath(Uri uri) {
String[] projection = { MediaColumns.DATA };
#SuppressWarnings("deprecation")
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
this (below) from #Biraj Zalavadia (answer) :
public String getAbsolutePath(Uri uri) {
String[] projection = { MediaColumns.DATA };
#SuppressWarnings("deprecation")
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
and
String selectedImagePath = getAbsolutePath(data.getData());
is all I needed

I want to get location of picture taken in android emulator

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();
}

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