How do I modify one activity's variables from another activity? - android

Let's say
First.class
has a variable
String currentValue = "Red"
with a button that leads to Second.class (an activity). First.class(Activity) displays in a textview what the variable currentValue happens to be. (Currently, Red).
If we push the button, it takes us to Second.class, which has an EditText box to modify the variable in First.class. It also has a button to confirm the change. Finally, it has a TextView at the very bottom showing a preview of what First.class' value variable is.
When a user types in "Blue" in Second.class' EditText box and hits the button, how would we change the variable from First.class without using intents and going back to that activity? I want to stay within Second.activity and do the changes from there.
After hitting the confirm button, the preview TextView should update to match the newly modified variable. We should still be seeing Second.class, I remind you. If the user hits "Back" or "up" at this point, they should return to First.class and also see that the TextView in First.class has been changed.
How do I modify First.class' variables if Second.class is entirely separate from First.class and cannot access it? (First.class is the hierarchical parent of Second.class.

How do I modify First.class' variables if Second.class is entirely separate from First.class and cannot access it?
You can't or (more importantly) you should not try to do this.
The Android Activity is a "special case" class and should be generally considered as being self-contained. In other words any changes to data in the second Activity which need to be reflected in the first Activity must be either persisted using some form of global storage (SharedPreferences for example) or should be passed using the extras of an Intent or a Bundle.
With SharedPreferences simply have the first Activity save your currentValue before starting the second Activity and do the reverse in second Activity before returning to the first. The first Activity then simply needs to check the SharedPreferences in onResume() and update its TextView if necessary.
As codeMagic mentioned, however, simply using startActivityForResult(...) would allow passing currentValue from the first to the second Activity and, before the second exits, updating the Bundle with any changes will allow it to be passed back to the first Activity through onActivityResult(...).

Related

Advice needed with back button on the device

I am working on an android app,coming to the point, one activity in the app has two edit text fields, the first field gets active that is gets enabled when the activity is started, and it is only after the first text field is filled, the second field becomes active. This part work correctly.
Now what the problem is when the user fills the second text field and presses the back button on the device, the second text field should get saved and should become inactive, also when the user again goes to the same activity, the second text field should remain inactive,and should get active that is editable only after the user double taps the second edit text field.
I know that database would be needed for saving the data entered in the second field,but even if that is used how should I resolve the problem above, I'd really appreciate your help.Thanks.
over ride this function onBackPressed(). In this function, write your code to "save" the text box contents and onResume(), you can re-load the text with the saved value.
override
onPause()
and
onResume()
to do your task.
You could aslo try startActivityForResult()

Using Primitive Data Types in another Class and the res/menu/.xml file

I'm a very new to Java. I thought I was doing okay but have now hit a brick wall, so to speak.
The idea is I use the 'home button' '_menu' for the user to choose one of 26 formats. The format they choose has 3 variables. Those 3 variables are then used in the first xml view, along with 2 user inputs to calulate another variable. This variable is then used in a second xml view, along with a third user input here, to calculate the final answer.
I have created the 26 choices and if for example I choose option 5, on the emulator screen I see all the correct values associated with this choice. I don't think those values are getting stored anywhere. I say this because if I come out of that view and return back into it, it's not showing, as in my example, choice 5. It's showing its initial state, as though I was going into it the first time. I assume it's something to do with launching this activity from the start but is there anyway around this. Or really where do I start.
My second question is with the integer variables that I created from this choice. I need to pass them into another java file for the first set of calculations. I've tried to pass the variables/data with the, 'new intent putExtra' but can't get it to work. But I don't think I can use this anyway since the I don't want to launch the second view directly from the res/menu/ .xml view.
Not sure if this is making sense to anyone. Can someone help point me in the right direction?
I don't quite understand your first question, but it sounds like you're launching a new activity and when you quit and come back to it, everything is reset. If you're launching a new activity after selecting the options from your phone's menu button, you should implement a method that saves data to the shared preferences of the main activity. This method should be called on the activities onPause(), onDestroyed(), or onStop() method. You can also add a method on onResume() where the activity checks if there's any data stored in shared preferences and if so, make the desired changes.
As for your second question...I kinda don't understand it either. new intent and putextra is used when you're starting a new activity and want to pass data to it. Views are not "launched" they are only inflated and brought on display whenever you want. I did an app once where I had everything in one activity and just using setContentView() method all the time. In the long run, it just complicated everything. It is easier to keep things simple and launch activities. Here is an example of some variables being passed to a new activity:
On my main activity (FirstActivity) I have:
(when newActivityButton is clicked)
case R.id.newActivityButton:
Intent mIntent = new Intent(FirstActivity.this,SecondActivity.class);
String[] luckyNumbers = {
luckyNumber[0].getText().toString(),
luckyNumber[1].getText().toString(),
luckyNumber[2].getText().toString(),
luckyNumber[3].getText().toString(),
luckyNumber[4].getText().toString(),
luckyNumber[5].getText().toString()};
mIntent.putExtra("luckyNumbers", luckyNumbers);
mIntent.putExtra("message", messageField.getText().toString());
FirstActivity.this.startActivity(mIntent);
break;
luckyNumbers[] is an array of textviews.
Then on my NewActivity onCreate(), I have:
message = getIntent().getExtras().getString("message");
Log.i("TAG", message);
luckyNumbers = getIntent().getExtras().getStringArray("luckyNumbers");
cv.setLuckyNumbers(this.luckyNumbers);
cv.setMessage(this.message);
where cv is just a custom view I created with its own methods

