Shared preferences issue - android

I'm new to android development
In my application I want to keep log-in status of user in my activity. I have 2 edit boxes for entering name and password. And 1 check-box for user if he wants to keep log-in.
When user clicks on login button I'm saving name and password in shared preference. And in onCreate method I want to retrieve that value. If user has clicks check-box then he should directly redirect to next page. But its not working.
Here is my code:
signUpButton=(Button)findViewById(R.id.signUpLoginId);
signUpButton.setOnClickListener(this);
//toggleButtonOnOff=(ToggleButton)findViewById(R.id.togglebutton);
loginEditText = (EditText) findViewById(R.id.loginNameID);
passwordEditText=(EditText)findViewById(R.id.passwordId);
box=(CheckBox)findViewById(R.id.checkbox);
preferences=PreferenceManager.getDefaultSharedPreferences(context);
String n=preferences.getString(PREF_USERNAME, null);
String p=preferences.getString(PREF_PASSWORD, null);
loginEditText.setText(n1);
passwordEditText.setText(p1);
Intent intent1=new Intent(LoginActivity.this,FindFishMenuActivity.class);
startActivity(intent1);
LoginActivity.this.finish();
if(box.isChecked())
{
box.setChecked(true);
Toast.makeText(LoginActivity.this,"box value set to true",Toast.LENGTH_LONG).show();
password=passwordEditText.getText().toString();
preferences=context.getSharedPreferences(key_str, MODE_PRIVATE);
editor=preferences.edit();
editor.putString(PREF_USERNAME, name);
editor.putString(PREF_PASSWORD, password);
editor.commit();
intent=new Intent(LoginActivity.this,FindFishMenuActivity.class);
startActivity(intent);
LoginActivity.this.finish();
}

If you finish your Activity, the Code after it is never reached!
But I would put the code which saves your Name and Password to the SharedPreference before you fire the Intent. Maybe the Preference-Object isn't saved yet when you try to read from it in the other Activity. Try debuging this using LogCat.

Related

can I change launcher activity in MainAvtivity

How can I change Launcher activity in android studio using Button click in Java file??
for example, if user clicks Button1 then a activity will be launcher activity and if user clicks Button2 then another activity will be a launcher activity???
Which activity is launched at startup is determined by the AndroidManifest.xml file, you cannot modify this at runtime.
However, you can make an activity whose sole purpose is to launch the app and then choose which other activity to launch:
in button 1 click, save activity 1's name into a sharedpreferences entry
in button 2 click, save the other's name
in the launch activity, check the value of the sharedpreferences entry and launch an intent with the correct activity based on that
Edit: example for what you are trying to do
In your Button1 click:
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// get the sharedpreferences with the name "myPreferencesName"
// and the mode "MODE_PRIVATE" (i.e. only you can read the settings stored in it)
// and then get its editor
SharedPreferences.Editor editor = getApplicationContext().
getSharedPreferences("myPreferencesName", Context.MODE_PRIVATE).
edit();
editor.putString("activityToLaunch", "activity1"); // activity1 can be whatever string you choose, not neccessarily the actual name of the activity
editor.apply();
}
});
In your button2 click, you do the same but put "activity2" as the preference value
In your MainActivity onCreate:
SharedPreferences prefs = getApplicationContext().
getSharedPreferences("myPreferencesName", Context.MODE_PRIVATE);
if(!prefs.contains("activityToLaunch")) {
// neither button has been pressed since you installed the app
// this always happens on the first launch after installation
// do the editor thing here as you would in the button click
// depending on which activity you want to be default, either set the preference value to "activity1", or "activity2", then editor.apply() it
}
if(prefs.getString("activityToLaunch").equals("activity1")) {
Intent intent = new Intent(getApplicationContext(), Activity1.class);
startActivity(intent);
}
else {
Intent intent = new Intent(getApplicationContext(), Activity2.class);
startActivity(intent);
}

Hide Intent if Default Data Inserted

I have an intent that appear only if certain data have not been inserted yet. It's like a custom form to insert some data. If the data have been inserted, in the future the apps opened, the intent will not appear anymore. It will open another intent, the default one. (Usually this might occur when the apps opened for the first time)
How do I manage the intent since the default intent could only be one?
For example: If the apps opened for the first time it will startIntent Form
next time the apps opened (assumed the data already inserted) it will startIntent MainActivity
i use sharedpreferences to insert data only once , simply use it this way, in the below code
the intent will be started only once the application is first installed, after that it will start the main activity intent.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (isFirstTime()) {
// startIntent Form
}
}
private boolean isFirstTime()
{
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
boolean ranBefore = preferences.getBoolean("RanBefore", false);
if (!ranBefore) {
// first time
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("RanBefore", true);
editor.commit();
}
return !ranBefore;
}
I assume you are doing something like registration thing, and want to show this form once. you have many options here.
1) As Ahmad(in the comments) says use SharedPreferences, and add some flag into it, which can tell you if the data is available or not. add a check in the very beginning of the activity/onCreate and open respective inten/activity depends on check.
2) you can use Database as well to see this value.
I would suggest you to use SPLASH screen, check this value/registration data into it. And if available start Activity A, else start Registration/default one.

Android login at once

