Android ClassCastException after reading from SharedPreferences - android

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";

Related

store edited values in edittext fields after changed paramaters

public class ActivityEditParent extends AppCompatActivity {
private static final String TAG="ActivityEditParent";
CustomEditText etFirstName,etLastName,etEmail,etPhone;
public static ConnectionDetector detector;
private static final String URL = "http://hooshi.me.bh-in-13.webhostbox.net/index.php/parents/editprofile";
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
private CustomButton btnSave;
private String parentFirstName,parentLastName,parentPhone;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_parent);
getSupportActionBar().hide();
detector = new ConnectionDetector(ActivityEditParent.this);
getUIComponents();
}
private void getUIComponents(){
etFirstName = (CustomEditText) findViewById(R.id.edit_first_name);
etLastName = (CustomEditText) findViewById(R.id.edit_last_name);
etEmail = (CustomEditText) findViewById(R.id.edit_email_address);
etPhone = (CustomEditText) findViewById(R.id.edit_phone_number);
btnSave = (CustomButton) findViewById(R.id.btn_save_parent);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editParent();
}
});
TextView title = (TextView) findViewById(R.id.toolbar_title);
ImageButton back = (ImageButton) findViewById(R.id.toolbar_back);
title.setText("Edit parent");
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goBack();
}
});
sharedPreferences = getSharedPreferences(AppConstants.OOSH_PREFERENCES, Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
String fName = sharedPreferences.getString(AppConstants.PARENT_FNAME,AppConstants.fName);
String lName = sharedPreferences.getString(AppConstants.PARENT_LNAME,AppConstants.lName);
String email = sharedPreferences.getString(AppConstants.PARENT_EMAIL,AppConstants.email);
String phone = sharedPreferences.getString(AppConstants.PARENT_MOBILE,AppConstants.mobile);
etFirstName.setText(fName);
etLastName.setText(lName);
etPhone.setText(phone);
etEmail.setText(email);
}
private void goBack() {
startActivity(new Intent(getApplicationContext(), ActivityEditDetails.class));
finish();
}
private void editParent(){
SharedPreferences preferences = getSharedPreferences(AppConstants.OOSH_PREFERENCES, Context.MODE_PRIVATE);
final SharedPreferences.Editor editor = preferences.edit();
JSONObject jsonParam = null;
parentFirstName = etFirstName.getText().toString().trim();
parentLastName = etLastName.getText().toString().trim();
parentPhone = etPhone.getText().toString().trim();
if (detector.checkInternet()){
jsonParam = new JSONObject();
JSONObject header = new JSONObject();
try {
jsonParam.put("parentId",preferences.getString(AppConstants.PARENT_ID,""));
jsonParam.put("parentFN",parentFirstName);
jsonParam.put("parentLN",parentLastName);
jsonParam.put("parentPhone",parentPhone);
jsonParam.put("apiAccessKey",preferences.getString(AppConstants.API_ACCESS_KEY,""));
header.put("parent",jsonParam);
Log.d("POST PARAMETERS:",""+header);
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, URL, header, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Response:",""+response);
String json_status = null;
try {
json_status = response.getString("status");
if (json_status.equalsIgnoreCase("Success")){
Toast.makeText(getApplicationContext(), "changed parent details successfully", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),ActivityHome.class));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
VolleySingleton.getInstance(getApplicationContext()).addToRequestQueue(jsonObjectRequest);
}
}
}
In the response After getting success message I want save the edited details in in respective edit text fields please help.After success message I am moving to home screen through intent and again I get back to this screen it is showing the previous details only.
all happens here :
...
if (json_status.equalsIgnoreCase("Success")){
Toast.makeText(getApplicationContext(), "changed parent details successfully", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),ActivityHome.class));
}
...
once you have a success response save the edited values on the preferences, for example etFirstName, save it is new value to the corresponding preference :
...
if (json_status.equalsIgnoreCase("Success")){
Toast.makeText(getApplicationContext(), "changed parent details successfully", Toast.LENGTH_SHORT).show();
editor.putString(AppConstants.PARENT_FNAME, parentFirstName);
editor.apply(); //don't forget this
startActivity(new Intent(getApplicationContext(),ActivityHome.class));
}
...
any way you're creating the editor but not using it.
you want to save data after download from network or after an edit in edit text fields was made??
if from network add some save method execution statement in code where you download data was successful
if (json_status.equalsIgnoreCase("Success")){
Toast.makeText(getApplicationContext(), "changed parent details successfully", Toast.LENGTH_SHORT).show();
// here you have successful received data so u can map them to edit text or save in shared prefs
// add method to save data here
saveData(response);
startActivity(new Intent(getApplicationContext(),ActivityHome.class));
}
private void saveData(JSONObject response) {
// use JSon response object save here to shared preferences
// see how to load data from json object
// https://processing.org/reference/JSONObject_getString_.html
SharedPreferences sharedPreferences = getSharedPreferences(AppConstants.OOSH_PREFERENCES, Context.MODE_PRIVATE);
sharedPreferences.putString(....).apply;
// or set edit text controls with JSon data
}
to save edit text changes you have two choices :
add to layout save button (you have one) button and set on click listener with method to save data:
btnSave = (CustomButton) findViewById(R.id.btn_save_parent);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveData(v);
}
});
private void saveData(View view) {
// get root view
View rootView = view.getRootView();
// find edit text widget on root view
EditText etFirstName = (EditText) rootView.findViewById(R.id.edit_first_name);
// get string from edit text widget
String firstName = etFirstName.getString.toString();
// get shared preferences
SharedPreferences sharedPreferences = getSharedPreferences(AppConstants.OOSH_PREFERENCES, Context.MODE_PRIVATE);
// save to shared prefs firstName wher NAME_KEY is string to identified your saved data for later use - to load
sharedPreferences.putString(NAME_KEY,firstName).apply;
}
private void loadDataFromSharedPredferences(View view) {
// get shared preferences
SharedPreferences sharedPreferences = getSharedPreferences(AppConstants.OOSH_PREFERENCES, Context.MODE_PRIVATE);
// load data from shared prefs firstName wher NAME_KEY is string to identified data to load
String firstName = sharedPreferences.getString(NAME_KEY,firstName);
// get root view
View rootView = view.getRootView();
// find edit text widget on root view
EditText etFirstName = (EditText) rootView.findViewById(R.id.edit_first_name);
// set string to edit text widget
etFirstName.setText(firstName);
}
add on text change listener for edittext widgets
ps. you need to clarify - write a exactly steps of what you want to do achieve
load data from network ? then save ?
or save request date ?
or save result data ?

