Android onActivityResult NEVER called - android

my onActivityResult method is never called. am using android 2.2
I am using a Tabhost, where TabHosts contain TabGroups which contain individual Activities.
One of my individual activity runs the following intent
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select Picture"), 0);
this loads my gallery apps, I use the default android gallery to select one image and when I return my onActivityResult is not called my activity.
It looks like this - and I put a breakpoint at if(resultCode == 0) , so right now, the logic of my onActivityResult should not matter
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == 0) {
if (requestCode == 0) {
Uri selectedImageUri = data.getData();
//OI FILE Manager
filemanagerstring = selectedImageUri.getPath();
//MEDIA GALLERY
selectedImagePath = getPath(selectedImageUri);
//DEBUG PURPOSE - you can delete this if you want
if(selectedImagePath!=null)
System.out.println(selectedImagePath);
else System.out.println("selectedImagePath is null");
if(filemanagerstring!=null)
System.out.println(filemanagerstring);
else System.out.println("filemanagerstring is null");
//NOW WE HAVE OUR WANTED STRING
if(selectedImagePath!=null)
System.out.println("selectedImagePath is the right one for you!");
else
System.out.println("filemanagerstring is the right one for you!");
}
}
}
Lifecycle functions are often called out of order and intermittently for Activities within a tabhost/tabgroup, so I checked to see what lifecycle functions ARE being called after the gallery closes (this happens as soon as I select an image from the android gallery)
The only one being called is the onResume() in my TabHost activity. So I tried putting the exact same onActivityResult() method in my TabHost class AS WELL AS the TabActivity class. With a breakpoint in the same location at the beginning of method.
Neither of these classes are called.
I'm drawing a blank now, how can I get the result from the gallery app in my app if none of the built in receiving methods will respond to it.
Since I know that my main TabHost gets the onResume() called, I tried added Intent graphics = getIntent(); to see if it would receive data from the gallery selection, it does not, so I don't see how I can do the logic in the onResume() method either.
Solutions welcome! :)

Try to call the startActivityForResult using the context of the tabgroup activity containing your current activity and then listen in the tabgroup activity.
Use this to get the tabGroupActivity:
TabGroupActivity parentActivity = (TabGroupActivity)getParent();
And then call startActivityForResult from it:
parentActivity.startActivityForResult(...);
Finally , put an onActivityResult listener in the tabGroupActivity:
protected void onActivityResult(int requestCode, int resultCode,Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
}

Judging from the many questions like this one, there are many reasons why a called activity may not trigger the caller's onActivityResult() method.
One reason I found, was when I called startActivityForResult(intent, requestCode), with a requestCode value of less than 0. My application did not need a requestCode and the Android documentation said using < 0 would not send a requestCode.
But the Android docs did not mention the consequence of a requestCode < 0. The consequence is that it prevents the caller's onActivityResult() method from ever being invoked! Ouch!
Therefore, even if your app does not need a requestCode, you many still want to use one with a value >= 0.
That's what I learned today:-)

The solution is to call a transparent activity over top of the main activity. This transparent activity is in front of the tabhost and will have normal lifecycle functions.
This transparent activity calls the gallery intent onCreate(), it gets everything returned like normal in its onActivityResult and you will be able to pass the information returned back to the rest of the app like normal. finish() is inside of the onActivityResult method, so the user never even notices that a transparent activity was called.
Update copied from from comments:
Activity A calls Activity B via normal intent. Activity B has no xml and runs onCreate like this
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.dialogpopper);
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*"); startActivityForResult(intent, 0);
}//end onCreate
and when Activity C is finished it calls the onActivityResult of Activity B

You just have to remove android:noHistory="true" this form your manifest file.

Use the constant values for the Result codes:
Activity.RESULT_OK and
Activity.RESULT_CANCELED
You'll see that the value for cancelled is actually 0. So in your code you are checking to see if the activity was cancelled.
change your code to
if (resultCode == Activity.RESULT_OK) {
...
}
Additionally change your Intent action to be:
intent.setAction(Intent.ACTION_PICK);
If you do this, you can just call
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, 0);
instead of creating the chooser. It will automatically pick the activities associated with that intent and mimetype and display them to you

The way onActivityResult is called depends on the launchMode of your Activity (in the manifest). I'm not sure if that can be an issue here.

