Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use getSharedPreferences in android

I have an application in which I have to implement a "Login" activity. I have these components:

  1. EditText username
  2. EditText password
  3. Button Login
  4. Button Cancel

I want that my application to remember the login details of the user once the user has logged in until the user would press the "log out" button. I'm not using preferences in my xml.

How do I get the getSharedPreferences(String name, int mode) to work in my application?

like image 290
CMA Avatar asked May 10 '11 12:05

CMA


People also ask

How do I save preferences on Android?

Shared Preferences allow you to save and retrieve data in the form of key,value pair. In order to use shared preferences, you have to call a method getSharedPreferences() that returns a SharedPreference instance pointing to the file that contains the values of preferences.

What is the difference between getPreferences () and getSharedPreferences ()?

getSharedPreferences() - Use this if you need multiple preferences files identified by name, which you specify with the first parameter. getPreferences() - Use this if you need only one preferences file for your Activity. Because this will be the only preferences file for your Activity, you don't supply a name.

What is shared preferences in Android?

A SharedPreferences object points to a file containing key-value pairs and provides simple methods to read and write them. Each SharedPreferences file is managed by the framework and can be private or shared. This page shows you how to use the SharedPreferences APIs to store and retrieve simple values.


1 Answers

First get the instance of SharedPreferences using

SharedPreferences userDetails = context.getSharedPreferences("userdetails", MODE_PRIVATE); 

Now to save the values in the SharedPreferences

Editor edit = userDetails.edit(); edit.putString("username", username.getText().toString().trim()); edit.putString("password", password.getText().toString().trim()); edit.apply(); 

Above lines will write username and password to preference

Now to to retrieve saved values from preference, you can follow below lines of code

String userName = userDetails.getString("username", ""); String password = userDetails.getString("password", ""); 

(NOTE: SAVING PASSWORD IN THE APP IS NOT RECOMMENDED. YOU SHOULD EITHER ENCRYPT THE PASSWORD BEFORE SAVING OR SKIP THE SAVING THE PASSWORD)

like image 149
Dharmendra Avatar answered Oct 11 '22 11:10

Dharmendra