SharedPreference value changes back on every login even with commit()

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.

sharedpreferences data lost when press back button android?

I have login activity and saved data into sharedpreferences data storage .
when I open app then first time login activity load and fill user credentials and stored in sharedpreferences, open Main Activity but when I press back button on Main Activity sharedpreferences data lost.
And next time when I opened app it shown login activity instead should be open Main Activity because I matched data this time from sharedpreferences.
My Complete code of Login Activity
public class Login extends AppCompatActivity implements View.OnClickListener {
private String output;
private Toolbar toolbar;
private Button button;
EditText Username,Password;
String myURL,userValue,passValue;
public static final String DEFAULT="N/A";
List<DataModel> loginList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
Username = (EditText) findViewById(R.id.etUsername);
Password = (EditText) findViewById(R.id.etPassword);
button = (Button) findViewById(R.id.btn_login);
button.setOnClickListener(this);
SharedPreferences sharedPreferences = getSharedPreferences("loginData",this.MODE_PRIVATE);
String user = sharedPreferences.getString("username",DEFAULT);
String pass = sharedPreferences.getString("password",DEFAULT);
if(user.equals(DEFAULT) || pass.equals(DEFAULT) && user==null && pass ==null)
{
Toast.makeText(this,"No Data was found",Toast.LENGTH_LONG).show();
}else{
Toast.makeText(this,"Data was found",Toast.LENGTH_LONG).show();
Toast.makeText(this,user+pass,Toast.LENGTH_LONG).show();
CheckOnline();
}
}
private void CheckOnline() {
if(inOnline())
{
String user,pass="";
SharedPreferences sharedPreferences = getSharedPreferences("loginData", this.MODE_PRIVATE);
user = sharedPreferences.getString("username", DEFAULT);
pass = sharedPreferences.getString("password", DEFAULT);
String getStatus = sharedPreferences.getString("LoggedIn", DEFAULT);
if (getStatus.equals("true")) {
Toast.makeText(this, user + pass, Toast.LENGTH_LONG).show();
myURL = "http://www.example.com/extra/login.php?user=" + user + "&pass=" + pass;
requestData(myURL);
}
}
else
{
Toast.makeText(this, "Network isn't available", Toast.LENGTH_LONG).show();
}
}
protected boolean inOnline()
{
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if(netInfo!=null && netInfo.isConnectedOrConnecting())
{
return true;
}
else{
return false;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void requestData(String uri) {
LoginCheck check=new LoginCheck();
check.execute(uri);
}
#Override
public void onClick(View v) {
// startActivity(new Intent(this, MainActivity.class));
if(v.getId()==R.id.btn_login)
{
if(inOnline())
{
userValue = Username.getText().toString();
passValue = Password.getText().toString();
myURL = "http://www.example.com/extra/login.php?user="+userValue+"&pass="+passValue;
requestData(myURL);
}
else
{
Toast.makeText(this, "Network isn't available", Toast.LENGTH_LONG).show();
}
// LoginCheck loginCheck = new LoginCheck();
// loginCheck.execute(new String[]{"http://www.dialerphilippines.com/predictivedialervoip/extra/login.php"});
}
}
protected String updateDisplay()
{
if(loginList != null) {
for(DataModel login : loginList) {
output = (login.getLoginResult() + "\n");
}
}
else{
output = "null hai";
}
return output;
}
#Override
public void onBackPressed() {
Login.this.finish();
}
private class LoginCheck extends AsyncTask<String,String,String>{
ProgressDialog dialog = new ProgressDialog(Login.this);
#Override
protected void onPreExecute() {
dialog.setMessage("Login....");
dialog.show();
}
#Override
protected String doInBackground(String... params) {
String content = null;
try {
content = HttpManager.getData(params[0]);
} catch (IOException e) {
e.printStackTrace();
return null;
}
return content;
}
#Override
protected void onPostExecute(String result) {
// loginList = JSONParser.parseLogin(result);
// String my = StringUtils.deleteWhitespace
// startActivity(new Intent(this, MainActivity.class));
String strWithoutWhiteSpace = result.trim();
// Integer res = Integer.parseInt(strWithoutWhiteSpace);
if(strWithoutWhiteSpace.equals("success")) {
SharedPreferences sharedPreferences = getSharedPreferences("loginData",MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("username",userValue);
editor.putString("password", passValue);
editor.putString("LoggedIn", "true");
editor.commit();
startActivity(new Intent(Login.this, MainActivity.class));
finish();
}
else{
Toast.makeText(Login.this, "Either Username or Password is not correct", Toast.LENGTH_SHORT).show();
}
dialog.dismiss();
}
}
}
Inserting data in shared Prefrences
SharedPreferences.Editor editor = getSharedPreferences(FILE_NAME, MODE_PRIVATE).edit();
editor.putString("name", "John");
editor.putInt("fName", "ALEX");
editor.commit();
Getting data back from Stored Shared Prefrences
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String name = prefs.getString("name", "default_value");
String fName= prefs.getInt("fName", "default_value");
You can create another shared preference value that holds whether the condition of Isloggedin is true and use this to redirect your activity.
String getStatus = pref.getString("LoggedIn", "nil");
if (getStatus.equals("true")) {
// go to main or wherever your want.
startActivity(new Intent(this, MYActivity.class));
} else {
// TO DO - go to login page
}
When Login validated and you are updating your shared preferences or "putting" your values in for login; update your isloggedin preference.
editor.putString("LoggedIn", "true");
editor.commit();
Also take control of your backpressed events, by overriding the onbackpressed.
#Override
public void onBackPressed() {
// TO DO
}
Providing Proper Back Navigation
edit
After your additional information:
1. I am not sure how finishing your activity in the onbackpressed event is helpful. It would be better to redirect your activity elsewhere, rather than finish the activity. This is not making sense to me. eg
#Override
public void onBackPressed() {
// TO DO
startActivity(new Intent(this, SomeActivityIWantTheUserToGoto.class));
}
Also, I cannot see where you are getting the string result from.
Apart from this. I suggest you implement what I have suggested. Completely, with a review of your string result. This question is growing and there comes a point in time where I cannot keep attending it.
Thanks.
edit2
I suggest you log what result is in your on postexecute. Actually check what result is.

Android SharedPreferences not loading and saving properly

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);
}
}