How do I code for login in some app in android that I do not need to login in it again next time I open the application ?
I tried a lot, but no success. If possible please provide me code.
In my app I created a base class for all my activities which checks in oncreate if the user is logged in with shared preferences. If not I show the login screen and continue my app after a successful login.
If this login is local:
First time when you login,
Editor editor= YourSharedPreference.edit();
editor.put(nameOfAccount,name);
editor.put(passwordOfAccount,password);
editor.commit();
Then every time you open the APP,
if(YourSharedPreference.contain(nameOfAccount)&&YourSharedPreference.contain(passwordOfAccount))
{//do not need login}
else
{//do login thing}
An easy way it to store it in the shared preferences.
Basicaly you request a shared preference then you can get string value from it (load).
Using the a SharedPreferences.Editor you can put string value into it (save).
Checking if the value is set (null) will tell you if the user already logged in your app or not.
Here an exemple:
#Override
protected void onCreate(Bundle state){
super.onCreate(state);
. . .
// Restore preferences
SharedPreferences settings = getSharedPreferences("LOGIN_PREF", 0);
String login = settings.getString("login", null);
String password = settings.getString("password", null);
if(login == null || password == null){
// Do stuff for login user
}else{
// Do stuff for not logged user
}
}
public void saveLogin(String password, String login){
SharedPreferences settings = getSharedPreferences("LOGIN_PREF", 0);
SharedPreferences.Editor loginEditor = settings.edit();
loginEditor.putString("login", login);
loginEditor.putString("password", login);
loginEditor.commit();
}

How to implement a registration activity in android that works only for once?

I'm designing an application that has an activity for registration process, this activity launches on default. I want this activity to be disabled forever once the registration process has been completed successfully and then it should be replaced by a different activity as the default activity for the rest of the lifetime of the application.I've tried to search my way through this problem but I've hardly found anything.Any help will be much appreciated.
Thanks in advance.
Once registration is complete, commit some value to the SharedPreferences, then in your splash screen or some other opening Activity, check the preferences. If the value indicates that the registration is complete, start a different Activity instead of the Registration one...
Example:
public class SplashScreen extends Activity {
public void onCreate(Bundle state) {
super.onCreate(state);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean regComplete = prefs.getBoolean("registration", false);
if(regComplete) {
startActivity(new Intent(this, SomeActivity.class));
} else {
startActivity(new Intent(this, Registration.class));
}
}
Better still:
Always launch the registration, but in onCreate(), simply launch a different Activity immediately and finish() the registration Activity if the prefs indicate that registration is complete.
Edit
SharedPreferences explained:
SharedPreferences lets you persist primitive values in your app. You grab the SharedPreferences by doing:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
then you write to SharedPreferences by getting the Editor. To do this, you call
SharedPreferences.Editor editor = prefs.Edit();
then you can commit values to the editor by using key/values:
editor.putBoolean("some string as a key here", true/false);
Then to actually save that, you call editor.commit();
Then you grab values back from SharedPreferences by simply calling
prefs.getBoolean("some previously chosen string as a key here", true/false);
where true/false is the default value that will be returned if no such key exists...
This is convenient and lets you do simple things like:
editor.putInt("some important number", 55);
editor.commit();
......later
int i = prefs.getInt("some important number", -1);
if(i != -1) {
//do stuff
} else {
//do other stuff
}
Also, please see: http://developer.android.com/guide/topics/data/data-storage.html#pref
Don't have the registration Activity be the default. Instead have another Activity as the default, and then at runtime it can check to see which Activity it should send the user to. If they haven't registered then startIntent( RegistrationActivity.class ).

shared preference in android

I am new in android development.
I've an activity in which I'm taking user name and password.and I'm passing those values to a web service which returns a key as a response.i have one toggle button in my activity. now if the user checks the toggle button that means he want to keep logged in and the user should be redirected to next activity when he next time log-in.
If toggle button is checked I'm storing user name, password and key in shared preference.
but I'm not getting how to retrieve those details next time(i.e when user next time log-in)
userDetails = this.getSharedPreferences("userdetails", MODE_PRIVATE);
Editor edit = userDetails.edit();
edit.clear();
edit.putString("username", txtUname.getText().toString().trim());
edit.putString("password", txtPass.getText().toString().trim());
edit.commit();
Toast.makeText(this, "Login details are saved..", 3000).show();
this way you can fetch preference
String Uname = userDetails.getString("username", "");
String pass = userDetails.getString("password", "");
and check for login this way
if(Uname=="" && pass =="")
//Go to login
else
//Go to Next Activity
try like this
best of luck
try this for store value in sharePreferences..
SharedPreferences prefs = getSharedPreferences("Share", Context.MODE_PRIVATE );
Editor editor = prefs.edit();
editor.putInt("Value", 1 );
editor.commit();
for get value
prefs.getInt("Value",0);
/////////////////////////////////////////
String Uname = userDetails.getString("username", "");
String pass = userDetails.getString("password", "");
if(Uname=="" && pass =="")
//Go to login
else
//Go to Next Activity
Based on the Checkbox add a sharedPreferences Boolean value when the user checks/unchecks on keep logged in. Then as you call onCreate of Login activity you need to check this and call the next activity if the boolean value is true.
Avoid storing the user password.
For each user, consider storing:
the user id
a random seed unique to this user
a hash of the seeded password.
The user will need to reenter his password, then you can add the stored seed to the entered password and apply the hash algorithm X times to the seeded password. Then compare the hash to the stored hash.
Then he can encrypt the password and store it in sharedpreferences whenever he needs the password he can get that encrypted password from the sharedpreferences and decrypt it.
Try this https://prashantsolanki3.github.io/Secure-Pref-Manager/ for saving and retrieving shared preferences securely and with ease.
The keys and values are automatically encrypted.
Save:
SecurePrefManager.with(this)
.set("user_name")
.value("LoremIpsum")
.go();
Retrieve:
String userName = SecurePrefManager.with(this)
.get("user_name")
.defaultValue("unknown")
.go();
Hope this helps!

Categories

Resources