do you have #Override above your onActivityRestult?
(looking at old code that does this so not sure why its needed) call super.onactivityresult(requestcode, resultscode, data) as the first call in the method
also my intents didnt have that other stuff in them
startActivityForResult(Intent.createChooser(intent,
"Select Picture"), 0);
i think should just be
startActivityForResult(source.class, destination.class);
of course source and destination should be the name of the classes
public class ImageSwitcherView extends Activity {
int pics[] = { R.drawable.image000, R.drawable.image001,
R.drawable.image002};
private int currentIndex = 0;
SharedPreferences preferences;
Gallery gallery;
ImageView fullPicView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.galleryview);
Bundle extras = getIntent().getExtras();
currentIndex = extras.getInt("bookmark");
gallery = (Gallery) findViewById(R.id.Gallery01);
gallery.setAdapter(new ImageAdapter(this));
gallery.setSelection(currentIndex);
gallery.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position,
long id) {
currentIndex = position;
// ---display the images selected---
fullPicView = (ImageView) findViewById(R.id.imageView1);
fullPicView.setImageResource(pics[currentIndex]);
fullPicView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(ImageSwitcherView.this,
imageView.class);
int resID = pics[currentIndex];
myIntent.putExtra("resID", resID);
myIntent.putExtra("index", currentIndex);
startActivityForResult(myIntent, 1);
}
});
}
});
}
public class ImageAdapter extends BaseAdapter {
private Context context;
private int itemBackground;
public ImageAdapter(Context c) {
context = c;
// ---setting the style---
TypedArray a = obtainStyledAttributes(R.styleable.Gallery1);
itemBackground = a.getResourceId(
R.styleable.Gallery1_android_galleryItemBackground, 0);
a.recycle();
}
// ---returns the number of images---
public int getCount() {
return pics.length;
}
// ---returns the ID of an item---
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
// ---returns an ImageView view---
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(context);
imageView.setImageResource(pics[position]);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setLayoutParams(new Gallery.LayoutParams(150, 120));
imageView.setBackgroundResource(itemBackground);
return imageView;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
currentIndex = data.getIntExtra("bookmark", 0);
gallery.setSelection(currentIndex);
fullPicView.setImageResource(pics[currentIndex]);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK
|| keyCode == KeyEvent.KEYCODE_HOME) {
preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("bookmark", gallery.getSelectedItemPosition());
editor.commit();
finish();
}
return super.onKeyDown(keyCode, event);
}
}

Related

How do I persist an attribute in an activity that I'm navigating back up to?

I have some activities basically set up as shown below (clicks on are ListViews).
Parent class method to go to MyChild1
public void onItemClick(int pos){
Intent i = new Intent(this, MyChild1.class);
i.putExtra("KEY1", myAdapter.getItem(pos).getId());
startActivity(i);
}
MyChild1 class method to go to MyChild2
public void onItemClick(int pos){
Intent i = new Intent(this, MyChild2.class);
i.putExtra("KEY2", myAdapter2.getItem(pos).getId());
startActivity(i);
}
So you see that I have a parent, a child, and a grandchild activity. The child inflates based on the id provided by the parent and the grandchild inflates based on the id of the child. This works fine. However, when I use up navigation from the grandchild back to the child, it no longer has the id it needs from the parent to properly inflate. I need to support up navigation because the child can change based on actions in the grandchild.
I could pass the parent's id all the way down to the grandchild activity, but I don't know how to pass it back up. How can I handle this?
Edit: More code for context.
Here is my activity's onCreate.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_course);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new CourseActivityFragment()).commit();
Intent intent = getIntent();
courseId = intent.getIntExtra(MainFragment.COURSE_ID, 0);
System.out.println("the saved state was null");
// The above prints, so I know it enters this if statement
} else {
courseId = savedInstanceState.getInt(COURSE_ID);
}
}
And here is my onSaveInstanceState
#Override
public void onSaveInstanceState(Bundle savedInstanceState){
// Save current CourseId
savedInstanceState.putInt(COURSE_ID, courseId);
// Call superclass to save view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
Instead of startActivity, use startActivityForResult:
Intent intent = new Intent(ParentClass.this, ChildClass.class);
startActivityForResult(intent, RequestCode);
In child class, set some parameter in intent to identify in Parent class.
Intent intent = getIntent();
intent.putExtra(<Key>, <Value>);
In parent class, override the onActivityResult method, and check your Value for that Key
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
if (requestCode == RequestCode)
{
//Do something
}
}
I don't quite follow what you need so I hope this will help. Save it in your Activity class as member variable. Activity's object is not destroyed right after user leave this activity. If that still occur and Android will kill your activity, you can use onSaveInstanceState() and restoreInstanceState() methods to restore this id.

