Need help to save/restore a string between activities - android

I'm learning Android and I didn't find an answer on the web. I want to save a string from an EditText on my MainActivity to restore it on my third Activity -> Activity3
I want this string to be displayed on a TextView of this Activity.
public class MainActivity extends Activity {
private EditText nomPrenom;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nomPrenom = (EditText) findViewById(R.id.nomPrenom);
...................}
in my activity_main.xml :
android:id="#+id/nomPrenom"
android:text="#string/nomPrenom"
and
public class Activity3 extends ListActivity {
private TextView yourName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity3);
yourName = (TextView) findViewById(R.id.nomPrenom);
yourName.setText("take the name of activity 1 here"); //<-- this line causes crash !!
..................}
here is activity3.xml
android:id="#+id/yourName"
android:text="#string/nomPrenom"
How can I do that ?

First of all your question is not so clear.. But as per given i think you need to fetch a data from edittext ( in main activity ) and then pass it to the third activity .
For This you need to use Intent to pass the data from one activity to other activity.
Example -
nomPrenom = (EditText) findViewById(R.id.nomPrenom);
nomPrenom .getText.toString();
Intent in = new Intent(MainActivity.this, Activity3 .class);
in.putExtra("value",nomPrenom .getText.toString()) ;
In Activity3 receive intent like this :-
String strValue = getIntent().getExtras().getString("value");
yourName = (TextView) findViewById(R.id.yourName);
yourName.setText(strValue);

Use Intent.putExtra("Your text here") and pass it to other activities.
or you can take the string from EditText and make the string Global, public and static and then use it in any other class.

You can do it with many ways ...
You can use shared preference so that you can access it from anywhere. But shared preference will retain your value after your application closed.
Another way pass your value with your activity intent when you are creating your activity like this: intent.putExtra' and get value into your activity viagetExtra`
Another way you can define your variable at global place consider create one class too hold such common variables and from there you can access those variable from anywhere.
All three ways can be changed according to your requirement.

In order to move from MainActivity to Activity3 write the following code
//get your edittext's text here
String text = nomPrenom.getText().toString();
//move to Activity3
Intent intent = new Intent(MainActivity.this, Activity3.class);
//pass the edit text value to Activity3
intent.putExtra("EditTextValue", text);
//start Activity3
startIntent(intent);
In Activity3, to get your edit text value do the following.
//get your edit text value here which is passed in MainActivity
String text = getIntent().getStringExtra("EditTextValue");
The variable "text" is the final output which you are looking for.

Related

Pass updated data to home activity without refreshing any activity

Here I have 3 activity and ActivityA contain textView which show username , ActivityB contain only button to redirect ActivityC, ActivityC Contain EditText and save button.
Now i want to change updated text from ActivityC to direct ActivityA when save button clicked without refreshing any Activity than what i have to do? can you please suggest simple way.
I have a same requirement in complex project, i need to save user location at server side using api call and show updated data in ActivityA.
Another way would be to use LocalBroadcastManager.
The code will be as follows.
//ACTIVITY A CODE
TextView username_tv;
String username;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
username_tv = (TextView) findViewById(R.id.username_tv);
//Get your username and store it in username
username = getYourUsername();
username_tv.setText(username);
LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
lbm.registerReceiver(receiver, new IntentFilter("USER_NAME_CHANGED_ACTION"));
}
public BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent != null) {
username = intent.getStringExtra("username");
username_tv.setText(username);
}
}
};
//ACTIVITY C CODE
//ADD this code to your 'SAVE' Button Listener
Intent intent = new Intent("USER_NAME_CHANGED_ACTION");
intent.putExtra("username", editText.getText().toString());
// put your all data using put extra
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
For more information on localBroadcastManager look here.
I do not understand why you need this, but you can do it by saving the value of EditText in ActivityC in SparedPreferences here is an example how can make it. Then you should check in onResume() method of ActivityAif there is saved value in SparedPreferences and if has some get the value and set it to "Username" TextView.
EventBus will solve your problem
http://greenrobot.org/eventbus/

How to put EditText info into a Intent variable

