Issue with shared - java

I am creating an application and am using shared prefs. The first two activities are a login screen and a reset password screen.
The login username and password initially are "user".When the user logs on, they are redirected to the reset password activity where they must change the password by entering a password, confirm it, and also enter the original password (user).
The new password will be saved to shared preferences thus overwriting the original password.
My issue is that when i run the app on the emulator it crashes every time irrespective of what username and password i use.. Here is the code so far:
LOGIN ACTIVITY
public class SignIn extends Activity {
static final String MY_PREFS = "Prefs";
static final String SAVED_PASSWORD = "Password";
// Object used for Shared Preferences
SharedPreferences appPrefs;
// First method called when the activity is opened
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
// get Shared Preferences for this application
SharedPreferences appPrefs = getSharedPreferences(SAVED_PASSWORD, 0);
}
// Called when the "LOGIN" button is pressed
public void loginBtnClicked(View v){
// The username and password that is to be used on initial use of the application
String userName = "user";
String original_password = "user";
// Get the settings for the password string from the prefs and assign a name
String existingPassword = appPrefs.getString(SAVED_PASSWORD,null);
// Widgets used during the login phase
EditText usernameField = (EditText)findViewById(R.id.editText_username);
EditText passwordField = (EditText)findViewById(R.id.editText_password);
Button reset =(Button)findViewById(R.id.goToReset);
Button next =(Button)findViewById(R.id.next);
// Get the text from the editText fields,convert to a string, and assign a name
String name = usernameField.getText().toString();
String pass = passwordField.getText().toString();
// If either field is empty inform user and return to give them another go
if (name.equals(null)|| pass.equals(null)){
Toast.makeText(this,"ERROR!!, all fields must be filled",Toast.LENGTH_SHORT).show();
return;
}
//========================================
// VALIDATION OF LOGIN INFORMATION SUBMITTED
//========================================
// If there NOT information saved to preferences.
if (existingPassword.equals(null)){
// IF the username and password are "USER"
if(name.equals(userName) && pass.equals(original_password)){
// Create an intent to open the next window
Intent reset_intent = new Intent(this,ResetPassword.class);
// Start the new activity
startActivity(reset_intent);
}
}
//If there IS information saved to preferences.
else if (existingPassword!=null){
//IF the username is "USER"...
if(name.equals(userName) ){
// If the password is what is saved to preferences.
if(pass.equals(existingPassword)){
// Make buttons visible for user choice
reset.setVisibility(View.VISIBLE);
next.setVisibility(View.VISIBLE);
}
else{
// Display a toast pop-up to show the text from the intent
Toast.makeText(this,"ERROR!!,password incorrect",Toast.LENGTH_SHORT).show();
}
}
else{
// Display a toast pop-up to show the text from the intent
Toast.makeText(this,"ERROR!!,username incorrect",Toast.LENGTH_SHORT).show();
}
}
}
// Called when the "GO TO RESET" button is pressed
public void ResetBtnClicked(View v){
// Create an intent to open the next window
Intent reset_intent = new Intent(this,ResetPassword.class);
// Start the new activity
startActivity(reset_intent);
}
//Called when the "NEXT" button is pressed
public void onNextBtnClicked (){
// Create an intent to open the next window
Intent personal_intent = new Intent(this,PersonalDetails.class);
// Start the new activity
startActivity(personal_intent);
}
}
public class ResetPassword extends Activity {
public static final String MY_PREFS = "Prefs";
public static final String SAVED_PASSWORD = "Password";
// for shared preferences
SharedPreferences appPrefs;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reset_password);
// get shared prefs for this application
SharedPreferences appPrefs = getSharedPreferences(SAVED_PASSWORD, 0);
}
//Save the new password
public void resetBtnClicked(View v){
// Widgets used during password reset.
EditText newPassword = (EditText)findViewById(R.id.editText_newPassword);
EditText confirmPassword = (EditText)findViewById(R.id.editText_retypePassword);
EditText currentPassword = (EditText)findViewById(R.id.editText_existingPassword);
// Get the text from the editText fields,convert to a string, and assign a name
String newPass = newPassword.getText().toString();
String confirmPass = confirmPassword.getText().toString();
String currentPass = currentPassword.getText().toString();
// get the settings for the password string from the prefs
String existingPassword = appPrefs.getString(SAVED_PASSWORD,null);
//========================================
// VALIDATION OF PASSWORD INFORMATION SUBMITTED
//========================================
// if the current password submitted is the same as the saved password
if(currentPass.equals(existingPassword)){
//if the new password is the same in both the new and re-enter fields
if(newPass.equals(confirmPass)){
//save the preferences
//get the editor for prefs
Editor prefsEditor = appPrefs.edit();
// update the prefs with the new settings
prefsEditor.putString(SAVED_PASSWORD,newPass);
prefsEditor.commit();
// Create an intent to open the next window
Intent personal_intent = new Intent(this,PersonalDetails.class);
// display a toast pop-up to show the text from the intent
Toast.makeText(this,"New password saved",Toast.LENGTH_SHORT).show();
// Start the new activity
startActivity(personal_intent);
}
// If the passwords do not match
else {
// display a toast pop-up to show the text from the intent
Toast.makeText(this,"Passwords do not match!!",Toast.LENGTH_SHORT).show();
}
}
// if the current password is incorrect
else{
// display a toast pop-up to show the text from the intent
Toast.makeText(this,"Incorrect password used!!",Toast.LENGTH_SHORT).show();
}
// If there is no password saved to prefs.
if (existingPassword.equals(null)){
if(newPass.equals(confirmPass)){
//save the preferences
//get the editor for prefs
Editor prefsEditor = appPrefs.edit();
// update the prefs with the new settings
prefsEditor.putString(SAVED_PASSWORD,newPass);
prefsEditor.commit();
// Create an intent to open the next window
Intent personal_intent = new Intent(this,PersonalDetails.class);
// display a toast pop-up to show the text from the intent
Toast.makeText(this,"New password saved",Toast.LENGTH_SHORT).show();
// Start the new activity
startActivity(personal_intent);
}
else{
// display a toast pop-up to show the text from the intent
Toast.makeText(this,"Passwords do not match!!",Toast.LENGTH_SHORT).show();
}
}
}
}
Any help would be greatly appreciated guys.

