sharedpreferences does not store data. Error shows in getSharedPreferences this method. Error is in DetailPref key. And catlog error is : Unable to start activity ComponentInf com.example.add_fetch_data.MainActivity java.lang.NullPointerException. please any one help me what to do to store data Because I am new in Android.
public class MainActivity extends Activity {
Button addData, viewData, saveData, fetchData;
EditText editName, editAdd;
TextView textName, textAdd;
Dialog AddDialog, ViewDialog;
SharedPreferences pref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pref = getSharedPreferences("DetailPref", MODE_PRIVATE);
addData = (Button) findViewById(R.id.btn_add_data);
addData.setOnClickListener(new View.OnClickListener() {
String name, address;
#Override
public void onClick(View arg0) {
AddDialog = new Dialog(MainActivity.this);
AddDialog.setContentView(R.layout.add_fragment);
AddDialog.setTitle("Enter Details");
editName = (EditText) findViewById(R.id.ed_ad_name);
editAdd = (EditText) findViewById(R.id.ed_ad_add);
saveData = (Button) findViewById(R.id.save_data);
saveData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
name = editName.getText().toString();
address = editAdd.getText().toString();
SharedPreferences.Editor edit = pref.edit();
// Storing data using SharedPreferences
edit.putString("Name", name);
edit.putString("Address", address);
edit.commit();
AddDialog.dismiss();
}
});
AddDialog.show();
}
});
}
}
Try edit.apply() instead of commit().
Please clear your sharedPreferences first to test. You can do this with code or in application settings
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.clear();
editor.commit();
And, you are using 3 different tags. "Name", "Address" and "DetailPref":
FIRST OPTION
You need to save all in DetailPref.
Maybe you need a structure for this. Something like this
{"Name": "xxxxx" , address: "home"}
So you can do this:
#Override
public void onClick(View arg0) {
name = editName.getText().toString();
address = editAdd.getText().toString();
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor edit = sharedPref.edit();
JSONObject jsonToSave = new JSONObject();
jsonToSave.put("Name", name);
jsonToSave.put("Address", address);
// Storing data using SharedPreferences
edit.putString("DetailPref", jsonToSave.toString());
edit.commit();
AddDialog.dismiss();
}
SECOND OPTION
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prefName = getSharedPreferences("Name", MODE_PRIVATE);
prefAddress = getSharedPreferences("Address", MODE_PRIVATE);
addData = (Button) findViewById(R.id.btn_add_data);
addData.setOnClickListener(new View.OnClickListener() {
String name, address;
#Override
public void onClick(View arg0) {
AddDialog = new Dialog(MainActivity.this);
AddDialog.setContentView(R.layout.add_fragment);
AddDialog.setTitle("Enter Details");
editName = (EditText) findViewById(R.id.ed_ad_name);
editAdd = (EditText) findViewById(R.id.ed_ad_add);
saveData = (Button) findViewById(R.id.save_data);
saveData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
name = editName.getText().toString();
address = editAdd.getText().toString();
SharedPrefearences.Editor editName = prefName.edit();
SharedPreferences.Editor editAddress = prefAddress.edit();
// Storing data using SharedPreferences
editName.putString("Name", name);
editAddress.putString("Address", address);
editName.commit();
editAddress.commit();
AddDialog.dismiss();
}
});
AddDialog.show();
}
});
Related
I'm making an Android app and in my app, I add the feature of storing the login state.
My Splash screen:
public class Splash extends AppCompatActivity {
private SharedPreferences preferences;
public int a = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressbar);
new CountDownTimer(5000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
a = a + 1;
progressBar.setProgress(a);
}
#Override
public void onFinish() {
SharedPreferences preferences = getSharedPreferences("login", MODE_PRIVATE);
String check = preferences.getString("login", "off");
if (check.equals("on")) {
startActivity(new Intent(Splash.this, Menu.class));
} else {
startActivity(new Intent(Splash.this, LoginPage.class));
}
}
}.start();
} }
My Login screen:
public class LoginPage extends AppCompatActivity {
private SharedPreferences preferences;
Context context;
Button login, register, database;
EditText username;
EditText password;
TextView msg;
MyDBManager db;
static final int REGISTRATION_REQUEST = 1; // The request code
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loginpage);
db = new MyDBManager(this);
msg = (TextView) findViewById(R.id.msg);
login = (Button) findViewById(R.id.button);
register = (Button) findViewById(R.id.button2);
database = (Button) findViewById(R.id.button3);
username = (EditText) findViewById(R.id.user);
password = (EditText) findViewById(R.id.pass);
// Click and move to the next activity
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
db.open();
Cursor c = db.getUser(username.getText().toString(), password.getText().toString());
if (c.moveToFirst()) {
db.close();
context.startActivity(new Intent(context,Menu.class));
// Intent i=new Intent(getApplicationContext(),Menu.class); //
i.putExtra("Username", username.getText().toString()); //
startActivity(i); // call Login Activity
Store();
}
else
{
db.close();
// set error message when the username and/or password is not valid
msg.setText("Unable to login: wrong username or password!");
// Stay at the current activity.
}
}
private void Store() {
SharedPreferences preferences=context.getSharedPreferences("login",Context.MODE_PRIVATE);
SharedPreferences.Editor editor=preferences.edit();
editor.putString("login_status","on");
editor.commit();
}
});
// Click and move to the next activity
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(LoginPage.this, Registration.class);
startActivityForResult(intent, REGISTRATION_REQUEST);
}
});
// Click and move to the next activity
database.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(LoginPage.this, Database.class);
startActivity(intent);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REGISTRATION_REQUEST) {
//if(resultCode == Registration.RESULT_OK){
Log.d("Pikatchu", "User successfully registered!");
Bundle res = data.getExtras();
String result = res.getString("result");
System.out.println(result);
msg.setText(result);
}
}
}
My Menu screen:
public class Menu extends AppCompatActivity {
private SharedPreferences preferences;
Button startJourney, displayJourneys;
TextView msg; // where to display the name of the user
Button buttonLogout ;
/* the string is where to store data when we select something */
String db_username;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
buttonLogout = (Button) findViewById(R.id.btn_logout);
msg = (TextView) findViewById(R.id.msg);
startJourney = (Button) findViewById(R.id.recordingmode);
// Bundle bundle = getIntent().getExtras(); //
db_username = (bundle.getString("Username")); //// //// // Set
Welcome message to the user who logged in //
msg.setText("Welcome "+db_username);
// Click and move to the next activity // startJourney.setOnClickListener(new View.OnClickListener() { //
#Override // public void onClick(View v) { //
Intent intent = new Intent(Menu.this, Recordingmode.class); //
intent.putExtra("Username", db_username); //
startActivity(intent); // } // });
// Click and move to the next activity buttonLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences preferences=getSharedPreferences("login", Context.MODE_PRIVATE);
SharedPreferences.Editor editor=preferences.edit();
editor.putString("login_status","off");
editor.commit();
finish();
moveTaskToBack(true);
} });
}
}
But if I login in the app, the error is thrown:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null
object reference
I'm using SharedPreferences to create settings on one activity that will be applied on other activities. I've created the SharedPreferences in OnCreate, but then I need to set them in a second function that is called when a button is pressed. At the moment the app keeps crashing on launch if I put SharedPreferences anywhere except for OnCreate.
Problem is I don't seem to be able to carry sharedPreferences into the openNextPage function, as all mentions of it in openNextPage bring up an error saying :
Cannot resolve symbol sharedPreferences
So how can I carry the editor over to this function?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome_screen);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
Button nextBtn = findViewById(R.id.confSetBtn);
nextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openNextPage();
}
});
}
public void openNextPage(){
SharedPreferences.Editor editor = sharedPreferences.edit();
if(checkBox1.isChecked()){
editor.putBoolean("value1", true);
}
if(checkBox2.isChecked()){
editor.putBoolean("value2", true);
}
editor.apply();
boolean none = sharedPreferences.getBoolean("value1", false);
if(none){
finish();
}
else{
Intent intent = new Intent(welcomeScreen.this, newSettingsActivity.class);
startActivity(intent);
}
}
You can try it like this i have edited your code. I have declared this as property in your class.
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome_screen);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
Button nextBtn = findViewById(R.id.confSetBtn);
nextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openNextPage();
}
});
}
public void openNextPage(){
SharedPreferences.Editor editor = sharedPreferences.edit();
if(checkBox1.isChecked()){
editor.putBoolean("value1", true);
}
if(checkBox2.isChecked()){
editor.putBoolean("value2", true);
}
editor.apply();
boolean none = sharedPreferences.getBoolean("value1", false);
if(none){
finish();
}
else{
Intent intent = new Intent(welcomeScreen.this, newSettingsActivity.class);
startActivity(intent);
}
}
To access a variable across app declare it as:
public static SharedPreferences object;
Follow this link to understand how to use shared preferences in your app.
Link
Cheers!
Pass instance of SharedPreferences as an argument as follows
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome_screen);
// update 1
final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
Button nextBtn = findViewById(R.id.confSetBtn);
nextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// update 2
openNextPage(sharedPreferences);
}
});
}
// update 3
public void openNextPage(SharedPreferences sharedPreferences){
SharedPreferences.Editor editor = sharedPreferences.edit();
if(checkBox1.isChecked()){
editor.putBoolean("value1", true);
}
if(checkBox2.isChecked()){
editor.putBoolean("value2", true);
}
editor.apply();
boolean none = sharedPreferences.getBoolean("value1", false);
if(none){
finish();
}
else{
Intent intent = new Intent(welcomeScreen.this, newSettingsActivity.class);
startActivity(intent);
}
}
Dynamically created EditTexts by Add button, and also I have assigned them unique ID's using setId(), Now what I want to do is to get values from the dynamically created EditTexts when the user taps a button, then store all of them as Sharedpreferences
This is the code
Thank you guys
ADDED CODES
List<EditText> allEds = new ArrayList<EditText>();
Button btnSave, btnAdd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final LinearLayout layoutmain = (LinearLayout) findViewById(R.id.layoutmain);
btnAdd = (Button) findViewById(R.id.btnadd);
btnSave = (Button) findViewById(R.id.btnsave);
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
EditText ed = new EditText(ActivityOptions.this);
ed.setId(ed.generateViewId());
ed.setTag(allEds.size());
ed.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
layoutmain.addView(ed);
// Add also to the allEds
allEds.add(ed);
}
});
btnSave.setOnClickListener(new View.OnClickListener() {
EditText ed = new EditText(ActivityOptions.this);
#Override
public void onClick(View arg0) {
SharedPreferences.Editor editor = getPreferences(Context.MODE_PRIVATE).edit();
editor.putString("key" + ed.getTag().toString(), ed.getText().toString());
for (EditText ed : allEds) {
editor.putString("key" + ed.getTag().toString(), ed.getText().toString());
}
editor.commit();
}
});
Intent intent = new Intent(this, MainActivity.class);
ArrayList<String> allTexts = new ArrayList<>();
for (EditText e : allEds) {
allTexts.add(e.getText().toString());
}
intent.putExtra("Text", (Serializable) allTexts);
}
}
While creating every new EditText, you generate ids by setId() but I don't see how these are going to be useful in your code.
Instead set the tag of the EditText like this:
ed.setTag(allEds.size());
and add it to the list:
allEds.add(ed);
Now in each EditText's tag you have stored its ordinal number (zero based) in the list and when you want to store its value in SharedPreferences you can do:
SharedPreferences.Editor editor = getPreferences(Context.MODE_PRIVATE).edit();
editor.putString("key" + et.getTag().toString(), ed.getText().toString());
editor.commit();
or by using a loop through all the items in the list:
for (EditText ed : allEds) {
editor.putString("key" + et.getTag().toString(), ed.getText().toString());
}
editor.commit();
This way you stored all the text values of the EditTexts with keys like:
"key0", "key1", "key2",...
Edit
Of you want to open another activity and pass the list to it:
Intent intent = new Intent(this, AnotherActivity.class);
ArrayList<String> allTexts = new ArrayList<>();
for (EditText e : allEds) {
allTexts.add(e.getText().toString())
}
intent.putExtra("Text", (Serializable) allTexts);
and in the other activity's onCreate():
ArrayList<String> list = (ArrayList<String>) getIntent().getSerializableExtra("Texts");
Edit2
Replace the code in btnSave.setOnClickListener() and the lines below, with this code:
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
SharedPreferences.Editor editor = getPreferences(Context.MODE_PRIVATE).edit();
for (EditText ed : allEds) {
editor.putString("key" + ed.getTag().toString(), ed.getText().toString());
}
editor.commit();
Intent intent = new Intent(this, MainActivity.class);
ArrayList<String> allTexts = new ArrayList<>();
for (EditText e : allEds) {
allTexts.add(e.getText().toString());
}
intent.putExtra("Text", (Serializable) allTexts);
startActivity(intent);
}
});
You forgot to add the EditText's to your list, so the save button will know about them and get their inputs.
After that you need to specify the save button (which I believe you did, but I cannot see a reference of it in your code).
Lastly just implement the logic for the save button in its onClick() (save in SharedPreferences).
List<EditText> allEds = new ArrayList<EditText>();
Button btnSave,btnAdd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final LinearLayout layoutmain = (LinearLayout)findViewById(R.id.layoutmain);
btnAdd = (Button) findViewById(R.id.btnadd);
btnSave = (Button) findViewById(R.id.btnsave);
btnadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
EditText ed = new EditText(MainActivity.this);
ed.setId(ed.generateViewId());
ed.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
layoutmain.addView(ed);
// Add also to the allEds
allEds.add(ed);
}
});
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
for (EditText ed : allEds) {
editor.putString("saved_text_key", ed.getText().toString());
editor.commit();
}
}
});
}
The SharedPreferences doesn't save my username while I don't get any error. I have checked my method with some tutorials and I can't find what's wrong. I have tried both commit() and 'apply()' despite that can't make here a difference.
Someone who finds the error?
my code:
public class MainActivity extends AppCompatActivity implements AsyncResponse, View.OnClickListener {
EditText etUsername, etPassword;
ImageButton btnLogin;
String username;
CheckBox ckbx_login;
public static final String PREFS_NAME = "MyPrefsFile";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
etUsername = (EditText) findViewById(R.id.etUsername);
etPassword = (EditText) findViewById(R.id.etPassword);
btnLogin = (ImageButton) findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(this);
username = etUsername.getText().toString();
}
#Override
public void processFinish(String result) {
if(result.equals("success")) {
SharedPreferences.Editor editor = getApplicationContext().getSharedPreferences(PREFS_NAME,0).edit();
editor.putString("loginname",username);
editor.commit();
Intent in = new Intent(this, SubActivity.class);
String naam2= etUsername.getText().toString();
in.putExtra("naam2",naam2);
startActivity(in);
}
else{
Toast.makeText(this,"Inloggen mislukt", Toast.LENGTH_LONG).show();
}
}
#Override
public void onClick(View view) {
HashMap postData = new HashMap();
postData.put("mobile", "android");
postData.put("txtUsername", etUsername.getText().toString());
postData.put("txtPassword", etPassword.getText().toString());
PostResponseAsyncTask task = new PostResponseAsyncTask(this, postData);
task.execute("http://exemple.com");
}
And the second class:
public static final String PREFS_NAME = "MyPrefsFile";
String name;
TextView msg_welcome;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_sub);
msg_welcome = (TextView) findViewById(R.id.txtVwelcome);
SharedPreferences prefs = this.getSharedPreferences(PREFS_NAME,0);
String restored_loginname = prefs.getString("loginname",null);
if(restored_loginname != null) {
name = prefs.getString("name", "No name defined");
}
Toast.makeText(getApplicationContext(),name,Toast.LENGTH_LONG).show();
}
public void scan(View View){
zXingScannerView = new ZXingScannerView(getApplicationContext());
setContentView(zXingScannerView);
zXingScannerView.setResultHandler(this);
zXingScannerView.startCamera();
}
#Override
protected void onPause() {
super.onPause();
zXingScannerView.stopCamera();
}
#Override
public void handleResult(Result result) {
// Toast.makeText(getApplicationContext(),result.getText(),Toast.LENGTH_LONG).show();
Intent i = new Intent(getApplicationContext(), Avt_form2.class);
String qrcode = result.getText();
i.putExtra("qrcode",qrcode);
startActivity(i);
}
Btw I know that Postdata is outdated. I am looking to replace it.
Issue : currently your taking the value of username in onCreate when you don't have the user input so
username = etUsername.getText().toString();
should be executed after user input is available like in onclick
or
#Override
public void processFinish(String result) {
if(result.equals("success")) {
SharedPreferences.Editor editor = getApplicationContext().getSharedPreferences(PREFS_NAME,0).edit();
username = etUsername.getText().toString();
//^^^^^^^^^
editor.putString("loginname",username);
editor.commit();
Note : name was not previously used to store any value , i guess wanted to use name2
There is a lot of countries in this app including India, Pakistan, UAE, South Africa..etc. When clicking on name of a country, a new activity will be opened. It will be saved by share preference and when we open the app, the last activity will be opened. I created an app like this. I want to add one more thing to this app.
I want to go to countries list view by a button from the opened activity. The user can change the country here and when opening the app, the changed country's activity must be opened. If all countries are opened like this, there must be a option for choosing another country. I hope you will do this for me.
The project code which is done by me is given below.
The share preference will work on it. I want an option to change the country option.
** countries Listview (MainActivity)**
public class MainActivity extends AppCompatActivity {
CardView ind,pak,uae,south;
String clickedCard;
SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().hide();
ind = (CardView) findViewById(R.id.ind);
pak = (CardView) findViewById(R.id.pak);
ind.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent CltButton = new Intent(MainActivity.this, India.class);
clickedCard = "Button 1";
CltButton.putExtra("fromMain", clickedCard);
startActivity(CltButton);
}
});
pak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent mgButton = new Intent(MainActivity.this,Pak .class);
clickedCard = "Button 2";
mgButton.putExtra("fromMain2", clickedCard);
startActivity(mgButton);
}
});
}
private void checkPreferences() {
////INDIA Preference
prefs = getSharedPreferences("pref", MODE_PRIVATE);
if (prefs.getString("txt", "").equals("") || prefs.getString("lastActivity", "").equals("")) {
} else {
String txt = prefs.getString("txt", "");
String activity = prefs.getString("lastActivity", "");
Intent CltButton = new Intent(MainActivity.this, India.class);
CltButton.putExtra("fromMain", txt);
startActivity(CltButton);
finish();
}
////PAKISTAN Preference
prefs = getSharedPreferences("pref2", MODE_PRIVATE);
if (prefs.getString("txt2", "").equals("") || prefs.getString("lastActivity2", "").equals("")) {
} else {
String txt2 = prefs.getString("txt2", "");
String activity = prefs.getString("lastActivity", "");
Intent mgButton =MainActivity new Intent(MainActivity.this, Pak.class);
mgButton.putExtra("fromMain2", txt2);
startActivity(mgButton);
finish();
}
}
}
India Activity code
public class India extends AppCompatActivity {
String s;
SharedPreferences prefs;
Button buttonind;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_india);
buttonind = (Button) findViewById(R.id.buttonind);
buttonind.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent mgButton = new Intent(India.this, Main2Activity.class);
startActivity(mgButton);
}
});
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
if (bundle == null) {
s = "no data received";
} else {
s = bundle.getString("fromMain");
}
}
#Override
protected void onPause() {
super.onPause();
prefs = getSharedPreferences("pref", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("txt", s);
editor.putString("lastActivity", getClass().getName());
editor.apply();
}
}
Pak Activity Code
public class Pak extends AppCompatActivity {
String s;
SharedPreferences prefs;
Button buttonpak;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pak);
buttonpak = (Button) findViewById(R.id.buttonpak);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
if (bundle == null) {
s = "no data received";
} else {
s = bundle.getString("fromMain2");
}
buttonpak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent mgButton1 = new Intent(Pak.this, Main2Activity.class);
startActivity(mgButton1);
}
});
}
#Override
protected void onPause() {
super.onPause();
prefs = getSharedPreferences("pref2", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("txt2", s);
editor.putString("lastActivity2", getClass().getName());
editor.apply();
}
}
You are very welcome for this - It took me some time to do and it is working exactly like you want it to.
MainActivity:
public class MainActivity extends AppCompatActivity {
CardView ind,pak,uae,south;
String clickedCard;
SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().hide();
ind = (CardView) findViewById(R.id.ind);
pak = (CardView) findViewById(R.id.pak);
uae = (CardView) findViewById(R.id.uae);
south = (CardView) findViewById(R.id.south);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
if (bundle!= null) {
SharedPreferences preferences,preferences1,preferences2,preferences3,preferences4;
SharedPreferences.Editor editor,editor1,editor2,editor3,editor4;
preferences = getSharedPreferences("pref", Context.MODE_PRIVATE);
editor = preferences.edit();
editor.clear();
editor.apply();
preferences1 = getSharedPreferences("pref1", Context.MODE_PRIVATE);
editor1 = preferences1.edit();
editor1.clear();
editor1.apply();
preferences2 = getSharedPreferences("pref2", Context.MODE_PRIVATE);
editor2 = preferences2.edit();
editor2.clear();
editor2.apply();
preferences3 = getSharedPreferences("pref3", Context.MODE_PRIVATE);
editor3 = preferences3.edit();
editor3.clear();
editor3.apply();
preferences4 = getSharedPreferences("pref4", Context.MODE_PRIVATE);
editor4 = preferences4.edit();
editor4.clear();
editor4.apply();
} else {
checkPreferences();
}
//checkPreferences();
ind.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent CltButton = new Intent(MainActivity.this, India.class);
clickedCard = "Button 1";
CltButton.putExtra("fromMain", clickedCard);
startActivity(CltButton);
finish();
}
});
pak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent mgButton = new Intent(MainActivity.this,Pak.class);
clickedCard = "Button 2";
mgButton.putExtra("fromMain2", clickedCard);
startActivity(mgButton);
finish();
}
});
uae.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent keraButton = new Intent(MainActivity.this, Uae.class);
clickedCard = "Button 3";
keraButton.putExtra("fromMain3", clickedCard);
startActivity(keraButton);
finish();
}
});
south.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent ButtonactivityIntent = new Intent(MainActivity.this, South.class);
clickedCard = "Button 4";
ButtonactivityIntent.putExtra("fromMain4", clickedCard);
startActivity(ButtonactivityIntent);
finish();
}
});
}
private void checkPreferences() {
////INDIA Preference
prefs = getSharedPreferences("pref", MODE_PRIVATE);
if (prefs.getString("txt", "").equals("") || prefs.getString("lastActivity", "").equals("")) {
} else {
String txt = prefs.getString("txt", "");
String activity = prefs.getString("lastActivity", "");
Intent CltButton = new Intent(MainActivity.this, India.class);
CltButton.putExtra("fromMain", txt);
startActivity(CltButton);
finish();
}
////PAKISTAN Preference
prefs = getSharedPreferences("pref2", MODE_PRIVATE);
if (prefs.getString("txt2", "").equals("") || prefs.getString("lastActivity2", "").equals("")) {
} else {
String txt2 = prefs.getString("txt2", "");
String activity = prefs.getString("lastActivity", "");
Intent mgButton = new Intent(MainActivity.this, Pak.class);
mgButton.putExtra("fromMain2", txt2);
startActivity(mgButton);
finish();
}
////U A E Preference
prefs = getSharedPreferences("pref3", MODE_PRIVATE);
if (prefs.getString("txt3", "").equals("") || prefs.getString("lastActivity3", "").equals("")) {
} else {
String txt2 = prefs.getString("txt3", "");
String activity = prefs.getString("lastActivity", "");
Intent mgButton = new Intent(MainActivity.this, Uae.class);
mgButton.putExtra("fromMain3", txt2);
startActivity(mgButton);
finish();
}
//// SOUTH AFRICA Preference
prefs = getSharedPreferences("pref4", MODE_PRIVATE);
if (prefs.getString("txt4", "").equals("") || prefs.getString("lastActivity4", "").equals("")) {
} else {
String txt2 = prefs.getString("txt4", "");
String activity = prefs.getString("lastActivity", "");
Intent mgButton = new Intent(MainActivity.this, South.class);
mgButton.putExtra("fromMain4", txt2);
startActivity(mgButton);
finish();
}
}
}
India.java:
public class India extends AppCompatActivity {
String s;
SharedPreferences prefs;
Button buttonind;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_india);
buttonind = (Button) findViewById(R.id.buttonind);
buttonind.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String test = "";
Intent mgButton2 = new Intent(India.this, MainActivity.class);
mgButton2.putExtra("test", test);
startActivity(mgButton2);
finish();
}
});
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
if (bundle == null) {
s = "no data received";
} else {
s = bundle.getString("fromMain");
}
}
#Override
protected void onPause() {
super.onPause();
prefs = getSharedPreferences("pref", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("txt", s);
editor.putString("lastActivity", getClass().getName());
editor.apply();
}
}
Pakistan.java
public class Pak extends AppCompatActivity {
String s;
SharedPreferences prefs;
Button buttonpak;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pak);
buttonpak = (Button) findViewById(R.id.buttonpak);
buttonpak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String test = "";
Intent mgButton2 = new Intent(Pak.this, MainActivity.class);
mgButton2.putExtra("test", test);
startActivity(mgButton2);
finish();
}
});
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
if (bundle == null) {
s = "no data received";
} else {
s = bundle.getString("fromMain2");
}
}
#Override
protected void onPause() {
super.onPause();
prefs = getSharedPreferences("pref2", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("txt2", s);
editor.putString("lastActivity2", getClass().getName());
editor.apply();
}
}
You can repeat the process for all the other countries. In MainActivity where I check if (bundle!= null) can be simplified, but it is working.