I'm sure there is an answer out there somewhere but I can't seem to find anything.
I am trying to make it so when the user clicks on an item on the app menu it will start an intent to the phone's gallery to choose an image of their choice to change the background of the app rather than the pre-set background image. Is there a way of doing this.
Here is what code I have but when I run it on my phone, the app crashes.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
Intent sendIntent = null;
if (id == R.id.action_settings) {
sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Try Out this new app...");
sendIntent.setType("text/plain");
startActivity(sendIntent);
}
PackageManager packageManager = getPackageManager();
List<ResolveInfo> activities = packageManager.queryIntentActivities(sendIntent, 0);
boolean isIntentSafe = activities.size() > 0;
String title = getResources().getString(R.string.chooser_title);
Intent chooser = Intent.createChooser(sendIntent, title);
if (sendIntent.resolveActivity(getPackageManager()) != null) {
startActivity(chooser);
}
//noinspection SimplifiableIfStatement
if (id == R.id.change_background){
Intent pictureIntent = new Intent();
pictureIntent.setType("image/*");
pictureIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(pictureIntent,
"Select Picture"), 0);
}
return true;
}}
To select the image from gallery
try {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
} catch (Exception e) {
Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
and in OnActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PICK_IMAGE:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImageUri = data.getData();
try {
// OI FILE Manager
String filemanagerstring = selectedImageUri.getPath();
// MEDIA GALLERY
String selectedImagePath = getPath(selectedImageUri);
if (selectedImagePath != null) {
filePath = selectedImagePath;
} else if (filemanagerstring != null) {
filePath = filemanagerstring;
} else {
Toast.makeText(getApplicationContext(), "Unknown path",
Toast.LENGTH_LONG).show();
}
if (filePath != null) {
decodeFile(filePath);
} else {
bitmap = null;
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Internal
error",Toast.LENGTH_LONG).show();
}
}
break;
default:
}
}
//Decode file() where you will get decoded file and then you can use that image
//file according to your requirement
public void decodeFile(String filePath) {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, 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 = BitmapFactory.decodeFile(filePath, o2);
image.setImageBitmap(bitmap);// set ImageView in your case set Layout
//background
}
Try This.
this is not best way to do it. But it fulfils your need.
xml File
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/rl"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="#+id/img"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="fitXY" />
<Button
android:id="#+id/butt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Click Me" />
Java FIle
public class MainActivity extends ActionBarActivity {
private static int RESULT_LOAD_IMG = 1;
String path = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.butt);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(Intent.createChooser(i, "Select Icon"),
RESULT_LOAD_IMG);
}
});
}
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);
}
#Override
protected void onActivityResult(int arg0, int arg1, Intent arg2) {
super.onActivityResult(arg0, arg1, arg2);
try {
if (arg0 == RESULT_LOAD_IMG && arg1 == RESULT_OK && null != arg2) {
Uri selectedImage = arg2.getData();
path = getPath(selectedImage);
ImageView iv = (ImageView) findViewById(R.id.img);
iv.setImageURI(selectedImage);
} else {
Toast.makeText(getApplicationContext(),
"You haven't picked Image", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Something went wrong",
Toast.LENGTH_LONG).show();
}
}
Related
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.
I am creating a chatting app. and i what to send content(Image, Video, Audio, Location, Contact) in Private and Group. for sending image i used this code
attachInfoButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
sendImage();
}
});
selectImage();
}
private void sendImage(){
File filePhoto = fileUpload;
System.out.println("Send Image..>>"+fileUpload);
Boolean fileIsPublic = true;
QBContent.uploadFileTask(filePhoto, fileIsPublic, null, new QBEntityCallbackImpl<QBFile>() {
#Override
public void onSuccess(QBFile file, Bundle params) {
String publicUrl = file.getPublicUrl();
System.out
.println("==========image uploaded success++++++++"
+ publicUrl);
Integer id = file.getId();
System.out
.println("===================image id+++++++++++"
+ id + "");
// create a message
QBChatMessage chatMessage = new QBChatMessage();
chatMessage.setProperty("save_to_history", "1"); // Save a message to history
// attach a photo
QBAttachment attachment = new QBAttachment("photo");
attachment.setId(file.getId().toString());
chatMessage.addAttachment(attachment);
// send a message
// ...
Intent a =new Intent(ImageFileAttachActivity.this, ChatActivity.class);
startActivity(a);
}
#Override
public void onError(List<String> errors) {
// error
}
});
// Intent a =new Intent(ImageFileAttachActivity.this, ChatActivity.class);
// startActivity(a);
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
// HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
// THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
public void decodeFile(String filePath) {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, 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 = BitmapFactory.decodeFile(filePath, o2);
attachInfoImage.setImageBitmap(bitmap);
}
private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(
ImageFileAttachActivity.this);
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) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
fileUpload=destination;
// new ProfilePicUpload().execute();
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();
}
attachInfoImage.setImageBitmap(thumbnail);
}
#SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
Uri selectedImageUri = data.getData();
String[] projection = { MediaColumns.DATA };
Cursor cursor = managedQuery(selectedImageUri, projection, null, null,
null);
int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
String selectedImagePath = cursor.getString(column_index);
fileUpload = new File(selectedImagePath);
// new ProfilePicUpload().execute();
Bitmap bm;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(selectedImagePath, options);
final int REQUIRED_SIZE = 200;
int scale = 1;
while (options.outWidth / scale / 2 >= REQUIRED_SIZE
&& options.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
options.inSampleSize = scale;
options.inJustDecodeBounds = false;
bm = BitmapFactory.decodeFile(selectedImagePath, options);
attachInfoImage.setImageBitmap(bm);
}
and I am successfully send Image to the QuickBlox server.and want to get this image for this code...
///////////////////// Download Image\\\\\\\\\\\\\\\\\\
#SuppressWarnings("deprecation")
public void processMessage(QBChat chat, final QBChatMessage chatMessage) {
for(QBAttachment attachment : chatMessage.getAttachments()){
final String fileId = attachment.getId();
QBContent.downloadFile(fileId, new QBEntityCallbackImpl<InputStream>() {
#SuppressWarnings("unused")
public void onComplete(Result result) {
if (result.isSuccess()) {
QBFileResult fileResult = (QBFileResult) result;
QBFile file = fileResult.getFile();
String fileURL = file.getPublicUrl();
}
}
});
}
}
But when i want to get that image then its create null pointer error.. i can't understand. where i'm wrong can you Please... and also provide example to create send content(Video, Audio, Location, Contact). Please Help me.
While selecting an image from a gallery in my application it doesn't crash but instead its unable to decode the stream of the path. Taking the picture directly from the camera is working fine but from the gallery its not here is my code in my activity result .
//enter code here
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Uri selectedImageUri = null;
String filePath = null;
switch (requestCode) {
case PICK_IMAGE:
if (resultCode == Activity.RESULT_OK)
{
selectedImageUri = data.getData();
name = getPath(selectedImageUri);
}
break;
case PICK_Camera_IMAGE:
if (resultCode == RESULT_OK) {
//use imageUri here to access the image
selectedImageUri = imageUri;
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT).show();
}
break;
}
if(selectedImageUri != null)
{
try
{
// OI FILE Manager
String filemanagerstring = selectedImageUri.getPath();
// MEDIA GALLERY
String selectedImagePath = getPath(selectedImageUri);
if (selectedImagePath != null) {
filePath = selectedImagePath;
} else if (filemanagerstring != null) {
filePath = filemanagerstring;
} else {
Toast.makeText(getApplicationContext(), "Unknown path",
Toast.LENGTH_LONG).show();
Log.e("Bitmap", "Unknown path");
}
if (filePath != null)
{
decodeFile(filePath);
} else {
bitmap = null;
}
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(), "Internal error",
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
}
public String getPath(Uri uri)
{
// just some safety built in
if( uri == null ) {
// TODO perform some logging or show user feedback
return null;
}
// try to retrieve the image from the media store first
// this will only work for images selected from gallery
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if( cursor != null ){
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
// this is our fallback here
return uri.getPath();
}
public void decodeFile(String filePath)
{
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, 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 = BitmapFactory.decodeFile(filePath, o2);
//imgView.setImageBitmap(bitmap);
}
any help would be appreciated.
In later versions of Android (KitKat and above), the format of Uris returned from the gallery picker has changed, and it's not always possible to get a file path from a Uri without a lot of hassle, and sometimes it's not possible at all. So, it's better just to decode the bitmap using the Uri directly.
Change your decodeFile() function to accept a Uri and decode the image using BitmapFactory.decodeStream(), like this:
public void decodeFile(Uri fileUri)
{
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(getContentResolver().openInputStream(fileUri), 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 = BitmapFactory.decodeStream(getContentResolver().openInputStream(fileUri), null, o2);
//imgView.setImageBitmap(bitmap);
}
Then you can simplify your onActivityResult() code to this:
if(selectedImageUri != null)
{
try
{
decodeFile(selectedImageUri);
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(), "Internal error",
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
If you have problems obtaining a valid Uri, see the accepted answer for this question for how to obtain a Uri inside OnActivityResult() with correct permissions on KitKat and above.
Well I choose another approach for this thing. You cannot diffrentiate between you chose a picture from gallery or from a Camera Intent.
Here is my code.
public class Chooser extends Activity {
ImageView imageView1;
private Uri outputFileUri;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_main);
imageView1 = (ImageView) this.findViewById (R.id.imageView1);
Button frag1 = (Button) this.findViewById (R.id.frag1);
frag1.setOnClickListener (new OnClickListener () {
#Override
public void onClick (View v) {
choosePic (null);
}
});
}
public void choosePic (View view) {
// Determine Uri of camera image to save.
final File root = new File (Environment.getExternalStorageDirectory () + File.separator + "DCIM/Camera" + File.separator);
root.mkdirs ();
final String fname = "image_" + getRandomName () + ".jpeg";
final File sdImageMainDirectory = new File (root, fname);
outputFileUri = Uri.fromFile (sdImageMainDirectory);
// Camera.
final List<Intent> cameraIntents = new ArrayList<Intent> ();
final Intent captureIntent = new Intent (android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
captureIntent.putExtra (MediaStore.EXTRA_OUTPUT, Uri.fromFile (sdImageMainDirectory));
final PackageManager packageManager = getPackageManager ();
final List<ResolveInfo> listCam = packageManager.queryIntentActivities (captureIntent, 0);
for (ResolveInfo res : listCam) {
final String packageName = res.activityInfo.packageName;
final Intent intent = new Intent (captureIntent);
intent.setComponent (new ComponentName (res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage (packageName);
intent.putExtra (MediaStore.EXTRA_OUTPUT, outputFileUri);
cameraIntents.add (intent);
}
// Filesystem.
final Intent galleryIntent = new Intent ();
galleryIntent.setType ("image/*");
galleryIntent.setAction (Intent.ACTION_GET_CONTENT);
// Chooser of filesystem options.
final Intent chooserIntent = Intent.createChooser (galleryIntent, "Select Source");
// Add the camera options.
chooserIntent.putExtra (Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray (new Parcelable[] {}));
startActivityForResult (chooserIntent, 1);
}
#Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
super.onActivityResult (requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
final boolean isCamera;
if (data == null) {
isCamera = true;
}
else {
final String action = data.getAction ();
if (action == null) {
isCamera = false;
}
else {
isCamera = action.equals (android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
}
}
Uri selectedImageUri;
if (isCamera) {
selectedImageUri = outputFileUri;
}
else {
selectedImageUri = data == null ? null : data.getData ();
}
imageView1.setImageURI (selectedImageUri);
}
}
}
public String getRandomName () {
Random r = new Random (); // just create one and keep it around
String alphabet = "abcdefghijklmnopqrstuvwxyz1234567890";
final int N = 10;
StringBuilder sb = new StringBuilder ();
for (int i = 0; i < N; i++) {
sb.append (alphabet.charAt (r.nextInt (alphabet.length ())));
}
return sb.toString ();
}
I have two buttons and two imageview. When I click on first button, it opens and uploads image.How to do for second button click and load image. My code is as follows
private static final int PICK_IMAGE = 1;
upload1=(Button)findViewById(R.id.uploadimage1);
upload2=(Button)findViewById(R.id.uploadimage2);
imgView1=(ImageView)findViewById(R.id.image1);
imgView2=(ImageView)findViewById(R.id.image2);
upload1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, "Select Picture"),
PICK_IMAGE);
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"No image found", Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PICK_IMAGE:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImageUri = data.getData();
String filePath = null;
try {
// OI FILE Manager
String filemanagerstring = selectedImageUri.getPath();
// MEDIA GALLERY
String selectedImagePath = getPath(selectedImageUri);
if (selectedImagePath != null) {
filePath = selectedImagePath;
} else if (filemanagerstring != null) {
filePath = filemanagerstring;
} else {
Toast.makeText(getApplicationContext(), "Unknown path",
Toast.LENGTH_LONG).show();
Log.e("Bitmap", "Unknown path");
}
if (filePath != null) {
decodeFile(filePath);
} else {
bitmap = null;
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Internal error",
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
break;
default:
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
// HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
// THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
public void decodeFile(String filePath) {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, 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 = BitmapFactory.decodeFile(filePath, o2);
//first image i have uploaded by using first button
imgView1.setImageBitmap(bitmap);
}
Now my question is for second button how to upload in second image. Please help me to solve this issue. Thanks in advance
private static final int PICK_IMAGE = 1;
private static final int PICK_IMAGE_2 = 2;
set click listener for upload2. Then in OnClick()
startActivityForResult(Intent.createChooser(intent, "Select Picture"),
PICK_IMAGE_2);
Finally, In onActivityResult()
case PICK_IMAGE :
imgView1.setImageBitmap(bitmap);
break;
CASE PICK_IMAGE :
imgView2.setImageBitmap(bitmap);
break;
You can simply repeat what you did for the first button, but with a different request code, so you know how to use the data in onActivityResult :
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_2);
}
I use below code to start camera capture on a button clicked:
Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(captureIntent, Variables.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
On activity result, I just simply start "crop" activity.
if (requestCode == Variables.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
picUri = data.getData();
performCrop();
}
When the camera first started, I pressed the back button to go back to the caller activity (A.class). And then start another activity, say B.class, causes window leak. Sometimes when B.class is called, the screen keep flashing....What's wrong with the code? Please HELP! Many thanks.
There are some alert dialogs I created, but it is already dismissed.
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;
}