Coming back from intent, do something

I have an android application which is using listView. After clicking on any item on the list it shows you AlertDialog where you can chose either edit or delete. After clicking edit it starts a new intent sending some extra strings to fill up the form for editing. I would like to refresh the list after I click on button save in that EditActivity.
I have read about notifyDataSetChanged() and I think it could work I just would like to know if there is any method which is in MainClass (listView class) and it is executed right after I came back from intent, right after clicking save button in EditActivity.
Or may I just add notifyDataSetChanged() method after I start an activity in the MainActivity?
public class yourClass extends ListActivity {
//define a class variable here.
private ArrayAdapter<Friend> adapter;
#Override
public void onCreate(Bundle savedInstanceState){
//Change this line setListAdapter(new ArrayAdapter<Friend>(this, android.R.layout.simple_list_item_1, db.getAllFriends()));
to
adapter = new ArrayAdapter<Friend>(this, android.R.layout.simple_list_item_1, db.getAllFriends());
setListAdapter(adapter);
}
#Override
public void onResume(){
super.onResume();
adapter.notifyDataSetChanged();
}
}
You can add listView.notifyDataSetChanged() in your activity onResume() function.
#Override
public void onResume(){
super.onResume();
yourListView.notifyDataSetChanged();
}
Use the method startActivityForResult() when opening your EditActivity then implement onActivityResult method in your main class. There you will be able to use notifyDataSetChanged
Read this from the doc
use startActivityForResult to call your EditActivity (this isn't simplest way to do what you want but is good way to do), by using this you can find out what is the result of your edit
Intent i = new Intent(this, EditActivity.class);
startActivityForResult(i, 1);
In your EActivity set the data which you want to return back to MainActivity
Intent returnIntent = new Intent();
returnIntent.putExtra("result",YOUR_RESULT); // skip if you do not want to return special result
setResult(RESULT_OK,returnIntent);
finish();
if you want to send cancel action (in your case fail edit) use this
Intent returnIntent = new Intent();
setResult(RESULT_CANCELED, returnIntent);
finish();
Now in your MainActivity class write following code for onActivityResult() method
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == RESULT_OK){
String result=data.getStringExtra("result"); // result sent from EditActivity
listViewAdapter. notifyDataSetChanged();
}
if (resultCode == RESULT_CANCELED) {
//Write your code if there's no result
}
}
}//onActivityResult

Set ImageView in a static method

I have a method that needs to be called from another activity, and I need to use it to set an ImageView in it's own activity. I have this method in MainActivity:
public static void setImageView(String fileName){
Log.i(TAG, fileName);
imageView = (ImageView) findViewById(R.id.imageView);
bmp = BitmapFactory.decodeFile(fileName);
imageView.setBackgroundResource(0);
imageView.setImageBitmap(bmp);
}
But I can't make a static reference to findViewById because it isn't a static method. This method is being called in a Camera Activity after the photo has been saved, I want to pass in the fileName (file URI) and set the imageView such that when the Camera Activity finishes and the user return to the MainActivity the ImageView is already set. As such, in CameraView I am trying to call this:
...code...
mCamera.takePicture(null, null, callback);
MainActivity.setImageView(fileName);
Is there a cheeky way around this? I know there are other posts on this but I can't quite work out how to apply the advice given there to my situation.
Thanks!
Maybe you should launch your CameraActivity using startActivityForResult() method, and after take the photo put the fileName as an Extra into an Intent and set it as result. Then in your MainActivity you can get the fileName back from the Intent arg of onActivityResult().
Something like:
public class MainActivity extends Activity{
public void aMethod(){
...
Intent i = new Intent(this, CameraActivity.class);
startActivityForResult(i, REQUEST_CODE);
...
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
Bundle b = data.getExtras();
String fileName = b.getString(RETURN_FILE_PARAMETER);
doSomething(fileName);
}
}
}
...
public class CameraActivity extends Activity{
private void returnFileFinishActivity(String fileName) {
Intent retIntent = new Intent();
retIntent.putExtra(RETURN_FILE_PARAMETER, fileName);
setResult(RESULT_OK, retIntent);
finish();
}
}
Regards.
A few things.
1) Since you should only be displaying one activity at a time, why not just start with startActivityForResult in the activity with the ImageView and override onActivityResult in your camera activity?
2) I'm not sure of your application, but it may be easier if you implement taking a picture by following this: http://mobile.tutsplus.com/tutorials/android/android-sdk-quick-tip-launching-the-camera/ .
3) You can expose a static reference to your main activity, in your main activity's onCreate method, do something like staticRef = this; and in your camera activity simply access it via MainActivity.staticRef... (I would not recommend this approach)
4) You can register a broadcast receiver in your Main activity that has a reference to your main activity or image view and in your camera activity you send a broadcast to it which you can set the image view