how to save the state of the activity when user pressed select?

i have created dynamic table-layout. in that layout in each row have four buttons.one button is use to navigate from one activity to another. my problem is when i switch from 1st activity to second activity by pressing button and i come back from 2nd activity to 1st activity clicked button loose its state.
Ex. 1) in 1st Activity i click button 1 and check the check box and go to 2nd activity after doing some operation i come back to 1st activity and i see the button1 and check box are unclicked and unchecked.
so how to maintain states of buttons
obviously it would be happen because i have to maintain the check box state when its come on the on resume() ..u can take a shared preferance to mantain the check box state .
Use variables and store the values in the variable when u clicked the button. Store that variable values in the Bundle object using the bundle.putExtras...() method. send this bundle object to the other activity using Intent.putExtra...s();. In the same manner ,if u need the those values then resend that bundle object and get that bundle object using Intent.getExtras....();. And finally restore the values from the bundle object.
This information may solve your problem.

Android, simply view question about view reset

I have a button in my activity, when you click the button an if statement is ran against its text label;
if(BTN_1.getText()=="firsttext"){
//do some stuff, then...
BTN_1.setText("secondtext");
}else if(BTN_1.getText()=="secondtext"){
//do other stuff, then...
BTN_1.setText("firsttext");
}
Firstly, if I hit the home button and go back to the desktop and then click back onto my app the view has reset its self; if I press the button and leave it in a state where the text of the button is "secondtext", when I return to my app it says "firsttext", how can I stop the view of my app refreshing its self like this?
Secondly, under my XML layout I have defined the buttons text; android:text="firsttext"
But this won't actually match my if statement above, under onCreate of this app I have: BTN_CONNECT.setText("Connect");
But visually the text of the button is exactly the same, why won't it match?
Thanks for reading :)
Where do I start?
String compares need to be done with equals(), not ==.
String compares to check your state are bad to begin with. Use an integer/enum to see manage your state.
Depending on how long you want your state to persist, you can either do it in Activity.saveInstanceState() (so it will persist if you change orientation), or in the SharedPreferences if you want it to persist forever.
Don't use hard-coded strings for android:text, use resources, so you can translate them.
I don't understand your last point.

Save and restore a ButtonText when screen orientation is switched

As usual in android, each time the screen is flipped to portrait/landscape mode an Activity runs through life-cycle from onSaveInstanceState to onDestroy and then is recreated.
In my Activity there's a ButtonText which can be changed by the user. It's reseted to the initial state, but I have to save the last state somehow. How can I achieve that, will I have to override onSaveInstanceState? Can someone show an example?
I had the same problem and expected that the default implementation would take care of restoring a button's text. Unfortunately it did not. Finally I found the attribute android:freezesText respectively the method setFreezesText(boolean). When set to true the button will restore its text automatically.
See the reference of Button's super class TextView: http://developer.android.com/reference/android/widget/TextView.html#attr_android:freezesText
Step #1: Call getText().toString() on the Button to get the caption.
Step #2: Call putString() on the Bundle passed to your implementation of onSaveInstanceState() to store the caption.
Step #3: Call getString() on the Bundle passed to your implementation of onRestoreInstanceState() (or in onCreate(), if the Bundle is not null, if you wish) to get your caption back, then call setText() on your Button to put the caption back in.
Here is a sample project that uses onSaveInstanceState() to save a Uri of a contact (which also affects whether or not a Button is enabled).

Categories

Resources