btnRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String name = inputFullName.getText().toString();
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
if (!name.isEmpty() && !email.isEmpty() && !password.isEmpty()) {
registerUser(name, email, password);
} else {
Toast.makeText(getApplicationContext(),
"Please enter your details!", Toast.LENGTH_LONG)
.show();
}
return name; //<-here is the error
}
i want to import "name" to another class.. How Can i do this?
I guess you want to send the value to another activity, right? Then you should use intents.
In your activity:
Intent intent = new Intent();
intent.putExtra("name", name);
startActivity(intent);
In the activity where you want to get the value:
Bundle extras = getIntent().getExtras();
if (extras != null) {
String data = extras.getString("name");
Easiest way to do it is via intents.
You can set up an intent for the class you want to launch. Then you can put the name as extra and start the activity class.
Intent intent = new Intent(this,YourActivityClass.class);
intent.putExtra("Name","value");
startActivity(intent);
You can also use preference to store and retrieve datas wherever you need.
For eg: this is in Utils class.
private Editor mEditor;
private SharedPreferences mPreferences;
private static final String PREFERENCE_NAME = "pref";
public Utils(Context context) {
mPreferences = context.getSharedPreferences(PREFERENCE_NAME,
Context.MODE_PRIVATE);
mEditor = mPreferences.edit();
}
/**
* Store string in preference.
*
* #param key
* the key
* #param value
* the value
*/
public static void storeStringInPreference(String key, String value) {
mEditor.putString(key, value);
mEditor.commit();
}
/**
* Gets the string from preference.
*
* #param key
* the key
* #return the string from preference
*/
public static String getStringFromPreference(String key) {
return mPreferences.getString(key, null);
}
In Activity A:
String password = inputPassword.getText().toString();
Utils.storeInPreference("password",password); //key,value
In Activity B:
String password = Utils.getStringFromPreference("password"); //key
Related
First of, allow me to point out that am new to android development and at this very moment am trying to store a user login session using SharedPreferences and having done a bit to create myself a class SessionManager to handle that, i got no error anyways but, each time i logged in, am quickly redirected to the LoginActivty again.
SessionManager.java
package com.example.drawerlayout;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import java.util.HashMap;
public class SessionManager {
SharedPreferences sharedPreferences;
public SharedPreferences.Editor editor;
public Context context;
int PRIVATE_MODE = 0;
private static final String PREF_NAME = "LOGIN";
private static final String LOGIN = "IS_LOGIN";
public static final String NAME = "NAME";
public static final String EMAIL = "EMAIL";
public static final String TYPE = "TYPE";
public SessionManager(Context context) {
this.context = context;
sharedPreferences = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = sharedPreferences.edit();
}
public void createSession(String name, String email, String type){
editor.putBoolean(PREF_NAME, true);
editor.putString(NAME, name);
editor.putString(EMAIL, email);
editor.putString(TYPE, type);
editor.apply();
}
public boolean isLoggedIn(){
return sharedPreferences.getBoolean(LOGIN, false);
}
public void checkLoggin(){
if (!this.isLoggedIn()){
Intent i = new Intent(context, LoginActivity.class);
context.startActivity(i);
((MainActivity) context).finish();
}
}
public HashMap<String, String> getUserDetails(){
HashMap<String, String> user = new HashMap<>();
user.put(NAME, sharedPreferences.getString(NAME, null));
user.put(EMAIL, sharedPreferences.getString(EMAIL, null));
user.put(TYPE, sharedPreferences.getString(TYPE, null));
return user;
}
public void logOut(){
editor.clear();
editor.commit();
Intent i = new Intent(context, LoginActivity.class);
context.startActivity(i);
((MainActivity) context).finish();
}
}
and SessionManager.java is used in LoginActivity like so:
String name = details.getString("username").trim();
String email = details.getString("email").trim();
String type = details.getString("type").trim();
//CREATE SESSION
sessionManager.createSession(name,email,type);
and in MainActivity.java like
sessionManager = new SessionManager(this);
sessionManager.checkLoggin();
You are updating wrong key in createSession method.
Replace PREF_NAME with LOGIN in createSession. And your code will work as expected.
public void createSession(String name, String email, String type){
// Check below line...
editor.putBoolean(LOGIN, true);
editor.putString(NAME, name);
editor.putString(EMAIL, email);
editor.putString(TYPE, type);
editor.apply();
}
See your String variable names once again!
String PREF_NAME is for getting the preference.
String LOGIN is for addressing the value to check if the user is logged in or not
Your Mistake:
Function createSession(String name, String email, String type)
You are updating the value of String PREF_NAME instead of String LOGIN
Solution:
Function createSession(String name, String email, String type)
Updating the value of String LOGIN instead of String PREF_NAMEin line no 29 of SessionManager.java
Most probably you have forgotten to put a boolean field LOGIN in your session manager's create session.. modify createSession Method as below
public void createSession(String name, String email, String type,Boolean isLoggedIn){
editor.putString(NAME, name);
editor.putString(EMAIL, email);
editor.putString(TYPE, type);
editor.putBoolean(LOGIN,isLoggedIn)
editor.apply();
}
And then if login success in login activity then call like this
String name = details.getString("username").trim();
String email = details.getString("email").trim();
String type = details.getString("type").trim();
//CREATE SESSION
sessionManager.createSession(name,email,type,true);
alright sharedpreference values are saving in xml file which contain its key and value so each of value will be generate on first attempt of login so why don't you check if any value is exists in sharedpreference or not by this way.. put this code to your sessionHandler
public static boolean preferenceExists(String key){
return sharedPreferences.contains(key);
}
it will return boolean flag if any value is exists there or not so simply do check if preferenceExists() or not.... if not then redirect it do login activity else redirect where you want
suggestion : create splashscreen where you can verify these things
I keep getting the following error when running my Espresso tests:
Attempt to invoke virtual method 'android.content.Context android.app.Instrumentation.getTargetContext()' on a null object reference
#RunWith(AndroidJUnit4.class)
public class TestLogin extends AndroidTestCase {
#Rule
public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule<>(MainActivity.class);
#Test
public void testVerifyCredentials() {
Context context = this.getContext().getApplicationContext();
SharedPreferences prefs = context.getSharedPreferences("current.user", Context.MODE_PRIVATE);
assertTrue(prefs.getBoolean("IsLoggedIn", false));
}
}
I already tried this as an InstrumentationTestCase, and then tried instead to do Context context = this.getInstrumentation().getTargetContext().getApplicationContext(); but that still lead to the NPE.
What am I doing wrong?
The SessionManager class I'm using in my application to manage SharedPrefs:
package com.nullpointexecutioners.buzzfilms.helpers;
import android.content.Context;
import android.content.SharedPreferences;
import com.firebase.client.Firebase;
import com.nullpointexecutioners.buzzfilms.Major;
/**
* Helper class for managing a session (i.e. persistence across launches of the app
*/
public class SessionManager {
private static SessionManager sInstance;
private final SharedPreferences pref;
private final SharedPreferences.Editor editor;
//SharedPref file name
private static final String PREF_NAME = "current.user";
//All Shared Preferences Keys
private static final String IS_LOGIN = "IsLoggedIn";
//Username
public static final String KEY_USERNAME = "username";
//Name
public static final String KEY_NAME = "name";
//Email
public static final String KEY_EMAIL = "email";
//Major
public static final String KEY_MAJOR = "major";
//is an Admin
public static final String IS_ADMIN = "isAdmin";
final Firebase mRef = new Firebase("redacted");
/**
* Constructor for instance of SessionManager
* #param context of session
* #return instance of SessionManager
*/
public static SessionManager getInstance(Context context) {
if (sInstance == null) {
sInstance = new SessionManager(context);
}
return sInstance;
}
/**
* Constructor for SessionManager class
* #param context of session
*/
private SessionManager(Context context) {
pref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
editor = pref.edit();
}
/**
* Create login session
* #param username to store in SharedPrefs
* #param name name of a user
* #param email to store in SharedPrefs
* #param major major of a user
* #param isAdmin determines if a user is admin or not
*/
public void createLoginSession(String username, String name, String email, String major, boolean isAdmin) {
/*Store each value into SharedPrefs*/
editor.putBoolean(IS_LOGIN, true);
editor.putString(KEY_USERNAME, username);
editor.putString(KEY_NAME, name);
editor.putString(KEY_EMAIL, email);
if (major.equals(Major.NONE.toString())) {
editor.putString(KEY_MAJOR, "NONE");
} else {
editor.putString(KEY_MAJOR, major);
}
editor.putBoolean(IS_ADMIN, isAdmin);
//Commit changes to SharedPrefs
editor.apply();
}
/**
* Update the current Session's values
* #param name to update
* #param email to update
* #param major to update
*/
public void updateSession(String name, String email, String major) {
/*Store the updated values into SharedPrefs*/
editor.putString(KEY_NAME, name);
editor.putString(KEY_EMAIL, email);
if (major.equals(Major.NONE.toString())) {
editor.putString(KEY_MAJOR, "NONE");
} else {
editor.putString(KEY_MAJOR, major);
}
//Commit changes to SharedPrefs
editor.apply();
}
/**
* Checks if current user is logged in
* If false, the user is redirected to WelcomeActivity to login or register
* #return true or false depending if we're logged in
*/
public boolean checkLogin() {
return pref.getBoolean(IS_LOGIN, false);
}
/**
* Checks if current user is an Admin
* If false, the user won't have access to Admin functions
* #return true or false depending if the user is an Admin
*/
public boolean checkAdmin() {
return pref.getBoolean(IS_ADMIN, false);
}
/**
* Getter for currently logged in user's username
* #return current user's username
*/
public String getLoggedInUsername() {
String username = null;
if (pref.contains(KEY_USERNAME) && pref.getBoolean(IS_LOGIN, false)) {
username = pref.getString(KEY_USERNAME, null);
}
return username;
}
/**
* Getter for currently logged in user's name
* #return current user's name
*/
public String getLoggedInName() {
String name = null;
if (pref.contains(KEY_NAME) && pref.getBoolean(IS_LOGIN, false)) {
name = pref.getString(KEY_NAME, "name");
}
return name;
}
/**
* Getter for currently logged in user's email
* #return current user's email
*/
public String getLoggedInEmail() {
String email = null;
if (pref.contains(KEY_EMAIL) && pref.getBoolean(IS_LOGIN, false)) {
email = pref.getString(KEY_EMAIL, null);
}
return email;
}
/**
* Getter for currently logged in user's major
* #return current user's major
*/
public String getLoggedInMajor() {
String major = null;
if (pref.contains(KEY_MAJOR) && pref.getBoolean(IS_LOGIN, false)) {
major = pref.getString(KEY_MAJOR, null);
}
return major;
}
/**
* Clears session credentials
*/
public void logoutUser() {
//UnAuth from Firebase
mRef.unauth();
//Clear SharedPrefs and set IS_LOGIN to false
editor.clear();
editor.putBoolean(IS_LOGIN, false);
editor.commit();
}
/**
* Getter for accessing the current SharedPrefs
* #return this session's SharedPrefs
*/
public SharedPreferences getPref() {
return pref;
}
}
Did you try this?
InstrumentationRegistry.getInstrumentation().getTargetContext()
If you just want to use getSharedPreferences,
try
Activity activity = mActivityRule.getActivity();
SharedPreferences prefs = activity.getSharedPreferences("current.user", Context.MODE_PRIVATE);
assertTrue(prefs.getBoolean("IsLoggedIn", false));
You can use the following code:
ApplicationProvider.getApplicationContext()
your test's this.getContext() gets the context of your TestLogin class. Use
YourActivity.getApplicationContext();
additionally, i recommend to use sharedpreferences in an application context in your application as well, e.g.:
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
and for your test:
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(yourActivity.getApplicationContext());
so your shared Preferences are the same within all activities inside your application.
I have one activity in which I store all the details regarding registration of user and what I want is to make a class Singleton and save mobile and password of user and in activity I use those stored data instead of creating every time a new object. How can I do that?
Here is my RegistrationModel where I store user data:
public class CRegistrationSessionManagement {
;
// User name (make variable public to access from outside)
public static final String s_szKEY_MOBILENUMBER = "mobileNumebr";
public static final String s_szKEY_PASSWORD = "pin";
public static final String s_szKEY_EMAILID = "emailId";
// Sharedpref file name
public static final String s_szREGIS_FILE_NAME = "RegistrationData";
// All Shared Preferences Keys
private static final String s_szIS_REGISTERED = "IsRegistered";
public static String mobile;
public SharedPreferences m_Regis_Pref;
// Editor for Shared preferences
public SharedPreferences.Editor m_editor;
// Context
public Context m_Context;
public CRegistrationSessionManagement(Context m_Context) {
this.m_Context = m_Context;
m_Regis_Pref = m_Context.getSharedPreferences(s_szREGIS_FILE_NAME, Context.MODE_PRIVATE);
m_editor = m_Regis_Pref.edit();
}
// Registration Session Management.
public void setRegisteredData(String mobile, String pin, String emailId) {
m_editor.putBoolean(s_szIS_REGISTERED, true);
m_editor.putString(s_szKEY_MOBILENUMBER, mobile);
m_editor.putString(s_szKEY_PASSWORD, pin);
m_editor.putString(s_szKEY_EMAILID, emailId);
m_editor.commit();
}
/**
* checkRegistrtaion() session wil check user Registrtaion status
* If false it will redirect user to Registrtaion page
* Else won't do anything
*/
public boolean checkRegistration() {
if (!isRegistered()) {
Intent i = new Intent(m_Context, CMainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
m_Context.startActivity(i);
return true;
}
return false;
}
/**
* Get stored Registration session data
*/
public HashMap<String, String> getRegistrationDetails() {
HashMap<String, String> user = new HashMap<>();
// user name
user.put(s_szKEY_MOBILENUMBER, m_Regis_Pref.getString(s_szKEY_MOBILENUMBER, null));
// user email id
user.put(s_szKEY_PASSWORD, m_Regis_Pref.getString(s_szKEY_PASSWORD, null));
user.put(s_szKEY_EMAILID, m_Regis_Pref.getString(s_szKEY_EMAILID, null));
// return user
return user;
}
public boolean isRegistered() {
return m_Regis_Pref.getBoolean(s_szIS_REGISTERED, false);
}
}
How can I fetch mobile and password in activity where I want to ...by only creating instance of this class...instead of creating every time a new object of that class.
You can use static method. Instead of public HashMap<String, String> getRegistrationDetails () you can use public static HashMap<String, String> getRegistrationDetails (). So when you want to use your getter. CRegistrationSessionManagement. getRegistrationDetails () . Take a look to this example to know more about static method and their uses. Java: when to use static methods
I'm trying to display a "rate us" dialog box the 5th time the user logs in to the app. On registering, the sharedpreference LOG_COUNT is set to 0 and the value of another shared prefernce LOG_BOOLEAN is set to true.
When the user logs in the first time, I check if the value of LOG_BOOLEAN is true. If it is, then the LOG_BOOLEAN is set to false. Every time the user logs in the value of the sharedpreference LOG_COUNT is increased. If it is 5, then I display the dialog box asking to rate and set it back to 0 if the user doesn't rate the app.
But every time the user logs in, the LOG_BOOLEAN is true and LOG_COUNTis 0 though I set it to false and increment it on the first login.
I use a class SessionManager to store and change sharedpreferences.
This is SessionManager.java:
package com.prematixsofs.taxiapp;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import java.util.HashMap;
/**
* Created by admin on 05-01-2016.
*/
public class SessionManager {
SharedPreferences pref;
String userName;
Editor editor;
Context _context;
int PRIVATE_MODE = 0;
int loginCount;
private static final String PREF_NAME = "TaxiPref";
private static String LOGIN_BOOLEAN = "loginBoolean";
private static String IS_LOGIN = "IsLoggedIn";
private static String LOG_COUNT = "loginCount";
// Email address (make variable public to access from outside)
public static final String KEY_EMAIL = "email";
public static final String KEY_NAME = "name";
// Constructor
public SessionManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void createLoginSession(String name, String email) {
// Storing login value as TRUE
// Storing email in pref
editor.putString(KEY_NAME, name);
editor.putString(KEY_EMAIL, email);
editor.putBoolean(IS_LOGIN, true);
// commit changes
editor.commit();
}
public void setLoginCount(int count) {
if (count == 0) {
editor.putInt(LOG_COUNT, count);
editor.commit();
} else {
loginCount = pref.getInt(LOG_COUNT, 10);
editor.putInt(LOG_COUNT, loginCount + 1);
editor.commit();
}
}
public int getLoginCount() {
return pref.getInt(LOG_COUNT, 11);//random default value
}
public void setLoginSessionToTrue() {
editor.putInt(LOG_COUNT, 0);
editor.commit();
editor.putBoolean(LOGIN_BOOLEAN, true);
editor.commit();
}
public boolean getLoginBoolean() {
boolean bool;
bool = pref.getBoolean(LOGIN_BOOLEAN, true);
return bool;
}
public void setLoginBooleanToFalse() {
editor.putBoolean(LOGIN_BOOLEAN, false);
editor.putInt(LOG_COUNT, 0);
editor.commit();
boolean set = pref.getBoolean(LOGIN_BOOLEAN, false);
int cou = pref.getInt(LOG_COUNT, 100);
}
/**
* Check login method wil check user login status
* If false it will redirect user to login page
* Else won't do anything
*/
public void checkLogin() {
// Check login status
if (!this.isLoggedIn()) {
// user is not logged in redirect him to Login Activity
Intent i = new Intent(_context, LoginActivity.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
}
/**
* Get stored session data
*/
public String getUserName() {
HashMap<String, String> user = new HashMap<String, String>();
// user email id
return pref.getString(KEY_NAME, null);
}
public String getUserEmail() {
return pref.getString(KEY_EMAIL, null);
}
/**
* Clear session details
*/
public void logoutUser() {
// Clearing all data from Shared Preferences
editor.clear();
editor.commit();
// After logout redirect user to Loing Activity
Intent i = new Intent(_context, MainActivity.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
// Add new Flag to start new Activity
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
/**
* Quick check for login
* *
*/
// Get Login State
public boolean isLoggedIn() {
return pref.getBoolean(IS_LOGIN, false);
}
}
This is login:
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//databaseHelper.delete();
item = databaseHelper.getLogin(uname.getText().toString(), pass.getText().toString());
if (item) {
sessionManager.createLoginSession(databaseHelper.getUserName(uname.getText().toString()), uname.getText().toString());
int c = sessionManager.getLoginCount(); // the value here is 11,the random default value.not the incremented value
countCheck = sessionManager.getLoginBoolean();
if (countCheck) { //check if first time log in
sessionManager.setLoginBooleanToFalse();
uname.setText("");
pass.setText("");
sessionManager.setLoginCount(0);
Intent intent2 = new Intent(getApplicationContext(), DateVehiclePicker.class);
startActivity(intent2);
} else if (sessionManager.getLoginCount() == 5) {
Intent intent1 = new Intent(getApplicationContext(), DateVehiclePicker.class);
sessionManager.setLoginCount(0);
intent1.putExtra("login", true);
startActivity(intent1);
}
} else
uname.setError("Enter a valid Email & Password");
}
});
This is Register.java where I set the sharedpreference to true and assign LOG_COUNTto zero:
signup.setOnClickListener(new View.OnClickListener() {
sessionManager.setLoginSessionToTrue();
});
try like this
private SharedPreferences.Editor getEditor() {
SharedPreferences settings = mContext.getSharedPreferences(GENERAL_PREFERENCE, 0);
return settings.edit();
}
and then
public void setUserId(String userId) {
this.userId = userId;
getEditor().putString(userIdKey, userId).commit();
}
you should create default initialization
private void initSharedPreference() {
SharedPreferences settings = mContext.getSharedPreferences(GENERAL_PREFERENCE, 0);
userId = settings.getString(userIdKey, ""); // to avoid nullpointerexception
}
call this method in you SharedPref constructor
EDIT
Create SharedPref like this:
public class SharedPref {
private Context mContext;
private String userId;
private final static String GENERAL_PREFERENCE = "general_pref";
private String userIdKey = "userIdKey";
public SharedPref(Context context) {
this.mContext = context;
initSharedPreference();
}
private void initSharedPreference() {
SharedPreferences settings = mContext.getSharedPreferences(GENERAL_PREFERENCE, 0);
userId = settings.getString(userIdKey, "");
}
private SharedPreferences.Editor getEditor() {
SharedPreferences settings = mContext.getSharedPreferences(GENERAL_PREFERENCE, 0);
return settings.edit();
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
getEditor().putString(userIdKey, userId).commit();
}
}
when create handler class:
public class DataSourceController {
public SharedPref sharedPref;
private static DataSourceController sInstance;
private DataSourceController(Context context) {
sharedPref = new SharedPref(context);
}
public static synchronized DataSourceController getInstance() {
return sInstance;
}
public static DataSourceController initSingleton(Context context) {
if (sInstance == null) {
sInstance = new DataSourceController(context);
}
return sInstance;
}
public static SharedPref getSharedPreference() {
return getInstance().sharedPref;
}
}
initialize this handler class in your Application class like this:
public class App extends Application {
#Override
public void onCreate() {
super.onCreate();
DataSourceController.initSingleton(this);
}
}
so now you can call DataSourceController.getSharedPreference().getUserId(); and DataSourceController.getSharedPreference().setUserId("id"); from any place of your app.
Yesterday, I built a SettingsActivity for my Android app where the user can enter the URL of a webservice-server. I save this using:
editor = sharedPref.edit();
editor.putString(
getString(R.string.SAVED_URL_MOBILEHELPER), lvsURL_mobilehelper);
editor.commit();
in the SharedPreferences after the "save" button is pressed.
In the onStart() I read the setting to set the saved value into the belonging text-field:
// line 29
String lvsURL_mobilehelper = sharedPref.getString(
getString(R.string.SAVED_URL_MOBILEHELPER), "");
This also worked well yesterday; the last string I entered and successfully read from the settings was "testURL12345".
Today, I was trying to add user-authentication around my application and since that, I get a ClassCastException when I open the SettingsActivity:
Caused by: java.lang.ClassCastException: java.lang.Long cannot be cast to
java.lang.String
at android.app.SharedPreferencesImpl.getString(SharedPreferencesImpl.java:224)
at de.unibonn.sdb.wissappmobile.activities.SettingsActivity.onResume(
SettingsActivity.java:29)
Does anyone have an idea why this all worked fine yesterday and now it doesn't?
Note: I don't want to store the user credentials in an AccountManager or persistent in my preferences, because the app shall be used on a "business tablet" and not a "personal tablet". The user credentials are needed for HTTP-Basic authentication. So my idea is to check in the parent Activity if the user is "logged in" and not inactive for more than 1800 seconds.
SettingsActivity:
/*
* Activity for settings page (webservice URL)
*/
public class SettingsActivity extends AppFragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
}
#Override
protected void onResume() {
super.onResume();
// Fill content
// URL of the Mobile Helper
String lvsURL_mobilehelper = sharedPref.getString(
getString(R.string.SAVED_URL_MOBILEHELPER), "");
EditText dfsURLMobileHelper = (EditText) findViewById(R.id.dfsURLMobileHelper);
dfsURLMobileHelper.setText(lvsURL_mobilehelper);
}
/*
* Action called when pressing the "Save"-Button
*
* Saves the entered Data in a local file.
*/
public void ClickBtnSave(View view) {
EditText dfsURLMobileHelper = (EditText) findViewById(R.id.dfsURLMobileHelper);
TextView txtError = (TextView) findViewById(R.id.txtError);
String lvsURL_mobilehelper = dfsURLMobileHelper.getText().toString();
String Eceptiontext = "";
Boolean success = false;
// Write to file
try {
editor = sharedPref.edit();
editor.putString(getString(R.string.SAVED_URL_MOBILEHELPER), lvsURL_mobilehelper);
editor.commit();
success = true;
} catch (Exception e) {
success = false;
Eceptiontext = e.getLocalizedMessage();
}
if (success) {
txtError.setText(getString(R.string.SAVING_SUCCESS));
} else {
txtError.setText(getString(R.string.SAVING_FAILED) + " : " + Eceptiontext);
}
}
/*
* Action called when pressing the "Back"-Button
*
* Opens the Search-Acitivity
*/
public void ClickBtnBack(View view) {
// Back to SearchActivity
Intent intent = new Intent(this, SearchActivity.class);
startActivity(intent);
}
}
Parent AppFragmentActivity:
/**
* Class to handle global Callbacks (e.g. user credentials)
*/
public class AppFragmentActivity extends FragmentActivity {
protected SharedPreferences sharedPref;
protected SharedPreferences.Editor editor;
protected String WebServiceUsername;
protected String WebServicePassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_appfragmentactivity);
}
#Override
protected void onResume () {
super.onResume();
// Check if user is "logged in".
// Meaning: Are there given user credentials and are they valid of was the user inactive for too long?
// We only do this "onResume" because this callback is the only one, which is called everytime an user
// starts/restarts/resumes an application
checkForUserCredentials();
// Set new "last action" now "now"
setLastAction(new Date().getTime());
}
#Override
protected void onStart () {
// Fill content
super.onStart();
// Set global sharedPreferences
sharedPref = getSharedPreferences(
getString(R.string.FILE_settings_file), Context.MODE_PRIVATE);
}
/*
* Checks if user credentials are valid meaning if they are set and not too old
*/
private void checkForUserCredentials() {
// Get filehandle to PreferencesFile
long TimeLastAction = sharedPref.getLong(
getString(R.string.SETTINGS_USER_LAST_ACTION), 0);
long TimeNow = new Date().getTime();
// Ask for User credentials when last action is too long ago
if(TimeLastAction < (TimeNow - 1800)) {
// Inactive for too long
// Set credentials back
setUsernameAndPassword("", "");
} else {
WebServiceUsername = sharedPref.getString(
getString(R.string.SETTINGS_USER_USERNAME), "");
WebServicePassword = sharedPref.getString(
getString(R.string.SETTINGS_USER_PASSWORD), "");
}
}
/*
* Saves the given last action in the sharedPreferences
* #param long LastAction - Time of the last action
*/
private void setLastAction(long LastAction) {
editor = sharedPref.edit();
editor.putLong(getString(R.string.SETTINGS_USER_LAST_ACTION), LastAction);
editor.commit();
}
/*
* Saves the given username and userpassword sharedPreferences
* #param String username
* #param String password
*/
private void setUsernameAndPassword(String username, String password) {
editor = sharedPref.edit();
editor.putString(
getString(R.string.SETTINGS_USER_USERNAME), username);
editor.putString(
getString(R.string.SETTINGS_USER_PASSWORD), username);
editor.commit();
WebServiceUsername = username;
WebServicePassword = password;
}
/*
* Method called when pressing the OK-Button
*/
public void ClickBtnOK(View view) {
// Save User-Creentials
EditText dfsUsername = (EditText) findViewById(R.id.dfsUsername);
String lvsUsername = dfsUsername.getText().toString();
EditText dfsPassword = (EditText) findViewById(R.id.dfsPassword);
String lvsPassword = dfsPassword.getText().toString();
if(lvsUsername.equals("") || lvsPassword.equals("")) {
TextView txtError = (TextView) findViewById(R.id.txtError);
txtError.setText(getString(R.string.ERR_Name_or_Password_empty));
} else {
// Save credentials
setUsernameAndPassword(lvsUsername, lvsPassword);
setLastAction(new Date().getTime());
// open Searchactivity
Intent intent = new Intent(this, SearchActivity.class);
startActivity(intent);
}
}
#Override
protected void onPause() {
super.onPause();
setLastAction(new Date().getTime());
}
#Override
protected void onStop() {
super.onStop();
setLastAction(0);
setUsernameAndPassword("", "");
}
}
Well, if Long, probably because of you put long there. Because of you are using R.string. sometimes it messes up resources ids, so need for clean project, or you have same string values for these ids in your string.xml. Simply saying, somewhere in logic you put long in same key
p.s. I think best practice is to use public static final String MY_PREFERENCE_KEY = "my_preference_key";