how to pass extra intent to two activities - android

i have an app that on the first activity asks the persons name on the second page it displays the name in a sentence i want to use the name in the third fourth or 9th activity how do i properly declare it (public?) and call it when and where ever i need it? this is my code sending it
Main
public class MainActivity extends Activity {
Button ok;
EditText name;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name=(EditText)findViewById(R.id.editText);
Typeface font_a = Typeface.createFromAsset(getAssets(),"fonts/MarkerFelt.ttf");
name.setTypeface(font_a);
ok=(Button)findViewById(R.id.button);
Typefacefont_b=Typeface.createFromAsset(getAssets(),
"fonts/SignPaintersGothicShaded.ttf");
ok.setTypeface(font_b);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String nameStr = name.getText().toString();
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
intent.putExtra("NAMEDATA",nameStr);
startActivity(intent);
}
});
}
and this is activity 2 receiving it
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
t = (TextView)findViewById(R.id.textView3);
Typeface font_b = Typeface.createFromAsset(getAssets(),"fonts/MarkerFelt.ttf");
t.setTypeface(font_b);
String n = this.getIntent().getStringExtra("NAMEDATA");
t.setText(n);
so please how would i reuse this?

Use SharedPreferences to save the name or whatever variable you need, then read whenever you need it. First, create global in MainActivity which will be used as preference file name:
public static final String PREFS_NAME = "MyPrefsFile";
Then, to save:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("name", name);
editor.commit();
to load:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
String name = settings.getString("name", "John");
Once saved, the prefs are accessible for every activity.
So in your case, save the name when ok button is pressed:
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String nameStr = name.getText().toString();
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("name", nameStr);
editor.commit();
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
startActivity(intent);
}
});
Then read it:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
t = (TextView)findViewById(R.id.textView3);
Typeface font_b = Typeface.createFromAsset(getAssets(),"fonts/MarkerFelt.ttf");
t.setTypeface(font_b);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
String n = settings.getString("name", "defaultName");
t.setText(n);
You can do similarly in every activity you need it. See docs here.

You have a number of different approaches to share data between activities. I would say which one you use depends on the ultimate source and destination of the data.
Pass through intents - This is the method you are currently using. To proceed, just keep passing the name to the next intent.
Save to SharedPreference - This method you save the information to the "preference" file of the application. This is useful if the the user is setting up a profile or other semi-fixed information.
Write it to a DB - Here you would create a a new SQLite table for user information and write new rows to it for the name, password, and other info. This has way more overhead and is really only useful if you have multiple users in the same application
Save to a singleton - In this case you create a static class with public properties that can be set. This would be least favorable all the information is lost on application close, but could be useful for temporary creation and retention across many activities. Be warned: bad programming can make singletons a nightmare

Create class extending from Application class.
Implement setter and getter inside that class like,
public class GlobalClass extends Application {
//create setters and getters here
public void setUserInfo(String userInfo) {
}
public void getUserInfo() {
return userInfo;
}
}
then you can use this from any activity like,
GlobalClass app = (GlobalClass ) getApplication();
app.getUserInfo();

Related

How can I store values from an activity so that I can use them later?

