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?
Related
public class addBoard extends AppCompatActivity {
private final int GET_GALLERY_IMAGE = 200;
Uri image;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addboard);
final EditText EDTITLE = findViewById(R.id.editTitle);
final EditText EDTEXT = findViewById(R.id.editText);
ImageView imgView = (ImageView)findViewById(R.id.imageView);
Button addPhoto = findViewById(R.id.photo);
addPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
startActivityForResult(intent, GET_GALLERY_IMAGE);
}
});
try {
Bitmap bm = MediaStore.Images.Media.getBitmap(getContentResolver(), image);
imgView.setImageBitmap(bm);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Button backButton = findViewById(R.id.backButton);
backButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("Input_Title", EDTITLE.getText().toString());
intent.putExtra("Input_Text", EDTEXT.getText().toString());
intent.putExtra("Input_Image", image);
setResult(RESULT_OK, intent);
finish();
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GET_GALLERY_IMAGE && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri selectImage = data.getData();
image = selectImage;
}
}
}
If you run this code in another project, there is no error, but if you use it in this project, you will get an error. Why is that?
Error :Caused by: java.lang.NullPointerException: uri
at com.example.toolbar.addBoard.onCreate**(addBoard.java:45)** // blue line
An error occurs during the operation to place Uri as bitmap in imageView.
My Main2Activity class
public class Main2Activity extends AppCompatActivity {
private static int PICK_IMAGE_REQUEST = 1;
ImageView imgView;
static final String TAG = "Main2Activity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
}
public void loadImagefromGallery(View view) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && null != data) {
final Uri uri = data.getData();
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
int nh = (int) (bitmap.getHeight() * (1024.0 / bitmap.getWidth()));
Bitmap scaled = Bitmap.createScaledBitmap(bitmap, 1024, nh, true);
imgView = (ImageView) findViewById(imageView);
imgView.setImageBitmap(scaled);
Button button3 = (Button) findViewById(bt_tab3);
button3.setOnClickListener
(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), Main3Activity.class);
intent.setData(uri).addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);
}
});
} else {
Toast.makeText(this, "No.", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Oops! Sorry", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}
And the Main3Activity
public class Main3Activity extends AppCompatActivity {
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
imageView = (ImageView) findViewById(R.id.imageView2);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Uri imageUri = getIntent().getData();
imageView.setImageURI(imageUri);
}
}
How can I show same gallery image in MainActivity and another Activity?
Move your Button related codes into onCreate() and send Uri as String using intent extras.
Update Main2Activity as below:
public class Main2Activity extends AppCompatActivity {
static final String TAG = "Main2Activity";
private static int PICK_IMAGE_REQUEST = 1;
ImageView imgView;
Button button3;
Uri imageUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
imgView = (ImageView) findViewById(R.id.imageView);
button3 = (Button) findViewById(R.id.bt_tab3);
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), Main3Activity.class);
intent.putExtra("imageUri", imageUri.toString());
startActivity(intent);
}
});
}
public void loadImagefromGallery(View view) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && null != data) {
// Get uri
imageUri = data.getData();
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
int nh = (int) (bitmap.getHeight() * (1024.0 / bitmap.getWidth()));
Bitmap scaled = Bitmap.createScaledBitmap(bitmap, 1024, nh, true);
// Set image
imgView.setImageBitmap(scaled);
} else {
Toast.makeText(this, "No.", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Oops! Sorry", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}
Get Uri as string from intent and construct Uri from string using Uri.parse() method.
Update Main3Activity as below:
public class Main3Activity extends AppCompatActivity {
ImageView imageView;
Uri imageUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
imageView = (ImageView) findViewById(R.id.imageView2);
if (getIntent().getExtras() != null) {
imageUri = Uri.parse(getIntent().getStringExtra("imageUri"));
imageView.setImageURI(imageUri);
}
}
}
Pass the file path from the uri as String like this to Main3Activity.
button3.setOnClickListener
(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), Main3Activity.class);
intent.putExtra("filePath", uri.getPath());
startActivity(intent);
}
});
And in Main3Activity get the data passed from the calling Activity like this.
public class Main3Activity extends AppCompatActivity {
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
imageView = (ImageView) findViewById(R.id.imageView2);
File file = new File(getIntent().getStringExtra("filePath"));
setImageFromFileIntoImageView(file);
}
private void setImageFromFileIntoImageView (File imgFile)
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
imageView.setImageBitmap(myBitmap);
}
}
}
You need to add the following permission in your AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
based on you not accepting previous answers here is a different approach :
first convert your image to byte array like :
Bitmap bm = BitmapFactory.decodeFile("/path/to/image.jpg");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is bitmap object
byte[] b = baos.toByteArray();
then convert that into string like :
String encodedImage = Base64.encodeToString(byteArrayImage, Base64.DEFAULT);
then from your first activity make an intent and put that string as an extra like:
Intent imageIntent = new Intent(context,Main3Activity.class);
imageIntent.putExtra("image",encodedImage);
startActivity(imageIntent);
and after that it is so easy to get this string in the next activity using getIntent and then getExtra
hope this helps.
I am trying to build an app that enables you to change your profile picture. When the app opens for the first time, it contains a Networkimageview for the current profile pic and a button to change the picture. When the button is pressed a new Activity is started that enables one to choose an image from the gallery and upload to a server.
When the upload is done, the new Activity is closed and the app returns to the MainActivity. How can I make the MainActivity to reload the image just uploaded to the server when the image uploads successfully from the new activity and closes? This is my code
Here's the MainActivity.java
public class MainActivity extends AppCompatActivity {
ImageLoader mImageLoader;
NetworkImageView mNetworkImageView;
private Button buttonChoose;
static final int PROFILE_PICTURE_REQUEST = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonChoose = (Button) findViewById(R.id.buttonChoose);
mNetworkImageView = (NetworkImageView) findViewById(R.id.networkImageView);
loadImage();
}
private String url = "http://10.0.2.2/images/0.jpg";
private void loadImage() {
mImageLoader = CustomVolleyRequest.getInstance(this).getImageLoader();
mNetworkImageView.setImageUrl(url, mImageLoader);
}
public void newActivity(View view) {
Intent profileIntent = new Intent(this, Activity2.class);
startActivityForResult(profileIntent, PROFILE_PICTURE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PROFILE_PICTURE_REQUEST) {
if (resultCode == RESULT_OK) {
loadImage();
}
}
}
}
The second activity Activity2.java
public class Activity2 extends AppCompatActivity implements View.OnClickListener {
private Bitmap bitmap;
private ImageView imageView;
private int PICK_IMAGE_REQUEST = 1;
private String UPLOAD_URL ="http://10.0.2.2/uploadd.php";
private String KEY_IMAGE = "image";
private Button buttonUpload;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
imageView = (ImageView) findViewById(R.id.imageView);
buttonUpload = (Button) findViewById(R.id.buttonUpload);
buttonUpload.setOnClickListener(this);
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
public String getStringImage(Bitmap bmp) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
public void uploadImage() {
//Showing the progress dialog
final ProgressDialog loading = ProgressDialog.show(this, "Uploading...", "Please wait...", false, false);
StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
loading.dismiss();
Toast.makeText(Activity2.this, s, Toast.LENGTH_LONG).show();
Intent returnIntent = new Intent();
setResult(RESULT_OK,returnIntent);
finish();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
//Dismissing the progress dialog
loading.dismiss();
//Showing toast
Toast.makeText(Activity2.this, volleyError.getMessage().toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//Converting Bitmap to String
String image = getStringImage(bitmap);
//Creating parameters
Map<String, String> params = new Hashtable<String, String>();
//Adding parameters
params.put(KEY_IMAGE, image);
//returning parameters
return params;
}
};
//Creating a Request Queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
//Getting the Bitmap from Gallery
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
//Setting the Bitmap to ImageView
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onClick(View v) {
if(v == buttonUpload){
uploadImage();
}
}
}
When you're finishing the Activity2 on a successful image upload, you need to put some extras in the intent which is passed to the launcher activity which is MainActivity.
So the onResponse segment of your uploadImage() function should look like the following. Declare the filePath variable as public so that you can use it here too.
// Declare filePath as public
Uri filePath;
#Override
public void onResponse(String s) {
loading.dismiss();
Toast.makeText(Activity2.this, s, Toast.LENGTH_LONG).show();
Intent returnIntent = new Intent();
returnIntent.putExtra("UPDATED_PIC", filePath.toString());
setResult(RESULT_OK,returnIntent);
finish();
}
Now from your MainActivity handle the retuneIntent to get the filePath and load the image from there. So the onActivityResult may look like -
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PROFILE_PICTURE_REQUEST) {
if (resultCode == RESULT_OK) {
if(data != null) {
Uri filePath = Uri.parse(extras.getString("UPDATED_PIC"));
try {
//Getting the Bitmap from Gallery
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
// Setting the Bitmap to ImageView
mNetworkImageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
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);
}
};
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