I'm trying to get the user information typed in the edit text. I want it saved into the Intent result variable. Trying to sending it back to the main activity afterwards. Keep getting the cannot resolve method. I'm thinking it must be that I'm missing a parameter in the putExtra() method
public class EnterDataActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_enterdata);
Button doneButton = (Button) findViewById(R.id.button_done);
final EditText getData = (EditText) findViewById(R.id.enter_data_here);
doneButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent result = new Intent();
result.putExtra(getData);
setResult(RESULT_OK, result);
finish(); // Ends sub-activity
}//ends onClick
});
}//ends onCreate void button
}
Well if you are trying to send the EditText that's not possible.
If you are trying to send the text that are on that EditText that's possible.
How to do it?
Declare a String to save the data (You can avoid this step, but that's more clear)
String mText = getData.getText().toString();
Then you'll use the getExtra() method to send the String to the new Activity
Intent i = new Intent(this, MyNewActivity.class);
i.putExtra("text_from_editText", mText);
startActivity(i);
Then the last step (You don't ask for it, but you'll need it), get the text.
//onCreate() of the second Activity
Intent i = getIntent();
String mText = i.getStringExtra("text_from_editText");
Replace result.putExtra(getData); with result.putExtra(getData.getText().toString()); to get the text from the EditText. Right now you're trying to put the entire EditText object into the intent as an extra instead of just the text from the EditText.

Pass reference of one Activity to another Activity

I know that I can pass some values between Activities using intent.
However, if I want to pass whole Activity to another Activity I think it is not good approach.
Is there another way to do that?
I have Settings Activity in which I am changing some Colors. So after I come back to my Main Activity I would like to apply those colors. To do this, I need access to MainActivity fields after I change Color value, so inside PreferenceActivity. In other words, I want to have access to Main activity fields from PreferenceActivity class. Any ideas?
You should be using a SharedPreference and then accessing that in your main activity. I recommend you reading up at http://developer.android.com/guide/topics/ui/settings.html because it seems like you are implementing your settings activity incorrectly. The part you might be specifically interested in is the "Read Preferences" section. However, I strongly suggest you read through the whole thing and then implement your settings the proper way.
Updated answer with the 3 different ways (that I can think of):
1) Start your preference activity using startActivityForResult(), then in your onActivityResult() access the SharedPreference and make your necessary changes. See here
2) Register a SharedPreferenceChangeListener with your MainActivity, which will be called when any changes happen to your SharedPreference. See here for a detailed discussion. Also see my initial response.
3) In your MainActivity's onResume(), access the SharedPreference and then make your changes there. I do not like this method because you will be cluttering onResume() with more logic and you will also probably have to have a variable that keeps track of the state of the variable you are interested in.
I would personally go with option 2 because the callback was created for this exact purpose.
I think you could pass the value by using method putExtra(name, value).
And after you start new activity you can get the value you pass before by using method getStringExtra(name).
Shared preferences can be used. If you want your changes to be reflected right away add listener. Refer to SharedPreferences.onSharedPreferenceChangeListener. Its an easy way to do.
If you want to lots of changes required in many activity from you change in any one.
And access last modify data from all Activity and modify also.
for example.
Constants.java
public class Constants
{
public static String name;
}
In your MainActivity you have an editText.
MainActivity.java
public class MainActivity extends Activity {
private EditText yourName;
private Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
yourName = (EditText) findViewById(R.id.yourName);
btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Constants.name = yourname.getText().toString();
Intent intent = new Intent(getApplicationContext(),Activity2.class);
startActivity(intent);
}
});
}
In your Activity2 you have an TextView and that getting value which you enter in MainActivity.java without pass in Intent.
Activity2.java
public class Activity2 extends Activity {
private TextView yourName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
yourName = (TextView) findViewById(R.id.tv_yourName);
// directly use ferom serializable class
yourname.setText(Constants.name);
}
like that you use many values from all activity and modify from all activity.

Android : Passing a value between activities

In my Android application I have to use common string value for all activities. "commonValue" is the common string value that I want to use in all activities. Relevant code of the main activity like this :
public class TestActivity extends Activity {
public String commonValue;//THE COMMON STRING FOR ALL ACTIVITIES
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
commonValue = "DemoValue";
}
}
In my next activity I created an object of "TestActivity" class and tried to assign "testValue" string to another string named "str"
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.testlist);
TestActivity obj = new TestActivity();//OBJECT OF MAIN ACTIVITY
String str = obj.commonValue;
}
but the "str" value in second activity does not equal to the value assigned in my first activity. Why is that & How can I do this?
Thanks!
Put your value in string.xml
<string name="common_value">DemoValue</string>
and use in any activity like this..
String common_value = getApplicationContext().getString(R.string.common_value);
Start using SharedPreferences in your app.
In your first activity you would do
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("commonValue", "DemoValue");
editor.commit();
In your second activity
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
String str = settings.getString("commonValue", null);
Try this -
TestActivity.java
public class TestActivity extends Activity {
public static String commonValue;//THE COMMON STRING FOR ALL ACTIVITIES
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
commonValue = "DemoValue";
}
}
another activity
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.testlist);
String str = TestActivity.commonValue;
}
If the value is always the same you can create a public static final variable and access it via TestActivity.COMMON_VALUE.
If you want to pass around a value between to Activities you should use Intents and add an extra with the value you want to pass.
As Sana has suggested, use SharedPreferences.
Alternatively, use a global constant class. If you want to stick with what you have, then you could try:
String str = TestActivity.this.commonValue;
Your existing code is creating a new instance of the activity, so it's not going to have the value you had set.
To pass data between activities use Bundle. and methods,
intent.putExtra()
and If you want to set data to be global to your app, then create an application class, and save the data there.
We have an Application file for each app you can declare the variable there and as the Application file can get from any activity so using the public getter setter and can get/set that
there are vaious oter metjod you can sue as mention on developer.android http://developer.android.com/resources/faq/framework.html
Singleton class
A public static field/method
A HashMap of WeakReferences to Objects (almost same as my above solution )
Persistent Objects
take a look on them as well
The reason why commonValue doesn't equal what you set in TestActivity onCreate method is because that function hasn't been called yet.
The solution for this is already mentioned by others. Like putting the value in a bundle.

Android: problem in getText method of EditText

In my project I have two activities or classes. In first activity I have a EditText and I want to get the text of it from second class.
In the first class I wrote this code but it seems has problem.
public String getTextMessage()
{
return textMessage.getText().toString();
}
because in second class when I want to get it, program crashes.
message = encode.getTextMessage();
What is your suggestion?
As told by sunil you have to firstly get string from edittextbox and through intent send it to another second activity. After start of second activity you have to get text from bundle.
code snippet is given below...
Activity A
Intent i = new Intent(this, Second.class);
i.putExtra("EXTRATEXT", editText.gettext().toString());
startActivity(i);
Activity B
Class Second extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String text = getIntent().getExtras().getString("EXTRATEXT");
}
Access the text by getText() from edit text and store it in an string. when you move to second activity sent string variable to second class via bundel. Extract the bundel in second class and use it.
You have to pass the value through intents

Categories

Resources