I'm trying to access shared preference value created in one application from other applications I'm able to retrieve the data only if I close the app from the task manager else the changes are not reflecting.
First Activty:
btnSignIn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// get The User name and Password
String userName = editTextUserName.getText().toString();
String password = editTextPassword.getText().toString();
sharedPreferences = getSharedPreferences(PREFS_READ_WRITE, Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);
Editor prefsPrivateEditor = sharedPreferences.edit();
prefsPrivateEditor.putString(KEY_READ_WRITE, "test");
prefsPrivateEditor.commit();
To clear:
clear.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
sharedPreferences = getSharedPreferences(PREFS_READ_WRITE, Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);
Editor prefsPrivateEditor = sharedPreferences.edit();
prefsPrivateEditor.clear();
prefsPrivateEditor.commit();
}
});
In other App I'm retrieving like this:
Context otherAppsContext = null;
try {
otherAppsContext = createPackageContext("com.example.app", 0);
} catch (NameNotFoundException e) {
}
sharedPreferences = otherAppsContext.getSharedPreferences(PREFS_READ_WRITE, Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);
String authToken=sharedPreferences.getString(KEY_READ_WRITE, "WORLD READ WRITE EMPTY");
Toast.makeText(getApplicationContext(), authToken, Toast.LENGTH_SHORT).show();
Here is a bit different code, but looks like a working one
https://stackoverflow.com/a/6030399/995020
Related
I have mentioned my complete code for the login and logout process to my application. Sometimes this code works but sometimes it just allows me to go to menu activity even without login. FYI: this code really worked earlier once i wanted to implement the remember me option, then only all these issues came up. can anyone check this and find me my issue or suggest me if u got any proper code for this process. when i logout and and open the application sometimes i can see the menu.
I have used shared preference and not using sessions for login and logout. is it correct. Im bit confused i would really appreciate any help. thanx in advance.
login code
public class LoginActivity extends Activity {
ProgressDialog prgDialog;
EditText emailET;
EditText pwdET;
String email;
String password;
Button button;
public static String PREFS_NAME = "mypre";
public static String PREF_EMAIL = "email";
public static String PREF_PASSWORD = "password";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_login);
final Button button = (Button) findViewById(R.id.btlogin);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
String email = emailET.getText().toString();
String password = pwdET.getText().toString();
if (Utility.isNotNull(email) && Utility.isNotNull(password)) {
if (Utility.validate(email)) {
if (emailET.getText().toString().equals(email)
&& pwdET.getText().toString()
.equals(password)) {
CheckBox ch = (CheckBox) findViewById(R.id.ch_rememberme);
if (ch.isChecked())
rememberMe(email, password);
}
new LoginAsyncTask(LoginActivity.this).execute(
email, password);
Toast.makeText(getApplicationContext(),
"Login process started...",
Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getApplicationContext(),
"Login error, invalid email",
Toast.LENGTH_LONG).show();
}
}
else {
Toast.makeText(
getApplicationContext(),
"Login error, don't leave any field blank",
Toast.LENGTH_LONG).show();
}
} catch (Exception ex) {
}
}
});
final TextView textView = (TextView) findViewById(R.id.link_to_landing);
textView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(),
LandingActivity.class);
startActivity(i);
finish();
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
}
});
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
Intent i = new Intent(getApplicationContext(),
LandingActivity.class);
startActivity(i);
overridePendingTransition(R.anim.slide_in_left,
R.anim.slide_out_right);
finish();
return false;
}
return super.onKeyDown(keyCode, event);
}
public void onStart() {
super.onStart();
// read email and password from SharedPreferences
getUser();
}
public void getUser() {
SharedPreferences pref = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
String email = pref.getString(PREF_EMAIL, null);
String password = pref.getString(PREF_PASSWORD, null);
if (email != null || password != null) {
// directly show logout form
showLogout(email);
}
}
public void rememberMe(String user, String password) {
// save email and password in SharedPreferences
getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit()
.putString(PREF_EMAIL, user).putString(PREF_PASSWORD, password)
.commit();
}
public void showLogout(String email) {
// display log out activity
Intent intent = new Intent(this, ActivityMenu.class);
intent.putExtra("user", email);
startActivity(intent);
overridePendingTransition(R.anim.slide_in_left,
R.anim.slide_out_right);
}
}
logout code
final RelativeLayout relativeLayout3 = (RelativeLayout) rootView
.findViewById(R.id.logoutlistview);
relativeLayout3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
SharedPreferences pref = getActivity().getSharedPreferences(
PREFS_NAME, Context.MODE_PRIVATE);
String email = pref.getString(PREF_EMAIL, null);
String password = pref.getString(PREF_PASSWORD, null);
if (email != null || password != null ) {
Editor editor = pref.edit();
editor.clear();
editor.commit();
email = "";
password = "";
firstname = "";
lastname = "";
// show login form
Intent intent = new Intent(getActivity(),
LActivity.class);
startActivity(intent);
intent.addFlags(IntentCompat.FLAG_ACTIVITY_CLEAR_TASK
| Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
else {
}
}
});
use this method to create a sharedPreference and then access it with this same name from any where in any activity within the same app
SharedPreference sp;
sp = getApplicationContext().getSharedPreferences(My_PREFERENCE,
context.MODE_PRIVATE);
Editor e = sp.edit();
e.put(key,value);
e.commit();
and when getting the same sharedPreference in another activity use this method
SharedPreference sp;
sp = getApplicationContext().getSharedPreferences(My_PREFERENCE,
context.MODE_PRIVATE);
sp.get(key,value);
Please check the below link which might help you.
http://androidapplicationdeveloper.weebly.com/login-and-logout-useing-sharedprefrences.html
In your code you have didn't set values of sharedpreference to blank while logout.
Hope it will help you.
I am working on appLocker in which I have to set the password on installed application of device.
for that I have created a list in which I am getting all the installed application. User can select the the application by using checkBox and set the password on that. for that I have to get the package name of that application. I am able to get the package name of selected application and save them using Share Preferences. now I have to get that package name in an another activity. please tell me how can I get that.
this is the code where I am getting the package name.
public void onClick(View v) {
if (R.id.select_done_btn == v.getId()) {
SharedPreferences prefs = getSharedPreferences(getPackageName(), MODE_PRIVATE);
int[] indexes = appListAdapter.getSelectedItemIndexes();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < indexes.length; ++i) {
AppInfo appInfo = installedApps.get(indexes[i]);
sb.append(appInfo.getPackageName()).append(";");
}
Editor editor = prefs.edit();
editor.putString("lock_apps", sb.toString());
editor.commit();
and this the code section where I have to get that package name to lock the selected application in another activity..
public void run() {
while (true) {
Log.i("lock", "lockerThread run.");
String packname = activityManager.getRunningTasks(1).get(0).topActivity.getPackageName();
if ("**PACKAGE NAME**".equals(packname)) {
startActivity(pwdIntent);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
In the above question
SharedPreferences prefs = getSharedPreferences(getPackageName() , MODE_PRIVATE);
prefs.getstring("key");
will give your saved string from SharedPreferences where ever you want in Application.
If you like you can go through other solution given as below for optimization
public void addTask(Task t) {
if (null == currentTasks) {
currentTasks = new ArrayList<task>();
}
currentTasks.add(t);
//save the task list to preference
SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);
Editor editor = prefs.edit();
try {
editor.putString(TASKS, ObjectSerializer.serialize(currentTasks));
} catch (IOException e) {
e.printStackTrace();
}
editor.commit();
}
Similarly we can retrieve the list of tasks from the preference inside onCreate() method:
public void onCreate() {
super.onCreate();
if (null == currentTasks) {
currentTasks = new ArrayList<task>();
}
// load tasks from preference
SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);
try {
currentTasks = (ArrayList<task>) ObjectSerializer.deserialize(prefs.getString(TASKS, ObjectSerializer.serialize(new ArrayList<task>())));
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
I've been getting null returns from getting strings from my saved preferences. I'm not sure how savedpreferences worked but my understanding was that when call a sharedpreferences, it creates the keypair file on the phone so you can come back to it later.
My program is essentially a string creation application. When you press a button, it creates a string to send as an sms. My settings activity page has four edittexts that save whatever is inside them with a buttonclick and returns to the main activity. The final button creates a String by getting the value from the keyvalue pair and constructs the message. However, I've always gotten null for each of the values.
Heres the code for the settings page and then the main page. Please ask if I could add more, I didn't add ALL of the code, just the sharedpreferences portions.
public SharedPreferences sp;
public Editor e;
public void savethethings(){ //run this when enter is pressed/savew
EditText smsintro_hint = (EditText) findViewById(R.id.settings_smsintro_hint);
EditText smsbody_hint = (EditText) findViewById(R.id.settings_smsbody_hint);
EditText checkboxbody_hint = (EditText) findViewById(R.id.settings_checkboxbody_hint);
EditText checkboxbody_description_hint = (EditText) findViewById(R.id.settings_checkboxbody_description_hint);
String introstring = smsintro_hint.getText().toString();
String bodystring = smsbody_hint.getText().toString();
String checkboxbodystring = checkboxbody_hint.getText().toString();
String checkboxdescriptionstring = checkboxbody_description_hint.getText().toString();
e.putString("intro", introstring);
e.commit(); // you forgot to commit
if(!bodystring.isEmpty())
{
e.putString("body", bodystring);
e.commit();
}
if(!checkboxbodystring.isEmpty())
{
e.putString("checkbody", checkboxbodystring);
e.commit();
}
if(!checkboxdescriptionstring.isEmpty())
{
e.putString("checkboxdescr", checkboxdescriptionstring);
e.commit();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.settingmenu);
//SP
sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); // forget about
// named preferences - get the default ones and finish with it
e = sp.edit();
Button tt = (Button)findViewById(R.id.savebutton);
tt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
public void save(View view)
{
//THINGS HAPPEN HERE WITH SHARED PREFERENCES :(
savethethings();
this.finish();
return;
}
public String finishedtext(String userstring)
{
smsintroduction = (sp.getString("intro", ""));
smsbody = (sp.getString("body", ""));
checkboxtext = (sp.getString("checkbody", ""));
checkboxmessage = (sp.getString("checkboxdescr", ""));
if(smsintroduction.isEmpty())
{
if(smsbody.isEmpty())
{
if(checkboxtext.isEmpty())
{
if(checkboxmessage.isEmpty()) //topkek for most AND statements Ive ever put in in if/then form
{
//Essentially the DEFAULT if they're ALL null
smsbody = "Hi "+ userstring +"! This is coming from jake's phone and it wants to send a text so we can talk or whatever. ";
}
}
}
}
Toast.makeText( this, "Creating text, then press send!", Toast.LENGTH_LONG).show();
String thetext = "";
thetext = smsintroduction + " " + smsbody + " " + checkboxtext;
return thetext;
}
public void savethethings(){ //run this when enter is pressed/savew
EditText smsintro_hint = (EditText) findViewById(R.id.settings_smsintro_hint);
EditText smsbody_hint = (EditText) findViewById(R.id.settings_smsbody_hint);
EditText checkboxbody_hint = (EditText) findViewById(R.id.settings_checkboxbody_hint);
EditText checkboxbody_description_hint = (EditText) findViewById(R.id.settings_checkboxbody_description_hint);
String introstring = smsintro_hint.getText().toString();
String bodystring = smsbody_hint.getText().toString();
String checkboxbodystring = checkboxbody_hint.getText().toString();
String checkboxdescriptionstring = checkboxbody_description_hint.getText().toString();
// if(!introstring.isEmpty()) //if the fields are NOT empty, they should get saved.
// {
e.putString("intro", introstring);
e.commit(); // you forgot to commit
if(!bodystring.isEmpty())
{
e.putString("body", bodystring);
e.commit();
}
if(!checkboxbodystring.isEmpty())
{
e.putString("checkbody", checkboxbodystring);
e.commit();
}
if(!checkboxdescriptionstring.isEmpty())
{
e.putString("checkboxdescr", checkboxdescriptionstring);
e.commit();
}
}
Create java class named SessionManger and put all your methods for setting and getting SharedPreferences values. When you want to save value use the object of this class and set and get the values.
Sample code given below.
public class SessionManager {
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;
int PRIVATE_MODE = 0;
public SessionManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences("name_that_you_use", PRIVATE_MODE);
editor = pref.edit();
editor.apply();
}
public void setIntroMessage(String data) {
editor.putString("intro", data);
editor.commit();
}
public String getIntroMessage() {
return pref.getString("intro", null);
}
}
I have try to set and store the password for my apps, but it is not working at all. The password should be setted first time then return the home page, then when the user open it again the password should be stored but somehow it didn't store it.
PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences passfile = getSharedPreferences("ans",0);
String pass = passfile.getString("ans", null);
check.setOnClickListener(new OnClickListener () {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String answer1 = answer.getText().toString();
//Check that user typed in an answer
if(answer1.length()<8){
Toast.makeText(CheckPwActivity.this, "Answer must be 8 characters long", Toast.LENGTH_SHORT).show();
answer.setText("");
answer.requestFocus();
return;
}
answer.getEditableText().toString();
//check if the answer is valid
if (answer1.equals("ans")) {
Intent intent2 = new Intent(CheckPwActivity.this,MainActivity.class);
startActivity(intent2);
}else{
return;
}
}});
}
public void setPassword(String key, String value) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
Editor preferenceEditor = context.getSharedPreferences("password", 8).edit();
preferenceEditor.putString(key, value);
preferenceEditor.commit();
}
public static String getPassword(String filename) {
return context.getSharedPreferences("password", 2).getString(filename,"");
}
you are using shared preferences wrong, in your set password you get shared preferences but then you get it again but in a different context
this is all you need to use shared preferences
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
then when you want to set it you use the editor you just got
editor.putString(key,pass).commit;
then to get it from shared preferences you would just do
preferences.getString(key,defaultString);
I'm trying to use sharedpreferences to check whether the user logged in before they start using the app. I save the username in shredpreferences when user log in.
Login.java
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
Button btnLogin = (Button) findViewById(R.id.buttonlogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View adapt) {
EditText usernameEditText = (EditText) findViewById(R.id.EditUserName);
userName = usernameEditText.getText().toString();
EditText passwordEditText = (EditText) findViewById(R.id.EditPassword);
userPassword = passwordEditText.getText().toString();
if (userName.matches("") && userPassword.matches("")) {
toast("Please enter Username and Password");
return;
} else if (userName.matches("") || userName.equals("")) {
toast("Please enter Username");
return;
} else if (userPassword.matches("") || userPassword.equals("")) {
toast("Please enter Password");
return;
} else {
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("MEM1", userName);
editor.commit();
new DownloadFilesTask().execute();
}
}
});
}
private void toast(String text) {
Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
}
private class DownloadFilesTask extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
}
protected void onPostExecute(Void result) {
toast("user logged in");
startActivity(new Intent(Login.this, MainActivity.class));
finish();
}
#Override
protected Void doInBackground(Void... params) {
return null;
}
}
}
and I tried to check the username value before I start my mainactivity.
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String username =sharedPreferences.getString("MEM1", "");
if(username.equalsIgnoreCase("")||username.length()==0)
{
toast("username is null");
startActivity(new Intent(MainActivity.this, Login.class));
finish();
}
but the username is always null. Please help. Thanks
Calling getPreferences means that you have to be in the same activity. Using getSharedPreferences allows you to share the preferences between activities. You just have to define a name for the preferences when calling getSharedPreferences("Pref name here", MODE_PRIVATE);
Write below Code instead of your code to save username into sharedpreferences.
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.Editor editor = myPrefs.edit();
editor.putString("MEM1", userName);
editor.commit();
And Use below code For Get Preferences Value.
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
String username = myPrefs.getString("MEM1","");
private final String TAXI_SPREF = "TAXI_SHARED_PREFERENCES";
//set-save data to shared preferences
SharedPreferences.Editor sPEditor = getSharedPreferences(TAXI_SPREF, MODE_PRIVATE).edit();
sPEditor.putInt("USERID", etUserID.getText().toString());
sPEditor.putString("EMAIL", etEmail.getText().toString());
sPEditor.apply();
//get data from shared preferences
SharedPreferences sharedPreferences = getSharedPreferences(TAXI_SPREF, MODE_PRIVATE);
int userID = sharedPreferences.getInt("USERID", 0);
string email = sharedPreferences.getString("EMAIL", 0);
//////// or /////
String email = getSharedPreferences(TAXI_SPREF, MODE_PRIVATE).getString("EMAIL","EMPTY");
if (!email.equals("EMPTY")){
etEmail.setText(email);
}