By looking at your code app is crashing at these lines bcz you are creating/init a local variable with same instance variable name ie. appPrefs and instance variable appPrefs still null (default value) 1. SignIn Activity
String existingPassword = appPrefs.getString(SAVED_PASSWORD,null);
2. ResetPassword Activity
String existingPassword = appPrefs.getString(SAVED_PASSWORD,null);
Reason :
For both activity you are not initializing the appPrefs object, which is a instance variable
Solution :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reset_password);
// get shared prefs for this application
//your code creates a new local variable with same instance variable name ie. appPrefs
//SharedPreferences appPrefs = getSharedPreferences(SAVED_PASSWORD, 0);
//changes : init instance variable
appPrefs = getSharedPreferences(SAVED_PASSWORD, 0);
}

Related

EditText data not being passed over without button click

I am building an app where you can upload images to my company server
My problem is that I have a login screen with Email, Password and Client ID(in LoginActivity)
Now The data you enter there is passed to another Activity(CameraActivity) and that is used to build a URL with Uri.Builder.
The data is being saved within the edittext boxes BUT it is only being passed(using intents) to the other activity on the button click so, you have to go back to the login screen and click the button to reSubmit the data for every upload and everytime you start the app(The Data is stored within the textboxes but it is not being passed to the other activity without the button click), for the URI.Builder to work and give the entered information to the URL.
I want the client to enter that information ONCE and click the Button ONCE and then it is stored and used everytime regardless of the app being exited etc.
Login Activity, This activity has the edittext boxes and the entered information is being saved but not passed to the other activity without the button click
public class LoginActivity extends AppCompatActivity {
String ID = "id";
String EMAIL = "email";
String PASS = "pass";
private SharedPreferences mPreference;
EditText email, password, id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
email=findViewById(R.id.emailtext);
password=findViewById(R.id.pwdtext);
id=findViewById(R.id.clientid);
Button loginBtn=findViewById(R.id.button);
mPreference = PreferenceManager.getDefaultSharedPreferences(this);
id.setText(mPreference.getString(ID, ""));
email.setText(mPreference.getString(EMAIL, ""));
password.setText(mPreference.getString(PASS, ""));
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EMAIL =email.getText().toString();
PASS =password.getText().toString();
ID =id.getText().toString();
mPreference.edit().putString(ID,ID).apply();
mPreference.edit().putString(EMAIL, EMAIL).apply();
mPreference.edit().putString(PASS, PASS).apply();
Intent intent=new Intent(LoginActivity.this,
CameraActivity.class);
intent.putExtra("clientId", ID);
intent.putExtra("email", EMAIL);
intent.putExtra("password", PASS);
startActivity(intent);
}
});
}
}
As suggested in the question comment, SharedPreferences is a good option.
SharedPreferences getPreferences(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context);
}
void setEmail(Context context, String email) {
SharedPreferences.Editor editor = getPreferences(context).edit();
editor.putString("EMAIL", email);
editor.apply();
}
String getEmail(Context context) {
return getPreferences(context).getString("EMAIL", "");
}
Above is an example of how you can put things and retrieve things from the shared preferences. Since you have more than an email to store (user ID, etc...) you could even store an object as a gson so you would have to call only one function. But of course this is your call.
You can start the CameraActivity if data exist in SharedPreferences.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
email=findViewById(R.id.emailtext);
password=findViewById(R.id.pwdtext);
id=findViewById(R.id.clientid);
Button loginBtn=findViewById(R.id.button);
mPreference = PreferenceManager.getDefaultSharedPreferences(this);
//Check if data exist
if(mPreference.contain(ID))
{
Intent intent=new Intent(LoginActivity.this,
CameraActivity.class);
intent.putExtra("clientId", mPreference.getString(ID, ""));
intent.putExtra("email", mPreference.getString(EMAIL, ""));
intent.putExtra("password", mPreference.getString(PASS, ""));
startActivity(intent);
}
//Rest of the code
}
Cheers :)