I would like to store a few values from an Activity so that when I navigate away from the activity, they still appear there.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
Button AddButton = (Button) findViewById(R.id.AddButton);
AddButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText firstNumEditText = (EditText) findViewById(R.id.firstNumEditText);
EditText secondNumEditText = (EditText) findViewById(R.id.secondNumEditText);
TextView ResultTxtView = (TextView) findViewById(R.id.ResultTxtView);
int num1 = Integer.parseInt(firstNumEditText.getText().toString());
int num2 = Integer.parseInt(secondNumEditText.getText().toString());
int result = num1 + num2;
ResultTxtView.setText(result + "");
}
});
In this case, I only want to save the values of num1, num2 and result. I would like it so that if I navigate back to the main menu, or if I go and do some other app and come back tomorrow, that the values would still be there.
You can store these values by using SharedPreferences.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
Button AddButton = (Button) findViewById(R.id.AddButton);
AddButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText firstNumEditText = (EditText) findViewById(R.id.firstNumEditText);
EditText secondNumEditText = (EditText) findViewById(R.id.secondNumEditText);
TextView ResultTxtView = (TextView) findViewById(R.id.ResultTxtView);
int num1 = Integer.parseInt(firstNumEditText.getText().toString());
int num2 = Integer.parseInt(secondNumEditText.getText().toString());
int result = num1 + num2;
ResultTxtView.setText(result + "");
// You can store these values here
// ...
}
});
protected void onResume() {
// And read these values here and set to your ResultTxtView.
// ...
}
You can use shared preferences in your app for saving the data and for using the same data later as mentioned below:
SharedPreferences sp = getSharedPreferences("Data",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString("Name", "Alex");
editor.putString("Email", "alex#gmail.com");
editor.commit();
And then if you want to get the same data in another activity you do this as mentioned below:
SharedPreferences sp= ActvivityA.this.getSharedPreferences("Data",Context.MODE_PRIVATE);
String name = sp.getString("Name");
String email = sp.getString("Email");
This data will be saved till you will not clear the cache of the application or you will not install a new update of the app so in this way you can use this data anywhere in the app.
In this case, I only want to save the values of num1, num2 and result. I would like it so that if I navigate back to the main menu, or if I go and do some other app and come back tomorrow, that the values would still be there.
When you need the values to be persisted across app launches, then Shared Preferences or a data store like SQLite/Room would be the way to go.
Shared Preferences : If the values stored are key value pairs and are limited in size and does not have to scale, then Shared Preference would suit your need.
SqLite : If the data that you store would scale and would become larger in time, then you need to look at a data store like SQLite where you can do Async operations.
create on class which extends Application and create variable to hold specific value and register that class in manifest
in manifest in application tag specify your application class name
public class MyApplication extends Application {
private MyApplication sInstance;
int result;
//write getter setter for result variable same for num1 and num2
#Override
public void onCreate() {
super.onCreate();
sInstance = this;
}
public static MyApplication getInstance() {
return sInstance;
}
}
in onClick set that variable value like MyApplication.getInstnce().setResult();
and in onCreate of set textview value with MyApplication.getInstance().getResult();
Use Following methods for save/retrieve string using SharedPreferences
public static int getIntPreferences(Context context,String key) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
int savedPref = sharedPreferences.getInt(key, null);
return savedPref;
}
public static void saveIntPreferences(Context context,String key, int value) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(key, value);
editor.commit();
}
Save num1,num2 and result using saveIntPreferences when you leave 1st Activity.
After getting back on 1st Activity, you can get saved value using getIntPreferences

Having more than one Launcher Activity

I'm working on an App which can read out car data.
When the user opens it the first time he must choose the car he drives (this is in MainActivity).
What I want to do is, that the user must not always choose his car when opening the App.
The App should directly go to the car data Activity of his car after the user chose the car once.
Can you please give me some ideas how to do that?
I already wrote in the AndroidManifest that MainActivity and this Car Data Activity are Launcher Activities but I think it will not work because how should the App know which Activity should be launch Activity.
Please help me a bit!
You can use SharedPreference for this process.
SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(YourLaunchActivity.this);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean("isCarSet", true);
editor.apply();
Then Check Everytime Launch activity
if (sharedpreferences.getBoolean("isCarSet", false)) {
Intent i =new Intent(YourLaunchActivity.this,SecondActivty.class);
startActivity(i);
finish();
}
I will suggest you use Shared Preference.
So what you can do in this case is that you can use Shared Preferences. Once the data is registered in Shared Preference, every time the app is started read the data from Shared Preference and go directly to the desired page.
Sample code for Shared Preference:
Setting values in Preference:
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", "Elena");
editor.putInt("idName", 12);
editor.apply();
Retrieve data from preference:
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
int idName = prefs.getInt("idName", 0); //0 is the default value.
}
more help at: https://developer.android.com/guide/topics/data/data-storage#pref
The other way around is to use sessions, but being at a nascent stage, I would suggest you to use Shared Preference.
You should create two activities:
- MainActivity (marked as launcher activity in manifest) where you show car data.
- CarChooseActivity where you choose car.
In MainAcitivity on onResume() method try to read car data (from SharedPreferences or other source). If this succeeded then show you car data, otherwise open CarChooseActivity.
Something like that:
public class MainActivity extends AppCompatActivity {
//code omitted
#Override
protected void onResume() {
super.onResume();
Car car = readCar();
if (car == null){//no car saved
Intent i = new Intent(this, CarChooseActivity.class);
startActivity(i);
}
}
//code omitted
}
public class CarChooseActivity extends AppCompatActivity {
Button mSaveButton;
#Override
public void onCreate(#Nullable Bundle savedInstanceState, #Nullable PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
//code omitted
mSaveButton = findViewById(R.id.savebutton);
mSaveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveCar();//save choosed car to SharedPreferences or other storage
finish();
}
});
//code omitted
}
}

