My question is how to pass data like String between two activities. Normally I would do this:
Intent i = new Intent(thisclass.this,NextClass.class);
Bundle b = new Bundle();
i.putExtras(b);
b.putString("Name",Name);
StartActivity(i);
But this would make my Activity close and will open the next Activity, no? Is there any way that I can only pass data without opening the other activity?
I think you are looking for something with the SharedPreference see the documentation : SharedPreference
if it is what are looking for.
Try this:
Global:
private SharedPreferences pref;
onCreate:
pref = this.getSharedPreferences("SharedPreference", Context.MODE_PRIVATE);
The place where you gonna save your data:
String data = "yourData"
pref.edit().putString("myData", data).commit();
And the other Activity:
Global:
private SharedPreferences pref;
onCreate:
pref = this.getSharedPreferences("SharedPreference", Context.MODE_PRIVATE);
The place where you gonna take your data:
String dataFromFristActivity = pref.getString("myData", null);
Your calling activity does not close but is paused.
I am with #Egor on this. The called activity does not yet exist. Unless u are trying to send data between activities in two different apps. That is a whole different can of worms.
Related
I want to make use of some TextViews(cityField, updatedField) I have in my activity inside my fragment.
I know it would have been easier to make use of them in the activity instead, but the problem is that I have to join in with some codes on Fragment due to getting some JSON data
Already I've gotten the id for the codes on activity
cityField = findViewById(R.id.textView4);
updatedField = findViewById(R.id.textView9);
Now I want to make use of them in my fragment
So the question is - is it possible? if it's possible, how?
Already, I checked some answers on this site - Send data from activity to fragment in Android
How to pass data from Activity to Fragment using bundle
but they directly didn't solve my problem.
You should create a SharedViewModel and let the Activity set values of variables like cityField and updateField while the Fragment Observe the changes done to them, basically the Activity will Set and Fragment will Get
for more information about ViewModels check this:
https://developer.android.com/topic/libraries/architecture/viewmodel
You can access these instances from your fragment like this:
String cityFieldFragment = (activity as YourActivity).cityField;
String updatedFieldFragment = (activity as YourActivity).updatedField;
If I understood this right, the fragment lives in your activity, so you are able to access the data from it, just make sure that the instances are public.
if the fragment is not already created you can make use of the constructor of the fragment and pass arguments to it.
If the fragment is already created, create a method inside the fragment and invoke it in the activity.
Let's say you want to pass it from an activity to another activity that contains fragments. First, you need to pass the data like so :
Intent intent = new Intent();
intent.setClass(FirstActivity.this, SecondActivity.class);
intent.putExtra("name", username);
intent.putExtra("pass", password);
startActivity(intent);
In this case, the fragment is inside the SecondActivity.java but to receive the data, we need code inside the Fragment.java instead of the SecondActivity.java.
Bundle extras = getActivity().getIntent().getExtras();
if (extras != null) {
getUsername = extras.getString("name");
getPassword = extras.getString("pass");
}
I haven't tried to pass the data directly to the fragment, but you can try with the same code. All you need to do is changing the intent instead of intent.setClass(FirstActivity.this, SecondActivity.class); to intent.setClass(FirstActivity.this, Fragment.class);.
Have you tried with SharedPreferences?
in you MainActivity
// create sharedPrefences file with the name "info"
SharedPreferences sp = this.getSharedPreferences("info",0);
// here the name and default value
sp.getString("name", "default value");
// create editor
SharedPreferences.Editor editor = sp.edit();
// enter a new value
editor.putString("name", "new value");
// save changes
editor.apply();
in your Fragment
SharedPreferences sp = getActivity().getSharedPreferences("info",0);
String str = sp.getString("name", "default value"); //will get you the new value you entered
I am novice programming on Android. I have one question, I have 2 activities. Firs I pass a parameter from the Activity A to the B like this:
Intent intent = new Intent(getBaseContext(), ActivityB.class);
intent.putExtra("ALMACEN_ANTES", almacen.getText().toString());
startActivity(intent);
And now in the activity B y get the extras. Later since the Activity B, I pass parameters to the A too.
My question is, is it possible to pass parameters to another activity without doing
Intent intent = new Intent(getBaseContext(), ActivityB.class) because I donĀ“t want to open 2 times the same activity.
Thank you!
Yes . You can save the value using SharedPreferences
It will be stored in an internal xml file and you can save it and retrive whenever you want. It need not start the activity when value passing.
An example shows below
SharedPreferences sharedpreferences;
Editor editor = sharedpreferences.edit();
editor.putString(Name, n);
editor.putString(Phone, ph);
editor.commit;
you can retrive this value from the activity where you need to access these values. It can be done by:
SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
String name=sharedpreferences.getString("Name","");
String ph=sharedpreferences.getString("Phone","");
You want to update a value in the activity A , you mean? because if you don't open it why sending a value to it ?
you can share data between two activities by other ways. In your case the best one would be a Singleton class:
you create a class which is inheriting from Application and containing your data, and from every activity you can update you data or get it...
Your singleton class:
import android.app.Application;
public class MyApplication extends Application {
private String data;
public String getData() {return data;}
public void setData(String data) {this.data = data;}
}
From activity B , you can set your data:
MyApplication app = (MyApplication) getApplicationContext();
app.setData(someData);
And teh Ativity A can have them like this:
MyApplication app = (MyApplication) getApplicationContext();
String data = app.getData();
See this answer
I want to know if there is a way to pass all the extras to the new intent.
Is it possible? And is it a good idea?
The reason is that I want to save the login state as a json string, and pass it in between Activities. I don't want to store data with SQLite or anything. Can I bypass all the intent extras to the new intent ?
please consider Shared Preference :
// Declaration
public static String KEY = "SESSION";
public static void saveUserName(String username, Context context) {
Editor editor = context
.getSharedPreferences(KEY, Activity.MODE_PRIVATE).edit();
editor.putString("username", username);
editor.commit();
}
public static String getUserName(Context context) {
SharedPreferences savedSession = context.getSharedPreferences(KEY,
Activity.MODE_PRIVATE);
return savedSession.getString("username", "");
}
You can store the login credentials to preference and retrieve them as well in any of your activity.
SaveUsername("Your text to save", Your_activity.this);
And to retrieve the value
String mUserName = getUserName(YourActivity.this);
It is recommended to have all your preference methods in your utils class to keep the code organized.
You can read more here
yes you can use Shared Preference to save the Login session of user here is handy example of managing session using shared preference http://www.androidhive.info/2012/08/android-session-management-using-shared-preferences/ I used it earlier and suggest you to have a look at it.
Any of the two may help you.
Saving it in the sharedPreference file.
If you want them to be accessable throught the application you can use the applicationClass, like a global singleton.
What the code should do: in the first fragment I have several EditText boxes, so people can fill in there name. In the second fragment I want the names to display in a TextView box. I thought using Shared Preferences was a good thing (correct me if I'm wrong).
In my first fragment I have this code:
public static String filename = "player1";
SharedPreferences someData;
[...]
someData = getActivity().getSharedPreferences(filename, 0);
String player1 = etPlayer1.getText().toString();
SharedPreferences.Editor editor = someData.edit();
editor.putString(player1, "player1");
editor.commit();
In my second fragment:
public static String filename = "player1";
SharedPreferences someData;
[...]
points1 = (TextView) getView().findViewById(R.id.tvPoints1);
someData = getActivity().getPreferences(0);
String dataReturned = someData.getString("player1", "Player 1");
points1.setText(dataReturned);
You may use an Intent or a Bundle. Shared Preferences are for storing long term data.
See this answer https://stackoverflow.com/a/10960855/826657
and this one for how to share data using a Bundle https://stackoverflow.com/a/16500141/826657
& this resource
http://developer.android.com/guide/components/fragments.html
Please pass your data (specially if complex) in a Bundle as explained here: Best practice for instantiating a new Android Fragment
Do not use shared preferences to do that.
There are many ways to pass data between activity and fragment. See this response here : data sharing between fragments and activity in android
I developed one app in that I want to send URI from Class1 editText to another class containing editText.
Can anyone tell me how to do that?
SharedPreferences are the wrong way to do that. Use the Bundle feature every Intent can have: http://developer.android.com/reference/android/content/Intent.html
On the second activity you can call getExtra() and there you go...
Assuming you want to use the SharedPreferences to transfer the URI, you could try this:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
prefs.edit().putString("my-uri", "http://google.com/").commit();
And to retrieve the URI:
prefs.getString("my-uri", "default URI");
If your two classes are Activities, and if one of them starts the other one, you should probably pass the URI as an intent extra.
Also, read the FAQ and accept some answers!
you can use System.setProperty/get Property as well.
don't you like to add putExtra in intent
like this
Intent i = new Intent(getApplicationContext(), Audit_FSD_Tab.class);
i.putExtra("UsrID", UsrID);
i.putExtra("Store", Store);
i.putExtra("location", location);
startActivityForResult(i, 0);
now in other activity access these extra
Bundle UsrVal = null;
UsrVal = this.getIntent().getExtras();
UsrID = UsrVal.getString("UserId");
Store = UsrVal.getString("Store");
location = UsrVal.getString("location");
Try to store Uri in the edit text inside shared preferences in first activity and then on create method of second activity retrieve Uri value from the shared preferences and display that in edit text.simple...
It can be possible by using Shared Preferences, for example
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
Editor editor = pref.edit();
data=pref.getString("key_name5", null);
editText.setText(data);
You can follow tutorial here
http://firstcode.info/android-sharedpreferences-basics/