RuntimeException when trying to store value fetched from server to sharedpreferences using Asynctask

i am using sharedpreferences to check the app is using for the first time or not.if the app is using for first time registration screen will show , and after that MainActivity will show if registration is completed succussfully or used later . Registration screen is showing when app is runnig for first time but the issue is there in Registering. while calling the shared preferences from MainActivity to insert value in it. and the issue is RuntimeException .this is what i am doing for that...
this is my MainActivity.java
SharedPreferences sp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
firtst_time_check();
setContentView(R.layout.available_items);.....}
this is first_time_check()
private boolean firtst_time_check(){
sp = PreferenceManager.getDefaultSharedPreferences(this);
String first = sp.getString("first", null);
if (first == null){
Intent i = new Intent(getBaseContext(), MainActivity.class);
startActivity(i);
}
return false;
}
this is code from Registration screen where exception is throwing in this line MainActivity set = new MainActivity();
JSONArray a = o.optJSONArray("status");
JSONObject obj = a.optJSONObject(0);
String uid = obj.optString("RegistrationID");
MainActivity set = new MainActivity();
set.sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String value = set.sp.getString("RegistrationID", uid);
SharedPreferences.Editor editor = set.sp.edit();
editor.putString("first", value);
editor.commit();
this is what showing in logcat
lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
No, need to use sp from MainActivity by creating object of Activity for saving value in SharedPreferences in Registration screen because PreferenceManager.getDefaultSharedPreferences also return SharedPreferences instance which we can use for saving and key-value in it. Change :
MainActivity set = new MainActivity();
set.sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
to
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(
getApplicationContext());

Save variable in SharedPreferences based on which button is clicked