Call another class and getText

public class ustawienia extends MainActivity {
EditText kryptonim;
public String test;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ustawienia);
kryptonim = (EditText) findViewById(R.id.edit_kryptonim);
test = kryptonim.getText().toString();
}
public String call_back(){
return test;
}
}
When call call_back() from another class I've got error: Unable to start activity ComponentInfo. What's wrong with that?
When you close an activity all data from it is lost, so unless both activities are runing at the same time you can't retrieve data. You could use shared prefrences instead.
// IN ORDER TO WRITE TO A FILE
SharedPreferences.Editor prefs = getSharedPreferences("PrefsName", MODE_PRIVATE).edit();
prefs.putString("test", kryptonim.getText().toString());
prefs.apply(); // use prefs.commit(); if this doesn't work
In order to read data
SharedPreferences prefsR = getSharedPreferences("PrefsName", MODE_PRIVATE); // you could also write 0 instead MODE_PRIVATE
String restoredText = prefsR.getString("test", null);
Ofcourse you need to import SharedPrefs , and put this in oncreate or wherever you want... let me now if it works :)

Checking if Shared Preferences Exist

Trying to check if if Shared Preferences exist or not. What I need is to allow the user to arrive on a page if they have been here before (i.e. shared preferences exist and are not equal to "") or put them to the welcome page if it is their first time on the app (i.e. shared preferences are blank as user hasn't entered any data).
public class PersonalDetails extends Activity {
private SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_personal_details);
if (sharedPreferences.contains("")) {
Intent intent = new Intent(PersonalDetails.this, Welcome.class);
startActivity(intent);
}
I think getPreferences needs two inputs as below.
public abstract SharedPreferences getSharedPreferences(String name,
int mode);
// Example
getSharedPreferences("your_app_name", MODE_PRIVATE);

save the data using shared preference in android

i am new developer in android applications.i would like to save the data using shared preference concept.i am saving the data in one activity and get the same data in another activity.here i would like to send the String a[]={"one","two","three"} one activity to another activity.i have written code as follows
Main1.java
public class Main1 extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SharedPreferences shp=getSharedPreferences("TEXT", 0);
final Editor et=shp.edit();
((Button)findViewById(R.id.button1)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String s1=((EditText)findViewById(R.id.editText1)).getText().toString();
et.putString("DATA", s1);
String s2[]={"one","two","three"};
//here i would like to save the string array
et.commit();
Intent it=new Intent(Main1.this,Main2.class);
startActivity(it);
}
});
}
Main2.java
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
String kk=getSharedPreferences("TEXT", 0).getString("DATA", null);
//here i would like to get the string array of Main1.java
((EditText)findViewById(R.id.editText1)).setText(kk);
}
can we get the string array values from Main1.java to Main2.java?
Put it into the starting intent:
Intent it = new Intent(Main1.this,Main2.class);
it.putExtra("MY_STRING_ARRAY", s2);
Get it back in the second activity:
String[] myStringArray = getIntent().getStringArrayExtra("MY_STRING_ARRAY");
If you want to send data from one activity to another then the best way would be send data using Intent object's putExtra method
Intent i = new Intent(Activity1.this, Activity2.class);
i.putExtra("data1", "some data");
i.putExtra("data2", "another data");
i.putExtra("data3", "more data");
startActivity(i);
and you can get the data from receiving activity Activity2 like this
Object data1 = getIntent().getExtras().get("data1");
Hope that helps
If you want to save your information via SharedPreference not just pass it along activities, use some code like this:
SharedPreferences settings = getSharedPreferences(GAME_PREFERENCES, MODE_PRIVATE);
SharedPreferences.Editor prefEditor = settings.edit();
prefEditor.putString("string_preference", "some_string");
prefEditor.putInt("int_preference", 18);
prefEditor.commit();
The commit command is the responsable of actually saving data to SharedPreferences.

Categories

Resources