I am developing an app in which I need to manage users session i.e when user logs in for the first time he must see the login page and once he is authenticated he is redirected to the home screen and tht time a value is set in sharedpreferences. Now on the home screen when the user clicks on logout button the values in shsredpreferences must be cleared and the next time the user opens the app he must be directed to login page.Unless and until user clicks logout he must not be shown the login page.
I am able to store values in sharedpreferences but not able to delete them.
here is my code for loginpage.java
package com.sess.eg;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class loginpage extends Activity {
/** Called when the activity is first created. */
EditText acc,user,pin;
Button login;
StringBuilder builder = new StringBuilder();
String UserName;
SharedPreferences.Editor prefs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// SharedPreferences prefs1 = getPreferences(MODE_WORLD_READABLE);
// UserName= prefs1.getString("User", "Abcdef");
//
// System.out.println(UserName);
//
// if(UserName.equals("Ad"))
//
// {
// System.out.println(UserName);
// Intent i=new Intent(loginpage.this,homepage.class);
// startActivity(i);
// }
setContentView(R.layout.main);
acc = (EditText) findViewById(R.id.ed_login_acc);
user = (EditText) findViewById(R.id.ed_user_acc);
pin = (EditText) findViewById(R.id.ed_pin_acc);
login = (Button) findViewById(R.id.login_button);
SharedPreferences prefs1 = getPreferences(MODE_WORLD_READABLE);
login.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v) {
prefs.putString("User", "Ad");
prefs.commit();
//System.out.println(sendJson1());
//startService(new Intent(Login.this, MyService.class));
Intent i = new Intent(loginpage.this, homepage.class);
startActivity(i);
finish();
//System.out.println(UserName);
}
});
}
#Override
protected void onStart() {
SharedPreferences prefs1 = getPreferences(MODE_WORLD_READABLE);
UserName= prefs1.getString("User", "Abcdef");
System.out.println(UserName);
if(UserName.equals("Ad"))
{
System.out.println(UserName);
Intent i=new Intent(loginpage.this,homepage.class);
startActivity(i);
finish();
}
super.onStart();
}
}
here is my code for homepage.java
package com.sess.eg;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class homepage extends Activity{
Button logout;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home3);
logout = (Button) findViewById(R.id.logout);
logout.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v) {
SharedPreferences.Editor prefs = getPreferences(MODE_WORLD_WRITEABLE).edit();
prefs.clear();
// prefs.commit();
SharedPreferences prefs1 = getPreferences(MODE_WORLD_READABLE);
String UserName= prefs1.getString("User", "Abcdef");
System.out.println(UserName);
finish();
}
});
}
}
In your code:
//prefs.commit();
Change this. Remove it from the comments.
prefs.commit();
commit() is called to save your preferences changes.
"Commit your preferences changes back from this Editor to the SharedPreferences object it is editing. This atomically performs the requested modifications, replacing whatever is currently in the SharedPreferences.
Note that when two editors are modifying preferences at the same time, the last one to call commit wins. "
Read here.
You have commented out the calls to prefs.commit(). Uncomment them.
Related
I have this login code where I don't secure it with sharedpreference because I don't know how to use it LOL. Can somebody teach me how to insert it into my code? Thanks. :D
Login
package com.example.kun.carkila;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.kosalgeek.genasync12.AsyncResponse;
import com.kosalgeek.genasync12.PostResponseAsyncTask;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
final String LOG = "MainActivity";
Button btnLogin;
EditText etUsername, etPassword;
TextView tvRegister;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
etUsername = (EditText) findViewById(R.id.etFirstname);
etPassword = (EditText) findViewById(R.id.etPassword);
btnLogin = (Button) findViewById(R.id.btnLogin);
tvRegister = (TextView) findViewById(R.id.tvRegister);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
HashMap postData = new HashMap();
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
postData.put("username", username);
postData.put("password", password);
PostResponseAsyncTask task1 = new PostResponseAsyncTask(MainActivity.this, postData,
new AsyncResponse() {
#Override
public void processFinish(String s) {
if (s.contains("renterowner")) {
Toast.makeText(MainActivity.this, "Renter Login Successful!", Toast.LENGTH_SHORT).show();
Intent in = new Intent(MainActivity.this, ListActivity.class);
startActivity(in);
finish();
} else if (s.contains("ownerrenter")) {
Toast.makeText(MainActivity.this, "Owner Login Successful!", Toast.LENGTH_SHORT).show();
Intent in = new Intent(MainActivity.this, ownerhome.class);
startActivity(in);
finish();
} else {
Toast.makeText(MainActivity.this, "Login Failed!", Toast.LENGTH_SHORT).show();
}
}
});
task1.execute("http://carkila.esy.es/authenticate.php");
}
});
tvRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent in = new Intent(MainActivity.this, RegisterActivity.class);
startActivity(in);
}
});
}
}
Does my code still have a chance of being secured with a sharedpreference? Thanks a lot if someone helped me. And also how to create a logout? Thaaanks :D
You can use this line of code
SharedPreferences preferences = getActivity().getPreferences(Context.MODE_PRIVATE); //updated this line
SharedPreferences.Editor editor = preferences.edit();
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
// Save to SharedPreferences
editor.putString("username", token);
editor.putString("password", token);
editor.apply();
Where you want to save username and password just call this line of code
and where you want to get this data you can use this line of code :
SharedPreferences preferences = getActivity().getPreferences(Context.MODE_PRIVATE); // update
String username = preferences.getString("username", null);
String password = preferences.getString("password", null);
And all this worked for me... You may use this in your app Good luck for your app.
Read this page, you should be able to implement it afterwards :)
https://developer.android.com/training/basics/data-storage/shared-preferences.html#GetSharedPreferences
To be secured, you can specify a context.MODE_PRIVATE, such as:
MODE_PRIVATE
File creation mode: the default mode, where the created file can only be accessed by the calling application (or all applications sharing the same user ID).
Hello i'm working on my android project. I have created an activity where the use gets four buttons, n i want the user to select any one. I have done this by setting other buttons to .setClickable(false). But when I restart or say relaunch the app again all the buttons get enabled. I want that when user selects a button it should save its choice, so that on retstart of app, the user doesn't get confused. Below is the piece of code:
Notifications.class
package com.mateoj.multiactivitydrawer;
import android.app.Notification;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.NotificationCompat;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.mateoj.multiactivitydrawer.department.dept_1styeartab;
import com.pushbots.push.Pushbots;
public class notifications extends BaseActivity {
private WebView webView;
Button clickButton;
Button clickButton1;
Button clickButton2;
Button clickButton3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Pushbots.sharedInstance().init(this);
Pushbots.sharedInstance().setCustomHandler(customHandler.class);
setContentView(R.layout.activity_notifications);
final SharedPreferences preferences = getSharedPreferences("com.mateoj.multiactivitydrawer", MODE_PRIVATE);
final SharedPreferences.Editor editor = preferences.edit();
clickButton = (Button) findViewById(R.id.ncs);
clickButton1 = (Button) findViewById(R.id.nmech);
clickButton2 = (Button) findViewById(R.id.nece);
clickButton3 = (Button) findViewById(R.id.neee);
clickButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent show = new Intent(getApplicationContext(), noti_cse.class);
Pushbots.sharedInstance().tag("cse");
Pushbots.sharedInstance().untag("mech");
Pushbots.sharedInstance().untag("ece");
Pushbots.sharedInstance().untag("eee");
editor.putString("session", "cse").commit();
editor.commit();
startActivity(show);
}
});
clickButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent show = new Intent(getApplicationContext(), noti_mech.class);
Pushbots.sharedInstance().tag("mech");
Pushbots.sharedInstance().untag("ece");
Pushbots.sharedInstance().untag("eee");
Pushbots.sharedInstance().untag("cse");
editor.putString("session", "mech").commit();
editor.commit();
startActivity(show);
}
});
clickButton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent show = new Intent(getApplicationContext(), noti_ece.class);
Pushbots.sharedInstance().tag("ece");
Pushbots.sharedInstance().untag("mech");
Pushbots.sharedInstance().untag("eee");
Pushbots.sharedInstance().untag("cse");
editor.putString("session", "ec").commit();
editor.commit();
startActivity(show);
}
});
clickButton3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent show = new Intent(getApplicationContext(), noti_eee.class);
Pushbots.sharedInstance().tag("eee");
Pushbots.sharedInstance().untag("ece");
Pushbots.sharedInstance().untag("mech");
Pushbots.sharedInstance().untag("cse");
editor.putString("session", "eee").commit();
editor.commit();
startActivity(show);
}
});
onStartUp();
}
private void onStartUp()
{
SharedPreferences sharedPreferences = getSharedPreferences("com.mateoj.multiactivitydrawer", Context.MODE_PRIVATE);
String str = sharedPreferences.getString("session", "");
if (str.equals("cs")) {
clickButton.setClickable(true);
clickButton1.setClickable(false);
clickButton2.setClickable(false);
clickButton3.setClickable(false);
} else if (str.equals("mech")) {
clickButton.setClickable(false);
clickButton1.setClickable(true);
clickButton2.setClickable(false);
clickButton3.setClickable(false);
} else if (str.equals("ec")) {
clickButton.setClickable(false);
clickButton1.setClickable(false);
clickButton2.setClickable(true);
clickButton3.setClickable(false);
} else if (str.equals("eee")) {
clickButton.setClickable(false);
clickButton1.setClickable(false);
clickButton2.setClickable(false);
clickButton3.setClickable(true);
}
}
/* private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
} */
#Override
protected boolean useDrawerToggle() {
return false;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_credits)
return true;
if (item.getItemId() == android.R.id.home)
onBackPressed();
return super.onOptionsItemSelected(item);
}
}
So what should be changed here
One thing you could do is save the state of the Button (Everytime you/user click on the Button save the true or false on your SharedPreferences) and everytime you start the Activity the value of setClickable() put the result of your SharedPrefernce.
That's an option, but there are a lot of ways to do it, that's one of them.
I don't know this framework that you are using (Pushbots), but I think you are forgeting to check which tag is saved in Pushbots during the activity method onCreate() and enable or disable the buttons according to it. You are saving the tags on Pushbots button you never check which tag is saved on it to enable or disable the button.
I'd recommend you to use SharedPreferences directly instead of use this framework, even I don't know it. SharedPreferences is so simple to use that I don't see any reason to use frameworks.
You can use the SharedPreferences class to save the user selection.This video can help you get started - https://www.youtube.com/watch?v=riyMQiHY3V4 .Just save the user selection of button in a key value pair with sharedpreferences class.On activity restart or relaunch just check for the value in the shared preferences instance and accordingly set the button setClickable(true) or setClickable(false).
EDIT:
clickButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//same code as above without the setClickable() on buttons
//remove the button.setClickable(false); for rest of the buttons
editor.putString("session", "akash").commit();
editor.commit();
startActivity(show); //Start the activity here
}
}):
Repeat this for all the click listeners and change the "akash" to something different (according to need) for each button click listener.Then use the method
private void onStartUp(){
SharedPreferences sharedPreferences = getSharedPreferences("com.mateoj.multiactivitydrawer", Context.MODE_PRIVATE);
String str=sharedPreferences .getString("session","akash");
if(str.equals("akash")){
//set buttons setClickable(true) or setClickable(false)
} else if(str.equals("...")) //replace "..." with other strings which can replace "akash"
//set buttons setClickable(true) or setClickable(false)
} //continue the else if logic till all conditions are met
}
call onStartUp(); in onCreate(); after setting the on click listeners for the buttons .
I have a simple android page with a spinner, two check boxes and a submit button. The java code for the screen is as follows:
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.content.Intent;
import org.json.JSONException;
import org.json.JSONObject;
public class Main extends AppCompatActivity implements View.OnClickListener{
private Button submit;
private Button edit;
Spinner place;
private CheckBox male;
private CheckBox female;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
submit = (Button) findViewById(R.id.btn_submit);
submit.setOnClickListener(this);
edit = (Button) findViewById(R.id.btn_edit);
edit.setVisibility(View.GONE);
place = (Spinner) findViewById(R.id.place);
place.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapter, View v,
int position, long id) {
// On selecting a spinner item
String item = adapter.getItemAtPosition(position).toString();
str_specimen = item;
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
male = (CheckBox) findViewById(R.id.male);
male.setChecked(false);
female = (CheckBox) findViewById(R.id.female);
female.setChecked(false);
submit.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Main.this,
home.class);
startActivity(intent);
}
});
}
}
I have a edit button that is not visible initially. When I choose a value from spinner and check a value in the check box and click on submit button. These values are sent to database and home page will launch.
What I want to do is that, when I visit the main page again, I want the previously selected values to appear and the spinner and checkbox should not be clickable, and the edit button should show up. If i click on the edit button the spinner and checkbox should be clickable and i should be able to submit again.
Can someone tell me how to do this?
Have a method, say isFirstVisit(), that returns a boolean if this is the first time the user is on that activity:
private boolean isFirstVisit() {
SharedPreferences prefs = getApplicationContext().getSharedPreferences("settings", Context.MODE_PRIVATE);
return prefs.getBoolean("IsFirstVisit", true);
}
Call it before you start adjusting your UI and then based on its value show/hide/check/uncheck/enable/disable various UI elements:
boolean firstTime = isFirstVisit();
edit = (Button) findViewById(R.id.btn_edit);
if(firstTime) {
edit.setVisibility(View.GONE);
}
Don't forget to set IsFirstVisit to false when done:
SharedPreferences prefs = getApplicationContext().getSharedPreferences("settings", Context.MODE_PRIVATE);
SharedPreferences.Editor ed = prefs.edit();
ed.putBoolean("IsFirstVisit", false);
ed.commit();
Use SharedPreferences after click
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("place", place.getSelectedItem().toString(););
editor.putInt("male", male.getText());
editor.putInt("female", female.getText());
editor.commit();
Retrieve data from preference after setContentView(R.layout.main);
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
String place = prefs.getString("place" null);
String male = prefs.getString("male", null);
String female = prefs.getString("female", null);
}
I am new in Android programing. I want to make an application. The button text increase whenever the user click on it. My counter is reseted when the application is closed. How can I store the last counter value and call it again when the application is reopened?
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
private int c;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button = (Button) findViewById(R.id.buttonClick);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
c++;
button.setText(Integer.toString(c));
}
});
}
}
EDIT:
I try to use this Shared Preferences but I got eror about "setSilent" and "mSilentMode". Help please
My new code
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
private int c;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);
setSilent(silent);
final Button button = (Button) findViewById(R.id.buttonClick);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
c++;
button.setText(Integer.toString(c));
}
});
}
#Override
protected void onStop(){
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);
// Commit the edits!
editor.commit();
}
}
It depends, are you asking how to preserve a variable across an app's lifespan or between different lifespans?
If it's across different lifespans, you can write it to disk and then read it onCreate.
If you need to do it across one lifespan, it depends on your use case, but generally putting it in a global, static variable would do the trick!
If this is unclear and you'd like some sample code, please, don't be afraid to ask! : )
You can save your c value in the Preference when your activity is going to be closed, and when you rise up your activity you set your c variabile to the previous value
Use this snippet out of your onClickListener: To get the int if there is any
SharedPreferences hhii = getSharedPreferences("c_value", MODE_PRIVATE);
int ca = hhii.getInt("c_value2", 0);
button.setText(ca+"");
Use this in your onClickListener: To save the int as the user clicks the button-much better than saving it in onBackPressed or OnDestroy or whatever
c++;
button.setText(Integer.toString(c));
SharedPreferences hhii = getSharedPreferences("c_value", MODE_PRIVATE);
hhii.edit().putInt("c_value2",c).commit();
Regards from Iran,
Gabriel
I'm developing a simple game in Android and even i followed the steps found in the net, the highscore of my app is never saved. I'm using SharedPreferences to store, but I'm quietly sure the problem is in there, because I don't understand at all how to use it.Hope you guys can help me, thanks.
package com.example.memory;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Final extends Activity implements OnClickListener{
TextView levelReachedText;
TextView bestScoreText;
int levelReached, bestScore;
Intent intent;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.finals);
levelReachedText = (TextView) this.findViewById(R.id.nivel);
bestScoreText = (TextView) this.findViewById(R.id.best);
Button menu = (Button) findViewById(R.id.inicio);
menu.setOnClickListener(this);
intent = getIntent();
levelReached = intent.getIntExtra("nivel", 1);
SharedPreferences preferences = this.getSharedPreferences("bestScore", MODE_PRIVATE);
int savedScore = preferences.getInt("selectedScore", 0);
levelReachedText.setText("You reached level "+levelReached );
if(savedScore>levelReached){
bestScore = savedScore;
}else{
bestScore = levelReached;
}
bestScoreText.setText("Maximum level reached "+levelReached);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.inicio:
SharedPreferences preferences = this.getSharedPreferences("mejorScore", MODE_PRIVATE);
preferences.edit().putInt("selectedScore", bestScore).commit();
this.finish();
break;
}
}
}
you are saving score value in mejorScore and trying to get it from bestScore.So either change
SharedPreferences preferences = this.getSharedPreferences("mejorScore", MODE_PRIVATE);
to
SharedPreferences preferences = this.getSharedPreferences("bestScore", MODE_PRIVATE);
or vice-versa.