Im trying to make an EULA for my app, but there is a different EULA for the different countries we work with.
my idea was that i save a String in SharedPreferences like ZA for South Africa and KE for Kenya. So if you click the South Africa button, it will save the string in SharedPreferences as ZA and the same for Kenya. Once the button has been clicked it the new activity will then load the appropriate EULA by pulling the ZA or KE string from the SharedPreferences. This is what i have at the moment:
Country_select.java
public class country_select extends Activity {
private static final String TAG = "Logs";
public static final String PREFS_NAME = "PrefsFile";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_country_select);
final Button za_button = (Button) findViewById(R.id.btn_za);
Button ke_button = (Button) findViewById(R.id.btn_ke);
Log.i(TAG, "created buttons");
za_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("Country_Selected", "ZA");
editor.commit();
}
});
Log.i(TAG, "set button settings for ZA");
ke_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("Country_Selected", "KE");
editor.commit();
}
});
Log.i(TAG, "set button settings for KE");
}
I may have this totally incorrect but on the layout file there are 2 buttons, one for KE and one for ZA.
I would like it, when the new activity is loaded to read SharedPreferences whether it has ZA or KE? Is what i have done here correct?
Thank you
I think you're better off with using IntentExtras, in your first activity upon clicking the country button store the value inside a variable and when you want to start the new activity pass the data as an intent extra:
Intent intent= new Intent(getActivity(), NewActivity.class);
intent.putExtra("country", countryCode);
startActivity(intent);
And then inside the new activity you can retrieve the value like this:
String countryCode = getIntent().getExtras().getString("country");
In order to maintain Shared preference across the application i use it this way
, take a look
I saved a AppPrefes class as a seprate class in the package
public class AppPrefes {
private SharedPreferences appSharedPrefs;
private Editor prefsEditor;
public AppPrefes(Context context, String Preferncename) {
this.appSharedPrefs = context.getSharedPreferences(Preferncename,
Activity.MODE_PRIVATE);
this.prefsEditor = appSharedPrefs.edit();
}
/****
*
* getdata() get the value from the preference
*
* */
public String getData(String key) {
return appSharedPrefs.getString(key, "");
}
public Integer getIntData(String key) {
return appSharedPrefs.getInt(key, 0);
}
/****
*
* SaveData() save the value to the preference
*
* */
public void SaveData(String Tag, String text) {
prefsEditor.putString(Tag, text);
prefsEditor.commit();
}
public void SaveIntData(String key, int value) {
prefsEditor.putInt(key, value);
prefsEditor.commit();
}
/**
* delete all AppPreference
*/
public void deleteAll() {
this.prefsEditor = appSharedPrefs.edit();
this.prefsEditor.clear();
this.prefsEditor.commit();
}
In your Activity or Fragment were you would like to get or save data just use it like this
Decalre an object for the AppPrefes class
AppPrefes appPref;
Initialize in onCreate
appPref = new AppPrefes(getActivity(), "type name of your preference");
To save data to the preference use
appPref.SaveData("tag_name", "value to be saved);
To get data from the preference
appPref.getData("tag_name");
You can also save Integer values and clear all preference values if necessary just call the apporopriate methods.
Yes, the storing part is correct. Now you will need to access the stored value in your new activity.
Example-
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
String storedCountry = sharedpreferences.getString("Country_Selected"); // could be null value if there is no value stored with Country_Selected tag.

Shared Preferences save and retrieve data

I'm using Shared Preferences to save data from an AutoCompleteTextView.
When the user writes something in this AutoCompleteTextView, he can click a button in order to save what he just wrote (so that he doesn't have to write it every time).
Here's what my code looks like:
private AutoCompleteTextView autoComplete = null;
String nameFile = "Web service data";
String myData = "";
SharedPreferences pref;
Editor editor;
String channel = "";
String[] valuesArray = {channel};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
pref = getApplicationContext().getSharedPreferences("MyPref", 0);
editor = pref.edit();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, valuesArray);
autoComplete = (AutoCompleteTextView) findViewById(R.id.autocompletion);
autoComplete.setAdapter(adapter);
Button add = (Button) findViewById(R.id.add);
add.setOnClickListener(sendForm2);
Button remove = (Button) findViewById(R.id.remove);
remove.setOnClickListener(sendForm2);
channel = pref.getString(nameFile, null);
}
OnClickListener sendForm2 = new OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.add:
myData = autoComplete.getText().toString();
editor.putString(nameFile, myData);
editor.commit();
break;
case R.id.remove:
editor.remove(nameFile);
editor.commit();
break;
}
}
};
The problem is, the Shared Preferences doesn't save any data in channel at all. Even when I close the application and restart it.
Any clue or idea how to resolve this problem?
First thing I would try would be to add a
Log.d("OnCreate", "channel : "+ channel);
in the onCreate just after
channel = pref.getString(nameFile, null);
to see if you have something inside.
If you don't, this really means that sharedpref are not saved.
In this case I would try to bring back the :
pref = getApplicationContext().getSharedPreferences("MyPref", 0);
editor = pref.edit();
just before the
switch (v.getId()) {
I remember reading that sometimes depending on what you are doing with your activities, the sharedpref editor you create can be "lost" and not be related to anything later in the code.
Use the following method to save and retrive String prefrence.
//save the prefrence by pasing key and data
public static void SavePrefrence(Context ctx, String Key, String value) {
ctx.getSharedPreferences("mypref", ctx.MODE_PRIVATE)
.edit().putString(Key, value).commit();
}
//get the prefrence by passing your key
public static String getPrefrence(Context ctx, String key) {
SharedPreferences pref = ctx.getSharedPreferences(
"mypref", ctx.MODE_PRIVATE);
String result = pref.getString(key, null);
return result;
}

Storing a string into a permenant variable issue

I'am trying to store a string from a variable (NumberString) to another variable (PermenantString)
When the string is entered in to PermenantString, it should be stored permenantly in that variable, until the app is deleted or i specifically create a button to clear that PermenantString variable.
MainAvtivity
public class MainActivity extends Activity {
public final String PermenantString= "";
verified.class
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.verified);
Button VerifyCompleteButton = (Button) findViewById(R.id.VerifyCompleteButton);
VerifyCompleteButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
String NumberString;
String PermenantString;
//TextView NUMView;
TextView NUMView = (TextView) findViewById(R.id.NUMView);
Bundle bundle = getIntent().getExtras();
NumberString= bundle.getString("NumberString");
PermenantString = bundle.getString("PermenantString");
PermenantString= NumberString.toString();
//set String PermenantString= ""; permenantly
NUMView.setText(PermenantString);
//
}
});
You should use preferences or sqlite to store the data. Check the storage options #
http://developer.android.com/guide/topics/data/data-storage.html
Example:
public static final String PREFS_NAME = "MyPrefsFile";
Then
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("key", stringvalue);
editor.commit();
Then to get
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
String value = settings.getString("key","defaultstring");
Note that variables are stored in volatile RAM memory. By volatile, I mean that the value is stored only as long as your app is running. This is the very opposite of the permanence that you seem to want.
In order to save a variable that will persist after your app is destroyed, you must use some storage mechanism such as SharedPreferences or a SQLite database. For more information, you should read Storage Options in the Android Developer Guides.

Categories