Passing image from activity to another activity?

I'm trying to take apicture and I want to pass this picture to another activity to be displayed in it.
OnClickListener listener_TakePic = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}
};
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_PIC_REQUEST && resultCode == RESULT_OK) {
Bitmap image = (Bitmap) data.getExtras().get("data");
}// End IF
}// End of Method
Please tell me what should I do or modify to achieve what I want..
Actually, i have created an application class "base class" in which, I have defined an "bitmap cameraPic" and "static final int CAMERA_PIC_REQUEST = 1;"
Now, I have an activity classed named "AddLocation" from which I call startActivityForResult(intent, CAMERA_PIC_REQUEST);
but I want the result of the camera Picture to appear in another activity called "MPActivity"
My question is, should I call "onActivityResult(int requestCode, int resultCode, Intent data)" method from "MPActivity" or there is no need to call it...
i'm really confused please clarify..
There are more than one way to tackle the task you are doing.
you can build a java class and put populates its one of property by the desired image. Then you can just get stuff that into an arraylist and pass that to a global arraylist.
you can use Application class and make a global image variable that can be accessed in every class in your activity.
etc ...

restart activity in android

I have one activity A, that has one button and one list view which shows names of books . on click of the button, activity B starts, there user fill the book form and save it . when he press back button , user comes to activity A. Here the book name should be updated in listview. I think I have to write some code in onResume() . Can u please tell me what to write. I am using customised list view.
Start activity B with startActivityForResult() and use method onActivityResult() to restart or process the new data
For example, to start Activity B:
String callingActivity = context.getLocalClassName();
Intent newActivity = new Intent(getApplicationContext(),ActivityB.class);
newActivity.setData(Uri.parse(callingActivity));
startActivityForResult(newActivity, 0);
Then somewhere in your Activity A class:
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == 0){
// do processing here
}
}
The other answers should suffice, but onResume() can be called in cases where the activity is resumed by other means.
To simply restart Activity A when user presses back button from Activity B, then put the following inside the onActivityResult:
if(requestCode == 0){
finish();
startActivity(starterintent);
}
And in the onCreate of Activity A, add starterintent = getIntent();
Just remember to initiate the variable with Intent starterintent; somewhere before your onCreate is called.
e.g.
public class ActivityA extends ListActivity {
Intent starterintent;
public void onCreate(Bundle b){
starterintent = getIntent();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == 0){
finish();
startActivity(starterintent);
}
}
private void startActivityB(){
String callingActivity = context.getLocalClassName();
Intent newActivity = new Intent(getApplicationContext(),ActivityB.class);
newActivity.setData(Uri.parse(callingActivity));
startActivityForResult(newActivity, 0);
}
}
Then just call startActivityB() from a button click or whatever
YES you are right. Write code in onResume.
When you updated date just call notifyDataSetChanged(); for your ListView adapter
Hope, it help you!
You can either start the activity when user press on Save, and it will fix it for you.
Or if you want to press back:
#Override
public void onResume(){
super.onResume();
list.clear();
list.addAll(getBooks());
adapter.notifyDataSetChanged();
}

Categories

Resources