ActivityUnitTestCase vs PreferenceScreen

I have a newly created android-18 app, with a PreferenceScreen that's too obvious & simple to list.
And I also have an automated test [fixed to convert the questions into the answers].
public class MyPreferenceTest extends ActivityUnitTestCase<MyPreference> {
Intent intent;
MyPreference activity;
public MyPreferenceTest() {
super(MyPreference.class);
}
#Override
protected void setUp() throws Exception {
Context targetContext = getInstrumentation().getTargetContext();
intent = new Intent(targetContext, MyPreference.class);
super.setUp();
}
private void assembleActivity() {
startActivity(intent, null, null);
activity = getActivity();
}
private void assemblePreferences(String device, String userName, String password) {
Context targetContext = getInstrumentation().getTargetContext();
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(targetContext);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("smart_phin_bluetooth_devices", device);
editor.putString("username", userName);
editor.putString("password", password);
editor.commit();
}
public void test_empty_userNames_dont_reflect_into_the_summary() {
assemblePreferences("", "", "");
assembleActivity();
activity.onResume();
EditTextPreference userName = (EditTextPreference) activity.findPreference("username"); // FIXME userName
assertEquals("", userName.getEditText().getText().toString());
assertEquals("", userName.getText());
assertEquals("Enter your user name", userName.getSummary().toString());
}
public void test_full_userNames_reflect_into_the_summary() {
assemblePreferences("", "BookerT", "");
assembleActivity();
activity.onResume(); // We must call this bc Android does but the test rig does not...
EditTextPreference userName = (EditTextPreference) activity.findPreference("username");
assertEquals("username", userName.getKey());
assertEquals("BookerT", String.valueOf(userName.getText().toString());
// assertEquals("BookerT", userName.getEditText().getText().toString());
assertEquals("BookerT", userName.getSummary().toString());
}
} // end of class MyPreferenceTest
The commented-out assertion would fail because nothing has invoked that EditText view yet.
The test now checks that new code in onResume() updates the Summary from generic verbiage to reflect the Preference's current value.
You have a bug in your tests.
private void assemblePreferences(String device, String userName, String password)
Note that the order of values here is device, userName, password.
assemblePreferences("BookerT", "", "");
Hence device is BookerT, not userName.

Categories

Resources