I am tryting to simply check to load the correct starting activity i do:
public class MainActivity extends AppCompatActivity {
public static final String TAG = "MainActivity";
public SharedPreferences sharedPreferences = MyApplication.getAppContext().getSharedPreferences("sharedPrefs", MODE_PRIVATE);
public SharedPreferences.Editor editor = sharedPreferences.edit();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
boolean onBoardingComplete = sharedPreferences.getBoolean("firstRun", true);
if(onBoardingComplete){
Intent navIntent = new Intent(this, NavigationStartActivity.class);
startActivity(navIntent);
}else{
Intent onBoardIntent = new Intent(this, OnBoardingActivity.class);
startActivity(onBoardIntent);
}
}
I get a null pointer exception on the initialisation of sharedPreferences effectively line 5 here. My sharedPrefs file exists in the storage data/data/com.myap/shared_prefs/sharedPrefs.xml
I have no idea why this would return null.
move it inside onCreate because outside context is null
public class MainActivity extends AppCompatActivity {
public static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sharedPreferences = getSharedPreferences("sharedPrefs", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
boolean onBoardingComplete = sharedPreferences.getBoolean("firstRun", true);
if (onBoardingComplete) {
Intent navIntent = new Intent(this, NavigationStartActivity.class);
startActivity(navIntent);
} else {
Intent onBoardIntent = new Intent(this, OnBoardingActivity.class);
startActivity(onBoardIntent);
}
}
}
Related
I've been experimenting for a couple of hours now on how to save the progress of a progressBar even if I closed/destroyed the app. I tried using the same method in TextViews and it works just fine. So, I'm wondering where I went wrong. Below is my code that I've done and any response is greatly appreciated! Have a nice day!
public class MainActivity extends AppCompatActivity {
public static final String PROGRESS = "progress";
private int CurrentProgress;
private ProgressBar progressBar;
private Button addProgress;
public static final String SHARED_PREFS="sharedPrefs";
private int getCurrentProgress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = findViewById(R.id.progressBar);
addProgress = findViewById(R.id.addProgress);
progressBar.setMax(1000);
addProgress.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CurrentProgress = CurrentProgress + 100;
progressBar.setProgress(CurrentProgress);
saveData();
}
});
loadData();
updateData();
}
public void saveData(){
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(PROGRESS, CurrentProgress);
editor.apply();
}
public void loadData() {
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
getCurrentProgress = sharedPreferences.getInt(PROGRESS, CurrentProgress);
}
public void updateData() {
progressBar.setProgress(CurrentProgress);
}
}
There are a few problems with your logic and syntax. Logic first:
First, when you're setting the value of getCurrentProgress in the loadData method, the second argument of .getInt is the default value that you want to set getCurrentProgress to. Right now, you're saying that if PROGRESS is not found in sharedPrefs, then the getCurrentProgress will be set to CurrentProgress, which is empty. Just change it to whatever you want the default value to be, probably zero or one:
getCurrentProgress = sharedPreferences.getInt(PROGRESS, 0);
Second, in your updateData method, you're setting progressBar's progress to CurrentProgress, which is, again, empty. You should be setting it to getCurrentProgress.
For syntax: your choice of variable names is very confusing. You should not name an int getCurrentProgress, that is the name of a method. You should not capitalize a variable name, CurrentProgress looks like a class. Also, make sure your indentations line up properly - the calls to loadData and updateData in onCreate are indented too far and it is difficult to read.
Also, I recommend adding more descriptive names to your variables, eg addProgress might be better as addProgressBtn. This helps you keep track of things better once you have a more complicated layout.
Here is what the code should look like:
public class MainActivity extends AppCompatActivity {
public static final String PROGRESS = "progress";
private int currentProgress;
private ProgressBar progressBar;
private Button addProgressBtn;
public static final String SHARED_PREFS="sharedPrefs";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = findViewById(R.id.progressBar);
addProgressBtn = findViewById(R.id.addProgress);
progressBar.setMax(1000);
addProgressBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
currentProgress = currentProgress + 100; // currentProgress += 100 works too
progressBar.setProgress(currentProgress);
saveData();
}
});
loadData();
updateData();
}
public void saveData(){
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(PROGRESS, currentProgress);
editor.apply();
}
public void loadData() {
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
currentProgress = sharedPreferences.getInt(PROGRESS, 0);
}
public void updateData() {
progressBar.setProgress(currentProgress);
}
}
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);
}
}
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.
I have one button in mainactivity when i click on button formactivty opened then after saved the data and i killed the app it display from main activity, it doesn't show welcome activity by using shared preference. any one can solve this one
Main Activity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void open(View v) {
Intent i = new Intent(MainActivity.this,Form.class);
startActivity(i);
}
}
FormActivty
public class Form extends Activity {
SharedPreferences sp;
public static String Filename= "LoginFile";
public static String key = "status";
EditText namee,emaill;
String Name,Email;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sp = getSharedPreferences(Filename,MODE_PRIVATE);
boolean res = sp.getBoolean(key,false);
if (res) {
setContentView(R.layout.welcom);
} else {
setContentView(R.layout.form);
}
}
public void save(View v) {
namee = (EditText)findViewById(R.id.name);
emaill = (EditText)findViewById(R.id.email);
Name = namee.getText().toString();
Email = emaill.getText().toString();
SharedPreferences.Editor ed = sp.edit();
ed.putBoolean(key,true);
ed.putString("k1",Name);
ed.putString("k2",Email);
ed.commit();
Intent i = new Intent(this,Welcome.class);
startActivity(i);
}
}
Welcome Activity
public class Welcome extends Activity {
SharedPreferences sp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcom);
sp = getSharedPreferences(Form.Filename,MODE_PRIVATE);
TextView tv= (TextView)findViewById(R.id.text);
TextView tv1= (TextView)findViewById(R.id.text1);
String username,email;
Intent i = getIntent();
Bundle b = new Bundle();
b= i.getExtras();
username = sp.getString("k1","");
email = sp.getString("k2","");
tv.setText(username);
tv1.setText(email);
}
public void logout(View v) {
SharedPreferences.Editor ed = sp.edit();
ed.putBoolean(Form.key,false);
ed.commit();
Intent i = new Intent(this,MainActivity.class);
startActivity(i);
}
}
On your MainActivity, under onCreate(), there should be a code that checks if your SharedPreference is empty. If it's empty, it should go to Form.class or it should not do anything since you have a button there in MainActivity. If not, then go to Welcome.class. You're almost there, just do some minor tweaks on your code and you'll get it.
public class MainActivity extends AppCompatActivity {
SharedPreferences sp;
public static String Filename= "LoginFile";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sp = getSharedPreferences(Filename,MODE_PRIVATE);
String name = sp.getString("k1", "");
if(!name.isEmpty()){
Intent intent = new Intent(MainActivity.this, Welcome.class);
startActivity(intent);
}
}
public void open(View v) {
Intent i = new Intent(MainActivity.this,Form.class);
startActivity(i);
}
}
If you'll notice on this code, every time the app is killed and you start it again, it'll check if sharedpreference is empty. If not, it will go directly to Welcome.class.