How to change edit text after view created - android

I need to change the text of a EditText and a TextView with the return of an activity.
So, in the onActivityResult I did the following:
protected void onActivityResult(int requestCode, int resultCode, Intent data){
Bundle extras = data.getExtras();
EditText edit = (EditText)findViewByID(R.id.edit);
edit.setText(extras.GetString("edit");
TextView tv = (TextView)findViewByID(R.id.tv);
tv.setText(extras.GetString("tv");
}
The text of the TextView is changed, but the text of the EditText isn't.
If I change the text on the onCreate everything works, but on the onActivityResult just the TextView works.
My question is: how can I change the text of the EditText on the onActivityResult?

You can see below a working simple example of how you can change the text of an EditText in the method onActivityResult.
Here is the code for the first activity:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Intent i = new Intent(this, MyActivity2.class);
startActivityForResult(i, 0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
final Bundle result = data.getExtras();
if (!result.isEmpty() && result.containsKey("data")) {
final EditText editText = (EditText) findViewById(R.id.edit);
editText.setText(data.getStringExtra("data"));
}
}
}
Here is the code of the second activity:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Intent result = new Intent(this, MyActivity.class);
result.putExtra("data", "test");
setResult(RESULT_OK, result);
finish();
}

Your logic is correct, but Android has its pitfalls and landmines (as usual!)
You can force a EditText.SetText("blablabla..."); inside your OnActivity Result
in 3 EASY steps:
Reload your layout into your Activity
Rebind your EditText
use SetText as usual.
In this sample code, I pass a URL string with and intent and write it into a TextView:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == RESULT_OK)
{
QRdata= data.getStringExtra("QRURL"); //Get the String from the Intent
if (QRdata.length()>0)//Continue if the Intent´s text is not empty..
{
//Step1
setContentView(R.layout.activity_confirmpackage);
//Step2
TextView qrtxt=(TextView)this.findViewById(R.id.qrurl);
//Setp 3,VoilĂ !
qrtxt.setText(QRdata.toString());
}

Do not change your views in the OnActivityResult - as that's a sure way to get your program crashed if the activity was stopped and was at some point wiped off the memory - and now is being recreated.
In this case, onActivityResult will highly likely run before the views finish to inflate from the OnCreate - setContentView method.
Do not use setContentView in the onActivityResult either, because it will duplicate the expensive operation which was performed in the OnCreate method.
The workaround (when you use the data from OnActivityResult for filling the UI views, such as EditText or TextView) is to set up a variable that would keep the value from the extras and then use this variable later - specifically in the OnResume method.

Related

saving the data that is passed through intents [duplicate]

This question already has an answer here:
Android: Saving and Restoring data when switching between Activities
(1 answer)
Closed 5 years ago.
I have a TextView and a Button in my first activity and an EditText and a Button in my second Activity.when i click a button in my first activity it must be redirected to second Activity.In the second activity i want to give the data in the EditText and click the button it must be redirected to first activity and second Activity EditText value must be displayed in the TextView given in the first activity.my problem is i want to save the EditText data after returning back from the first activity.
public class ActivityA extends Activity {
private void gotoActivityB(){
startActivityForResult(new Intent(this,ActivityB.class),101);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 101 {
if (resultCode == RESULT_OK) {
String value = data.getStringExtra("KEY");
}
}
}
}
public class ActivityB extends Activity {
#Override
protected void onDestroy() {
super.onDestroy();
Intent intent = new Intent();
intent.putExtra("KEY",editTextValue);
setResult(Activity.RESULT_OK,intent);
}
}

How do I change an activities's boolean values or other variable values in another activity?

So I have a boolean value in Activity A that is set to false. Then, in another activity I want to change that value to true. Then when i press the back button back to activity A, that boolean is now true and it runs that in the onCreate.
here's what I mean, Activity A
private static boolean newCardcheck = false;
#Override
protected void onCreate(Bundle savedInstanceState)
{
}
public static void setNewCardcheck() {
newCardcheck = true;
}
#Override
public void onResume() {
super.onResume();
if(newCardcheck)
{
Toast.makeText(this,"hey everyone",Toast.LENGTH_SHORT).show();
}
else
{
alfunction();
sendCards(storeCards);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(requestCode == RESULT_LOAD_IMAGE)
{
newCardcheck = true;
}
}
Activity B:
#Override
public void onBackPressed()
{
MyActivity.setNewCardcheck();
super.onBackPressed();
setResult(Activity.RESULT_OK, getIntent());
finish();
}
So when I press back, I want newCardcheck to be true and run the "if" statement not the else statement.
Hope you guys can help.
thanks.
And I also tried putting setNewCard() method in an onClick it didn't work either.
The best way to do this is through SharedPreferences. SharedPreferences will write your data to a private file in a key/value within your app's apk that will persist even you turn your device off.
You can initialize SharedPreferences in onCreate like so: SharedPreferences sharedPreferences = getSharedPreferences(getPackageName(), MODE_PRIVATE).
To store a value simply call: sharedPreferences.edit().putString("myKey", stringValue).commit();
To retrieve that value anywhere from your application, initialize SharedPreferences, and then use the following code: String myData = sharedPreferences.getString("myKey");
Let me know if that helps!
EDIT: You may also want to look into getting a result from your Intent. See Getting a Result from an Activity. Use SharedPreferences if you need the boolean to be persistent (ie: written to storage and available on reboot), otherwise you may want to try onActivityResult.
Edit 2:
Try overriding onActivityResult in Activity A as so:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
myBoolean = true;
}
}
Then in Activity B try
setResult(Activity.RESULT_OK, getIntent());
finish();
This is the standard way of passing data to and from activities. Check out my link above about getting a result from an activity to delve a little deeper.

Android notifyDataSetChanged() not working

I am working on ArrayAdapter and ListView. I have an Activity A and Activity B. Activity A starts an Activity B (startActivityForResult()) and when Activity B is finished, it returns the result back to Activity A.
Activity A:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
listViewPrayerList = (ListView) findViewById(R.id.listView_prayerlist);
prayerList = new ArrayList<PrayerSetting>();
if (getIntent().hasExtra(Utils.PRAYER_LIST)) {
prayerList.clear();
prayerList.addAll((ArrayList<PrayerSetting>) getIntent()
.getSerializableExtra(Utils.PRAYER_LIST));
pAdapter = new PrayerAdapter(this, R.layout.prayer_list_item,
prayerList);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (data != null && data.hasExtra(Utils.SETTINGS)) {
PrayerSetting p = (PrayerSetting) data
.getSerializableExtra(Utils.SETTINGS);
prayerList.set(itemClickedPosition, p);
pAdapter.notifyDataSetChanged(); // UI/List doesn't change
}
}
I don't understand what I am doing wrong! I have tried many solutions but still don't get it.
Stackoverflow Question 1
Stackoverflow Question 2
Stackoverflow Question 3
Blogspot link
Stackoverflow Question 4
I do understand that its a basic question. Thanks in Advance.
Try moving
pAdapter = new PrayerAdapter(this, R.layout.prayer_list_item,
prayerList);
before if statement in onCreate

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

Android onActivityResult NEVER called

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

Categories

Resources