gallery.class
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
public class gallery extends Fragment {
private static final int PICK_FROM_GALLERY = 1;
RelativeLayout gallerylayout;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.mainfragment, container, false);
gallerylayout = (RelativeLayout) v.findViewById(R.id.gallery_layout);
gallerylayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
fireGallery();
}
});
return v;
}
private void fireGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_FROM_GALLERY);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PICK_FROM_GALLERY:
String[] all_path = data.getStringArrayExtra("all_path");
System.out.println("all_path " + all_path); //Returns null
System.out.println("Data " + data.getExtras()); //Returns null
break;
}
}
}
The data in onActivityResult is always null, please correct me if anything wrong with my code. As mentioned both logs inside onActivityResult returns null. Note i am extending Fragment not activity.
Try this, you may get data from it:
#Override
protected void onActivityResult (int requestCode,int resultCode,Intent data){
super.onActivityResult (requestCode,resultCode,data);
try{
// When an Image is picked
if (requestCode == PICK_FROM_GALLERY && resultCode == RESULT_OK
&& null != data){
// Get the Image from data
Uri selectedImage = data.getData ();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
// Get the cursor
Cursor cursor = getContentResolver ().query (selectedImage,
filePathColumn,null,null,null);
// Move to first row
cursor.moveToFirst ();
int columnIndex = cursor.getColumnIndex (filePathColumn[0]);
String imgDecodableString = cursor.getString (columnIndex);
cursor.close ();
Log.e ("Image Path",imgDecodableString);
Toast.makeText (this,"You have picked Image" ,
Toast.LENGTH_LONG).show ();
}
else{
Toast.makeText (this,"You haven't picked Image",
Toast.LENGTH_LONG).show ();
}
}
catch (Exception e){
Toast.makeText (this,"Something went wrong",Toast.LENGTH_LONG)
.show ();
Log.e ("Exception",e.toString ());
}
}
you can reading :http://inthecheesefactory.com/blog/how-to-fix-nested-fragment-onactivityresult-issue/en?fb_action_ids=780839882030502&fb_action_types=og.comments
Create ActivityResultEvent.java
import android.content.Intent;
/**
* Created by nuuneoi on 3/12/2015.
*/
public class ActivityResultEvent {
private int requestCode;
private int resultCode;
private Intent data;
public ActivityResultEvent(int requestCode, int resultCode, Intent data) {
this.requestCode = requestCode;
this.resultCode = resultCode;
this.data = data;
}
public int getRequestCode() {
return requestCode;
}
public void setRequestCode(int requestCode) {
this.requestCode = requestCode;
}
public int getResultCode() {
return resultCode;
}
public void setResultCode(int resultCode) {
this.resultCode = resultCode;
}
public Intent getData() {
return data;
}
public void setData(Intent data) {
this.data = data;
}
}
Create ActivityResultBus.java
import android.os.Handler;
import android.os.Looper;
import com.squareup.otto.Bus;
/**
* Created by nuuneoi on 3/12/2015.
*/
public class ActivityResultBus extends Bus {
private static ActivityResultBus instance;
public static ActivityResultBus getInstance() {
if (instance == null)
instance = new ActivityResultBus();
return instance;
}
private Handler mHandler = new Handler(Looper.getMainLooper());
public void postQueue(final Object obj) {
mHandler.post(new Runnable() {
#Override
public void run() {
ActivityResultBus.getInstance().post(obj);
}
});
}
}
// >>>>>>>>>>>>>> override onActivityResult on Activity
public class MainActivity extends ActionBarActivity {
...
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
ActivityResultBus.getInstance().postQueue(
new ActivityResultEvent(requestCode, resultCode, data));
}
...
}
In fragment :
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Don't forget to check requestCode before continuing your job
if (requestCode == 12345) {
// Do your job
tvResult.setText("Result Code = " + resultCode);
}
}
#Override
public void onStart() {
super.onStart();
ActivityResultBus.getInstance().register(mActivityResultSubscriber);
}
#Override
public void onStop() {
super.onStop();
ActivityResultBus.getInstance().unregister(mActivityResultSubscriber);
}
private Object mActivityResultSubscriber = new Object() {
#Subscribe
public void onActivityResultReceived(ActivityResultEvent event) {
int requestCode = event.getRequestCode();
int resultCode = event.getResultCode();
Intent data = event.getData();
onActivityResult(requestCode, resultCode, data);
}
};
if (requestCode == PICK_FROM_GALLERY && resultCode == Activity.RESULT_OK && null!=data)
{
Bitmap photo;
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().getContentResolver().query(
selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
if (picturePath != null) {
Log.v("", picturePath);
cursor.close();
photo = BitmapFactory.decodeFile(picturePath);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 100, baos);
photo = Bitmap.createScaledBitmap(photo, 1200, 1200, true);
this.data = baos.toByteArray();
chooseImage.setImageBitmap(photo);
}
else {
Utilities.showToast(getActivity(),
"This image is not on your device");
}
}
if You want to get picture from the gallery then you should use this function
Related
I want to scan QR Code in fragment.
But onActivityResult is not calling.
Fragment.java
#Override
public View onCreateView(LayoutInflater inflater ,ViewGroup container ,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate( R.layout.fragment_offer ,container ,false );
scanOffer = view.findViewById( R.id.scanOffer );
scanOffer.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View view) {
scanBarcode();
}
} );
return view;
}
public void scanBarcode() {
/** This method will listen the button clicked passed form the fragment **/
Intent intent = new Intent(getContext(),CaptureActivity.class);
intent.setAction("com.google.zxing.client.android.SCAN");
intent.putExtra("SAVE_HISTORY", false);
startActivityForResult(intent, 0);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0) {
if (resultCode == Activity.RESULT_OK) {
uniqueCode = data.getStringExtra("SCAN_RESULT");
Log.d(TAG, "contents: " + uniqueCode);
Toast.makeText( getContext() ,uniqueCode ,Toast.LENGTH_SHORT ).show();
// callAddStoreContestParticipantService();
} else if (resultCode == Activity.RESULT_CANCELED) {
Log.d(TAG, "RESULT_CANCELED");
}
}
}
Please help me.
onActivityResult() is not calling
CaptureActivity.class opens Qr after scanning onActivityResult() is not calling
Try below code for barcode scan and also override on activity result in parent activity
private static final int BARCODE_REQUEST = 312;
private void startBarcode() {
//IntentIntegrator.forFragment(getActivity().initiateScan()); // `this` is the current Fragment
IntentIntegrator integrator = new IntentIntegrator(getActivity()) {
#Override
protected void startActivityForResult(Intent intent, int code) {
Fragment.this.startActivityForResult(intent, BARCODE_REQUEST); // REQUEST_CODE override
}
};
//IntentIntegrator integrator = new IntentIntegrator(getActivity());
//IntentIntegrator.forSupportFragment(this);
integrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);
integrator.setPrompt("Scan a barcode");
integrator.setCameraId(0); // Use a specific camera of the device
integrator.setBeepEnabled(true);
integrator.setBarcodeImageEnabled(true);
integrator.setOrientationLocked(false);
integrator.setTimeout(15000);
integrator.initiateScan();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case BARCODE_REQUEST:
IntentResult Result = IntentIntegrator.parseActivityResult(IntentIntegrator.REQUEST_CODE, resultCode, data);
if (Result != null) {
if (Result.getContents() == null) {
Timber.i("cancelled scan");
showSnackbar("cancelled scan", true);
} else {
Timber.i("Scanned");
showSnackbar("Code scan successfully", false);
try {
long id = Long.parseLong(Result.getContents());
// getFood(id);
searchBarcode(Result.getContents());
} catch (Exception e) {
e.printStackTrace();
}
// searchBarcode(Result.getContents());
//getFood(Long.valueOf(mItem.get(position - 1).getID()));
}
} else {
showSnackbar("Barcode not scanned", true);
Timber.i("Barcode Result is NULL");
super.onActivityResult(requestCode, resultCode, data);
}
break;
}
}
You can get reference from this example:Barcode Scanner
you have to call getActivity().startActivityForResult(intent, 0);
in your fragment
and in your activity you in onActivityResultMethod() you have to call yourfragmnt.onActivityResult()
I am Developing a that takes a video from Storage via intent. So i am Facing this problem
Problem:-
java.lang.illegalArgumentException:inputFile not exists:/document/video:105065
Code:-
Intent
public void videotext( View v ) {
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.setType("video/*");
startActivityForResult(i, request);
}
On Activity Result
#Override
protected void onActivityResult( int requestCode, int resultCode, Intent data ) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == request) {
uri = data.getData();
mSurfaceView.setVideoURI(uri);
//MediaController media1=new MediaController(this);
media.setAnchorView(mSurfaceView);
mSurfaceView.setMediaController(media);
mSurfaceView.start();
inputFile=new File(uri.getPath());
inputFile=inputFile.getAbsoluteFile();
VideoCompress(inputFile,OutputFile);
}
}
}
VideoCompress is a method to Compress video..
public void VideoCompress(File inputFile,File OutputFile)
{
GiraffeCompressor.create() //two implementations: mediacodec and ffmpeg,default is mediacodec
.input(inputFile) //set video to be compressed
.output(OutputFile) //set compressed video output
.bitRate(2073600)//set bitrate 码率
.resizeFactor(Float.parseFloat(String.valueOf(1.0)))//set video resize factor 分辨率缩放,默认保持原分辨率
// .watermark("/sdcard/videoCompressor/watermarker.png")//add watermark(take a long time) 水印图片(需要长时间处理)
.ready()
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<GiraffeCompressor.Result>() {
#Override
public void onCompleted() {
Toast.makeText(UploadVideo.this,"Compressing",Toast.LENGTH_LONG).show();
}
#Override
public void onError(Throwable e) {
Toast.makeText(UploadVideo.this,e.toString(),Toast.LENGTH_LONG).show();
}
#Override
public void onNext(GiraffeCompressor.Result s) {
Toast.makeText(UploadVideo.this,"Compressed",Toast.LENGTH_LONG).show();
}
});
}
Use this Method to get Path for your Uri :
public static String getPath(Context context,Uri uri) {
Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
use it like mSurfaceView.setVideoURI(data.getData());
I'm beginner in android, In my project I want to add texts and image from gallery, from add activity and send to main activity to display in a list view,
this is code for add button on main Activity
Intent intentForAdd = new Intent(getApplicationContext(),addActivity.class);
startActivityForResult(intentForAdd,requestcode2);
And this the code for add Activity
boolean ownImage = false;
final private int PICK_IMAGE = 1;
byte[] imageDat;
Button buttonAdd,cameraB;
ImageView imageAdd;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
idAdd = findViewById(R.id.idAdd);
nameAdd = findViewById(R.id.nameAdd);
cameraB = findViewById(R.id.cameraB);
buttonAdd = findViewById(R.id.buttonAdd);
imageAdd = findViewById(R.id.imageAdd);
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int idA = Integer.parseInt(idAdd.getText().toString());
String nameA = nameAdd.getText().toString();
Intent intent = new Intent();
intent.putExtra("NameAdd", nameA);
intent.putExtra("IdAdd", idA);
intent.putExtra("ImageAdd",imageData);
setResult(Activity.RESULT_OK, intent);
finish();
}
});
cameraB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(Intent.createChooser(intent,"Choose Image From"),PICK_IMAGE);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != Activity.RESULT_CANCELED){
if (requestCode == PICK_IMAGE){
try{
Uri uri = data.getData();
Bitmap bitmap;
bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
imageAdd.setImageBitmap(bitmap);
ownImage = true;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG,100,byteArrayOutputStream);
imageData = byteArrayOutputStream.toByteArray();
} catch (Exception e) {
Toast.makeText(getBaseContext(),e.toString(),Toast.LENGTH_LONG).show();
}
}else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
This is onActivityResult method in MainActivity to receive the data from add activity and displaay in list view,how to receive the image from add activity ??
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == requestcode2){
if(resultCode == Activity.RESULT_OK){
String nameAdd = data.getStringExtra("NameAdd");
int idAdd = data.getIntExtra("IdAdd", 0);
byte[] img = data.getByteArrayExtra("ImageAdd");
Employee e = new Employee(idAdd,nameAdd,img);
list.add(e);
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(),"Added Successfully",Toast.LENGTH_LONG).show();
}
}
}
And finally this is the Employee Class
public class Employee {
int id;
String name;
byte[] imgg;
public Employee() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public byte[] getImgg() {
return imgg;
}
public void setImgg(byte[] imgg) {
this.imgg = imgg;
}
public Employee(int id, String name, byte[] imgg) {
this.id = id;
this.name = name;
this.imgg = imgg;
}
The code run correctly when I add texts but the problem in Image did not display in the list
If your only goal is to save a variable and share it with other activities (you are not doing this to learn how to get an image from an intent) can't you just declare your variable as static?
In the app I'm developing, the user can define an image on his profile. The first time the app is executed, an intro activity is shown where the user can choose between selecting a photo from the galery or taking a new one with the camera.
This works fine. After the user sets a profile pic, I save it in the app folder and I can use that pic inside the app later.
My app is based on the Navigation Drawer (support) so it is composed by fragments. One of this fragments is for the user's profile where the profile pic is shown. here, the user has te chance to change this pic again. An here is where I'm getting troubles.
To select a new pic, I'm using the same code I used to get the pic in the intro activity, just adapting some things to the fragment (putting getActivity()). But it seems that is not returning the image to the fragment and it's throwing a NPE.
This is how the pic is selectect from gallery in SettingsFragment:
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, PICK_IMAGE_REQUEST_FRAG);
And here is the onActivityResult in SettingsFragment too:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case PICK_IMAGE_REQUEST_FRAG:
if (resultCode == getActivity().RESULT_OK && data != null) {
/*We get the image URI*/
Uri selectedImageUri = data.getData();
Bitmap srcBmp = null;
try {
srcBmp = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), selectedImageUri);
} catch (FileNotFoundException e) {
Log.e("GET_IMAGE", e.getMessage(), e);
} catch (IOException e) {
Log.e("GET_IMAGE", e.getMessage(), e);
}
/*Transform the original image to landscape to use it as profile background*/
Bitmap landBmp = null;
if (srcBmp.getWidth() <= srcBmp.getHeight()) {
landBmp = Bitmap.createBitmap(
srcBmp,
0,
srcBmp.getHeight()/2 - srcBmp.getWidth()/2, //srcBmp.getHeight()/4 ?
srcBmp.getWidth(),
srcBmp.getWidth() /2
);
}
/*Scale the bitmap*/
int originalWidth = srcBmp.getWidth();
int originalHeight = srcBmp.getHeight();
int newWidth = 400;
int newHeight = (originalHeight*newWidth)/originalWidth;
Bitmap fullbitmap = Bitmap.createScaledBitmap(landBmp, newWidth, newHeight, true);
/*Save the bitmap in app-folder*/
ContextWrapper cw1 = new ContextWrapper(getActivity().getApplicationContext());
File directory1 = cw1.getDir("profile", Context.MODE_PRIVATE);
if (!directory1.exists()) {
directory1.mkdir();
}
File filepath1 = new File(directory1, "profile_pic.png");
FileOutputStream fos1 = null;
try {
fos1 = new FileOutputStream(filepath1);
fullbitmap.compress(Bitmap.CompressFormat.PNG, 100, fos1);
fos1.close();
} catch (Exception e) {
Log.e("SAVE_FULL_IMAGE", e.getMessage(), e);
}
/*Show background profile pic*/
Drawable drawable = new BitmapDrawable(getResources(), fullbitmap);
header_container.setBackgroundDrawable(drawable);
}
break;
But as said, the app crashes an this is what logcat tells:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=131073, result=-1,
data=Intent { dat=content://media/external/images/media/204 flg=0x1 }}
to activity {com.myproject.executer/com.myproject.executer.MainActivity}:
java.lang.NullPointerException at android.app.ActivityThread.deliverResults(ActivityThread.java:3389)
Caused by: java.lang.NullPointerException at android.graphics.Bitmap.createScaledBitmap(Bitmap.java:590)
at com.myproject.executer.SettingsFragment.onActivityResult(SettingsFragment.java:275)
Where line 275 is Bitmap fullbitmap = Bitmap.createScaledBitmap(landBmp, newWidth, newHeight, true);
So, I don't understand well what is happening, because it says something that is failing to deviler the result to MainActivity , and it has to deliver the result to SettingsFragment.
If the onActivityResult() method doesn't complete and return, the system counts it as the delivery having failed, which is why the errors start with that message.
In your code, it would seem that landBmp is null, because the condition srcBmp.getWidth() <= srcBmp.getHeight() is false, and you don't initialize landBmp in that case. This is throwing the NullPointerException, and halting execution before onActivityResult() returns.
you can reading :http://inthecheesefactory.com/blog/how-to-fix-nested-fragment-onactivityresult-issue/en?fb_action_ids=780839882030502&fb_action_types=og.comments
Create ActivityResultEvent.java
import android.content.Intent;
/**
* Created by nuuneoi on 3/12/2015.
*/
public class ActivityResultEvent {
private int requestCode;
private int resultCode;
private Intent data;
public ActivityResultEvent(int requestCode, int resultCode, Intent data) {
this.requestCode = requestCode;
this.resultCode = resultCode;
this.data = data;
}
public int getRequestCode() {
return requestCode;
}
public void setRequestCode(int requestCode) {
this.requestCode = requestCode;
}
public int getResultCode() {
return resultCode;
}
public void setResultCode(int resultCode) {
this.resultCode = resultCode;
}
public Intent getData() {
return data;
}
public void setData(Intent data) {
this.data = data;
}
}
Create ActivityResultBus.java
import android.os.Handler;
import android.os.Looper;
import com.squareup.otto.Bus;
/**
* Created by nuuneoi on 3/12/2015.
*/
public class ActivityResultBus extends Bus {
private static ActivityResultBus instance;
public static ActivityResultBus getInstance() {
if (instance == null)
instance = new ActivityResultBus();
return instance;
}
private Handler mHandler = new Handler(Looper.getMainLooper());
public void postQueue(final Object obj) {
mHandler.post(new Runnable() {
#Override
public void run() {
ActivityResultBus.getInstance().post(obj);
}
});
}
}
// >>>>>>>>>>>>>> override onActivityResult on Activity
public class MainActivity extends ActionBarActivity {
...
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
ActivityResultBus.getInstance().postQueue(
new ActivityResultEvent(requestCode, resultCode, data));
}
...
}
In fragment :
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Don't forget to check requestCode before continuing your job
if (requestCode == 12345) {
// Do your job
tvResult.setText("Result Code = " + resultCode);
}
}
#Override
public void onStart() {
super.onStart();
ActivityResultBus.getInstance().register(mActivityResultSubscriber);
}
#Override
public void onStop() {
super.onStop();
ActivityResultBus.getInstance().unregister(mActivityResultSubscriber);
}
private Object mActivityResultSubscriber = new Object() {
#Subscribe
public void onActivityResultReceived(ActivityResultEvent event) {
int requestCode = event.getRequestCode();
int resultCode = event.getResultCode();
Intent data = event.getData();
onActivityResult(requestCode, resultCode, data);
}
};
The complete code of my Fragment:
public class ProfileEditPictureFragment extends BaseFragment implements OnClickListener {
private ImageView imageView = null;
private Button buttonPick = null;
private Button buttonSave = null;
private Button buttonCancel = null;
private File tempFile = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setRetainInstance(true);
this.sessionProfilePreferences = new SessionProfilePreferences(this.getActivity());
this.sessionLoginPreferences = new SessionLoginPreferences(this.getActivity());
this.sessionLoginSingleton = SessionLoginSingleton.getInstance(this.getActivity());
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
this.tempFile = new File(Environment.getExternalStorageDirectory(), "temp_photo.jpg");
}
else {
this.tempFile = new File(this.getActivity().getFilesDir(), "temp_photo.jpg");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_profile_picture_edit, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
this.imageView = (ImageView) view.findViewById(R.id.profile_picture_edit_imageview_photo);
this.buttonPick = (Button) view.findViewById(R.id.profile_picture_edit_button_pick);
this.buttonPick.setOnClickListener(this);
this.buttonSave = (Button) view.findViewById(R.id.profile_picture_edit_button_save);
this.buttonSave.setOnClickListener(this);
this.buttonCancel = (Button) view.findViewById(R.id.profile_picture_edit_button_cancel);
this.buttonCancel.setOnClickListener(this);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.v("ProfileEditPicture", "requestCode: " + requestCode);
Log.v("ProfileEditPicture", "resultCode: " + resultCode);
Log.v("ProfileEditPicture", "data: " + data);
Bitmap bitmap = null;
if(resultCode == Activity.RESULT_OK) {
if (requestCode == Globals.REQUEST_PICK_PHOTO) {
try {
InputStream inputStream = this.getActivity().getContentResolver().openInputStream(data.getData());
FileOutputStream fileOutputStream = new FileOutputStream(this.tempFile);
Helper.copyStream(inputStream, fileOutputStream);
fileOutputStream.close();
inputStream.close();
this.startCropImage();
} catch (Exception e) {}
} else if (requestCode == Globals.REQUEST_CROP_PHOTO) {
String path = data.getStringExtra(CropActivity.IMAGE_PATH);
if (path == null) {
return;
}
bitmap = BitmapFactory.decodeFile(this.tempFile.getPath());
this.imageView.setImageBitmap(bitmap);
}
}
}
#Override
public void onClick(View view) {
switch(view.getId()) {
case R.id.profile_picture_edit_button_pick : {
this.pickPicture();
} break;
case R.id.profile_picture_edit_button_save : {
} break;
case R.id.profile_picture_edit_button_cancel : {
this.getActivity().finish();
}
}
}
private void pickPicture() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
this.startActivityForResult(Intent.createChooser(intent, "Select Picture"), Globals.REQUEST_PICK_PHOTO);
}
private void startCropImage() {
Intent intent = new Intent(this.getActivity(), CropActivity.class);
intent.putExtra(CropActivity.IMAGE_PATH, this.tempFile.getPath());
intent.putExtra(CropActivity.SCALE, true);
intent.putExtra(CropActivity.ASPECT_X, 3);
intent.putExtra(CropActivity.ASPECT_Y, 2);
this.startActivityForResult(intent, Globals.REQUEST_CROP_PHOTO);
}
}
But the resultCode is always 0 and the data is always null. Permissions are set ofcourse.
So how can i pick images from the gallery?
I test it on Nexus 4 with Android 5.0.1
Try ACTION_PICK like this
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
And on Activity result
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == RESULT_LOAD_IMG && 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]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
ImageView imgView = (ImageView) findViewById(R.id.imgView);
imgView.setImageBitmap(BitmapFactory
.decodeFile(imgDecodableString));
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
I was having same problem in one of my activities when I set launchMode="singleInstance" in manifest for that activity. It works fine when I remove that attribute. Although I don't know reason for this behaviour.