sharedpreferences data lost when press back button android? - 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.

Related

I want to store Register and Login information in shared preferences in android

I know there are n number of examples in android for shared preferences but I want to Register and store the info in shared preferences and in database using JSON. And then fetch data from JSON and Login with those credentials. If user is already logged in open Main Activity,else go to Splash screen and then open Login Activity. Please go through my detailed code :
RegisterActivity :
public class RegisterActivity extends AppCompatActivity implements ServerRequests.Registereponse {
private EditText password, phone, email;
public static EditText name;
ServerRequests serverRequests;
JSONParser jsonParser;
private Button registerButton;
TextView alreadyMember;
Editor editor;
UserSession session;
SharedPreferences sharedPreferences;
public static final String MyPREFERENCES = "MyPrefs";
public static final String Name1 = "nameKey";
public static final String Phone1 = "phoneKey";
public static final String Email1 = "emailKey";
public static final String Password1 = "passwordKey";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
jsonParser = new JSONParser();
serverRequests = new ServerRequests(getApplicationContext());
serverRequests.setRegistereponse(this);
alreadyMember = (TextView) findViewById(R.id.alreadyMember);
name = (EditText) findViewById(R.id.FName);
phone = (EditText) findViewById(R.id.PhoneNum);
email = (EditText) findViewById(R.id.mail);
password = (EditText) findViewById(R.id.password);
registerButton = (Button) findViewById(R.id.email_sign_in_button);
sharedPreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
registerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CharSequence temp_emailID = email.getText().toString();
if (name.getText().toString().length() == 0) {
name.setError("Please enter your name");
name.requestFocus();
} else if (phone.getText().toString().length() == 0) {
phone.setError("Please enter your phone number");
phone.requestFocus();
} else if (!isValidEmail(temp_emailID)) {
email.setError("Please enter valid email");
email.requestFocus();
} else if (password.getText().toString().length() == 0) {
password.setError("Please enter password");
password.requestFocus();
} else {
try {
String Name = name.getText().toString();
String Email = email.getText().toString();
String Password = password.getText().toString();
String Phone = phone.getText().toString();
JSONObject obj = jsonParser.makeRegisterJson(Name, Email, Password, Long.parseLong(Phone));
Log.e("final Json", obj.toString());
serverRequests.register(obj);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(Name1, Name);
editor.putString(Email1, Email);
editor.putString(Password1, Password);
editor.putString(Phone1, Phone);
editor.commit();
// Toast.makeText(RegisterActivity.this, "Registered Successfully!", Toast.LENGTH_LONG).show();
} catch (Exception e) {
}
}
// startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
}
});
alreadyMember.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
finish();
}
});
}
#Override
public void onRegsiterReposne(JSONObject object) {
Toast.makeText(RegisterActivity.this, "hiii" + object.toString(), Toast.LENGTH_SHORT).show();
}
public final static boolean isValidEmail(CharSequence target) {
if (TextUtils.isEmpty(target)) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
}
LoginActivity :
public class LoginActivity extends AppCompatActivity implements ServerRequests.Loginreponse {
private static final String PREFER_NAME = "Reg";
private Button email_sign_in_button;
private EditText email, password;
private TextView notMember, forgotPass;
UserSession session;
private SharedPreferences sharedPreferences;
ServerRequests serverRequests;
JSONParser jsonParser;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
jsonParser = new JSONParser();
serverRequests = new ServerRequests(getApplicationContext());
serverRequests.setLoginreponse(this);
notMember = (TextView) findViewById(R.id.notMember);
forgotPass = (TextView) findViewById(R.id.forgotPass);
notMember.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
finish();
}
});
forgotPass.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, ForgotPassword.class));
}
});
// get Email, Password input text
email = (EditText) findViewById(R.id.email);
password = (EditText) findViewById(R.id.pass);
// User Login button
email_sign_in_button = (Button) findViewById(R.id.login);
sharedPreferences = getSharedPreferences(PREFER_NAME, MODE_PRIVATE);
// Login button click event
email_sign_in_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
String Email = email.getText().toString();
String Password = password.getText().toString();
JSONObject obj = jsonParser.makeLoginJson(Email, Password);
Log.e("final Json", obj.toString());
serverRequests.login(obj);
} catch (Exception e) {
}
// startActivity(new Intent(LoginActivity.this, MainActivity.class));
// finish();
}
});
}
#Override
public void onLoginReposne(JSONObject object) {
Toast.makeText(LoginActivity.this, "helloo" + object.toString(), Toast.LENGTH_SHORT).show();
if (object.toString().contains("true")) {
Toast.makeText(LoginActivity.this, "Logged in..", Toast.LENGTH_SHORT).show();
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
}
}
}
SplashScreen :
public class SplashScreen extends Activity {
Thread splashTread;
SharedPreferences preferences;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
StartAnimations();
}
public void onAttachedToWindow() {
super.onAttachedToWindow();
Window window = getWindow();
window.setFormat(PixelFormat.RGBA_8888);
}
private void StartAnimations() {
Animation anim = AnimationUtils.loadAnimation(this, R.anim.alpha);
anim.reset();
LinearLayout l = (LinearLayout) findViewById(R.id.lin_lay);
l.clearAnimation();
l.startAnimation(anim);
anim = AnimationUtils.loadAnimation(this, R.anim.translate);
anim.reset();
ImageView iv = (ImageView) findViewById(R.id.splashImage);
iv.clearAnimation();
iv.startAnimation(anim);
/* TextView tv = (TextView) findViewById(R.id.splashText);
tv.clearAnimation();
tv.startAnimation(anim);*/
splashTread = new Thread() {
#Override
public void run() {
try {
int waited = 0;
// Splash screen pause time
while (waited < 3500) {
sleep(100);
waited += 100;
}
startNextScreen();
} catch (InterruptedException e) {
// do nothing
} finally {
SplashScreen.this.finish();
}
}
};
splashTread.start();
}
private void startNextScreen() {
preferences = getSharedPreferences("TrainingApp", MODE_PRIVATE);
String userLoginStatus = preferences.getString("userLoginStatus", "no");
if (userLoginStatus.equals("no")) {
Intent intent = new Intent(SplashScreen.this,
LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
SplashScreen.this.finish();
} else {
Intent intent = new Intent(SplashScreen.this,
MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
SplashScreen.this.finish();
}
}
}
JSONParser class :
public class JSONParser {
//----------For Register
public JSONObject makeRegisterJson(String name, String email, String password, long phone) throws JSONException {
JSONObject object = new JSONObject();
object.put("name", name);
object.put("email", email);
object.put("password", password);
object.put("phone", phone);
// if its in array------
/*JSONObject finalObject=new JSONObject();
finalObject.put("request",object);
return finalObject;*/
return object;
}
//--------For Login--------------------------------------------------------
public JSONObject makeLoginJson(String Name, String password) throws JSONException {
JSONObject object = new JSONObject();
object.put("userName", Name);
object.put("password", password);
/*JSONObject finalObject=new JSONObject();
finalObject.put("request",object);
return finalObject;*/
return object;
}
}
ServerRequests class :
// ---------------- for register------------------------------------------------------------------------------
public void setRegistereponse(Registereponse registereponse) {
this.registereponse = registereponse;
}
private Registereponse registereponse;
public interface Registereponse {
void onRegsiterReposne(JSONObject object);
}
public void register(JSONObject jsonObject) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, Services.REGISTER_URL, jsonObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.e("Json response", "" + response);
boolean b = response.getBoolean("success");
if (registereponse != null) {
registereponse.onRegsiterReposne(response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error ", "" + error);
}
}
);
queue.add(jsonObjectRequest);
}
// --------------For Login ---------------------------------------------------------------------------
public void setLoginreponse(Loginreponse loginreponse) {
this.loginreponse = loginreponse;
}
private Loginreponse loginreponse;
public interface Loginreponse {
void onLoginReposne(JSONObject object);
}
public void login(JSONObject jsonObject) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, Services.LOGIN_URL, jsonObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.e("Json response", "" + response);
boolean b = response.getBoolean("success");
if (loginreponse != null) {
loginreponse.onLoginReposne(response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error ", "" + error);
}
}
);
queue.add(jsonObjectRequest);
}
UserSession class :
public class UserSession {
// Shared Preferences reference
SharedPreferences pref;
// Editor reference for Shared preferences
Editor editor;
// Context
Context _context;
// Shared preferences mode
int PRIVATE_MODE = 0;
// Shared preferences file name
public static final String PREFER_NAME = "Reg";
// All Shared Preferences Keys
public static final String IS_USER_LOGIN = "IsUserLoggedIn";
// User name (make variable public to access from outside)
public static final String KEY_NAME = "Name";
// Email address (make variable public to access from outside)
public static final String KEY_EMAIL = "Email";
// password
public static final String KEY_PASSWORD = "Password";
public static final String KEY_PHONE = "PhoneNumber";
public static final String KEY_QUALIFICATION = "Qualification";
// Constructor
public UserSession(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREFER_NAME, PRIVATE_MODE);
editor = pref.edit();
}
//Create login session
public void createUserLoginSession(String uEmail, String uPassword) {
// Storing login value as TRUE
editor.putBoolean(IS_USER_LOGIN, true);
// Storing name in preferences
editor.putString(KEY_EMAIL, uEmail);
// Storing email in preferences
editor.putString(KEY_PASSWORD, uPassword);
// commit changes
editor.commit();
}
/**
* Check login method will check user login status
* If false it will redirect user to login page
* Else do anything
*/
public boolean checkLogin() {
// Check login status
if (!this.isUserLoggedIn()) {
// user is not logged in redirect him to Login Activity
Intent i = new Intent(_context, LoginActivity.class);
// Closing all the Activities from stack
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);
return true;
}
return false;
}
/**
* Get stored session data
*/
public HashMap<String, String> getUserDetails() {
//Use hashmap to store user credentials
HashMap<String, String> user = new HashMap<String, String>();
// user name
user.put(KEY_NAME, pref.getString(KEY_NAME, null));
// user email id
user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));
user.put(KEY_PASSWORD, pref.getString(KEY_PASSWORD, null));
user.put(KEY_PHONE, pref.getString(KEY_PHONE, null));
user.put(KEY_QUALIFICATION, pref.getString(KEY_QUALIFICATION, null));
// return user
return user;
}
/**
* Clear session details
*/
public void logoutUser() {
// Clearing all user data from Shared Preferences
editor.clear();
editor.commit();
// After logout redirect user to MainActivity
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);
}
// Check for login
public boolean isUserLoggedIn() {
return pref.getBoolean(IS_USER_LOGIN, false);
}
}
At the time of login successfull put this code:
prefs = getSharedPreferences("logindetail", 0);
SharedPreferences.Editor edit = prefs.edit();
edit.putString("userLoginStatus", "yes");
edit.commit();
At the time of logout use this:
prefs = getSharedPreferences("logindetail", 0);
SharedPreferences.Editor edit = prefs.edit();
edit.clear();
edit.commit();
And at the time of checking if user is login or not use below code:
Loginprefs = getApplicationContext().getSharedPreferences("logindetail", 0);
userLoginStatus = Loginprefs.getString("userLoginStatus", null);
if(userLoginStatus.tostring().equals("yes")){
//the user is login
}else{
//user is logout
}
Hope this helps you

How to: store image in sdcard, store and get imagepath in sharedpreferences for Profile Pic

Profile pic can be selected and set for a while but what we generally want (first object) is when user re-launch that page, there should be an image previously set by the user and if user has not set that image, there should be default image. I have used sharedpreferences for text views but it is said that for the image views, generally it is good practice to store the selected image first in sdcard, then get that Uri, make it string and then use it for sharedpreferences. i dont know if it can be done through onPause and onResume as well! if it is so, then which way should be prefer? and How to do that? Another thing is (Second object) i have an activity namely user profile where i want to inflate the data (Here, profile pic selected by the user) from edit profile activity. Here is the same case as of edit profile where if the user have not set custom profile pic then there should be default pic. Following is my edit profile activity:
public class EditUserProfile extends AppCompatActivity {
private CoordinatorLayout coordinatorLayout;
public static final String Uimage = "Uimage";
public static final String Name = "nameKey";
public static final String UContact = "UContact";
public static final String Uemail = "Uemail";
private TextInputLayout inputLayoutName, inputLayoutEmail, inputLayoutContact;
private EditText usernameTextView, userEmailTextView, userContactTextView;
private ImageView userImageView;
SharedPreferences sharedpreferences;
private int PICK_IMAGE_REQUEST = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_user_profile);
Toolbar userProfileToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(userProfileToolbar);
inputLayoutName = (TextInputLayout) findViewById(R.id.input_layout_username);
inputLayoutEmail = (TextInputLayout) findViewById(R.id.input_layout_useremail);
inputLayoutContact = (TextInputLayout) findViewById(R.id.input_layout_usercontact);
userImageView = (ImageView) findViewById(R.id.userImage );
usernameTextView = (EditText) findViewById(R.id.username);
userContactTextView = (EditText) findViewById(R.id.usercontact);
userEmailTextView = (EditText) findViewById(R.id.useremail);
Button btnSave = (Button) findViewById(R.id.action_save);
sharedpreferences = getSharedPreferences(Uimage, Context.MODE_PRIVATE);
sharedpreferences = getSharedPreferences(Name, Context.MODE_PRIVATE);
sharedpreferences = getSharedPreferences(UContact, Context.MODE_PRIVATE);
sharedpreferences = getSharedPreferences(Uemail, Context.MODE_PRIVATE);
if (sharedpreferences.contains(Name)) {
usernameTextView.setText(sharedpreferences.getString(Name, ""));
}
if (sharedpreferences.contains(UContact)) {
userContactTextView.setText(sharedpreferences.getString(UContact, ""));
}
if (sharedpreferences.contains(Uemail)) {
userEmailTextView.setText(sharedpreferences.getString(Uemail, ""));
}
usernameTextView.addTextChangedListener(new MyTextWatcher(usernameTextView));
userEmailTextView.addTextChangedListener(new MyTextWatcher(userEmailTextView));
userContactTextView.addTextChangedListener(new MyTextWatcher(userContactTextView));
coordinatorLayout = (CoordinatorLayout) findViewById(R.id
.coordinatorLayout);
final ImageButton button = (ImageButton) findViewById(R.id.editImage);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Intent intent = new Intent();
// Show only images, no videos or anything else
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
// Always show the chooser (if there are multiple options available)
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri uri = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
// Log.d(TAG, String.valueOf(bitmap));
userImageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Validating form
*/
private boolean submitForm() {
if (!validateName()) {
return false;
}
if (!validateContact()) {
return false;
}
if (!validateEmail()) {
return false;
}
Snackbar snackbar = Snackbar
.make(coordinatorLayout, "Saved!", Snackbar.LENGTH_LONG);
snackbar.show();
return true;
}
private boolean validateName() {
if (usernameTextView.getText().toString().trim().isEmpty()) {
inputLayoutName.setError(getString(R.string.err_msg_name));
requestFocus(usernameTextView);
return false;
} else {
inputLayoutName.setError(null);
}
return true;
}
private boolean validateEmail() {
String email = userEmailTextView.getText().toString().trim();
if (email.isEmpty() || !isValidEmail(email)) {
inputLayoutEmail.setError(getString(R.string.err_msg_email));
requestFocus(userEmailTextView);
return false;
} else {
inputLayoutEmail.setError(null);
}
return true;
}
private boolean validateContact() {
if (userContactTextView.getText().toString().trim().isEmpty()) {
inputLayoutContact.setError(getString(R.string.err_msg_contact));
requestFocus(userContactTextView);
return false;
} else {
inputLayoutContact.setError(null);
}
return true;
}
private static boolean isValidEmail(String email) {
return !TextUtils.isEmpty(email) && android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
private void requestFocus(View view) {
if (view.requestFocus()) {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}
private class MyTextWatcher implements TextWatcher {
private View view;
private MyTextWatcher(View view) {
this.view = view;
}
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
public void afterTextChanged(Editable editable) {
switch (view.getId()) {
case R.id.username:
validateName();
break;
case R.id.useremail:
validateEmail();
break;
case R.id.usercontact:
validateContact();
break;
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.editprofile_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_save:
if (!submitForm()){
return false;
}
TextView usernameTextView = (TextView) findViewById(R.id.username);
String usernameString = usernameTextView.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, usernameString);
editor.apply();
TextView ucontactTV = (TextView) findViewById(R.id.usercontact);
String uContactS = ucontactTV.getText().toString();
editor.putString(UContact, uContactS);
editor.apply();
TextView uEmailTV = (TextView) findViewById(R.id.useremail);
String uEmailS = uEmailTV.getText().toString();
editor.putString(Uemail, uEmailS);
editor.apply();
Snackbar snackbar = Snackbar
.make(coordinatorLayout, "Saved!", Snackbar.LENGTH_LONG);
snackbar.show();
Intent userProfileIntent = new Intent(EditUserProfile.this, UserProfile.class);
userProfileIntent.putExtra(Name, usernameString);
userProfileIntent.putExtra(UContact, uContactS);
userProfileIntent.putExtra(Uemail, uEmailS);
setResult(RESULT_OK, userProfileIntent);
finish();
}
return true;
}
}
Following is the user profile activity where i want to inflate default or custom profile pic from edit profile activity as same as i am able to inflate rest of text views:
public class UserProfile extends AppCompatActivity {
SharedPreferences sharedpreferences;
public static final String Uimage = "Uimage";
public static final String Name = "nameKey";
public static final String UContact = "UContact";
public static final String Uemail = "Uemail";
public static final int Edit_Profile = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile);
Toolbar userProfileToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(userProfileToolbar);
sharedpreferences = getSharedPreferences(Uimage, MODE_PRIVATE);
sharedpreferences = getSharedPreferences(Name, MODE_PRIVATE);
sharedpreferences = getSharedPreferences(UContact, MODE_PRIVATE);
sharedpreferences = getSharedPreferences(Uemail, MODE_PRIVATE);
displayMessage(sharedpreferences.getString(Name, ""));
displayUContact(sharedpreferences.getString(UContact, ""));
displayUEmail(sharedpreferences.getString(Uemail, ""));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.userprofile_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_editProfile:
Intent userProfileIntent = new Intent(UserProfile.this, EditUserProfile.class);
startActivityForResult(userProfileIntent, Edit_Profile);
return true;
}
return true;
}
// Call Back method to get the Message form other Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case Edit_Profile:
if (resultCode == RESULT_OK) {
String name = data.getStringExtra(Name);
String Result_UContact = data.getStringExtra(UContact);
String Result_UEmail = data.getStringExtra(Uemail);
displayMessage(name);
displayUContact(Result_UContact);
displayUEmail(Result_UEmail);
}
break;
}
}
public void displayMessage(String message) {
TextView usernameTextView = (TextView) findViewById(R.id.importProfile);
usernameTextView.setText(message);
}
public void displayUContact(String contact) {
TextView userContactTextView = (TextView) findViewById(R.id.importContact);
userContactTextView.setText(contact);
}
public void displayUEmail(String email) {
TextView userEmailTextView = (TextView) findViewById(R.id.importEmail);
userEmailTextView.setText(email);
}
}
Please consider that i have no experience in programming, coding or android development and i have just started to learn that!
You are right. You can store the image in your sd card and use the uri to load the image subsequently.
You can consider to save the image uri in the stored preference. With that you will just need to handle two cases.
In your onCreate() method
- Check if the image uri is valid (image exist)
- If it does, load it and make it the display image
- If it is missing, load the default image
* Alternatively, you can set the default image as the image for the imageview
Whenever the user updates the image
- Store the image into the sd card
- Update your shared preference
As such, you should not need to handle these in your onPause() and onResume() methods.
Hope it helps!
I have no much timer to write the entire answer, but here is how to store some Strings into the application shared Preferences:
1. storing some strings, it makes sense to store them when your "save"-button is clicked:
// assume a,b,c are strings with the information from ur edittexts to be saved:
String a,b,c;
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sp.edit();
editor.putString("namekey",a);
editor.putString("UContact", b);
editor.putString("UEmail", c);
editor.commit();
now these 3 things are saved.
2. loading these values (e.g. in ur onCreate() method after setting the content):
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
// check if the namevalues "namekey", "UContact", "UEmail" have values saved in the sharedPreferences. If not, load defaultvalue
String user_name = sp.getString("namekey", "no name entered yet");
String user_email = sp.getString("UEmail", "no email entered yet");
String user_contact = sp.getString("UContact", "no Contact entered yet");
displayMessage(user_name);
displayUContact(user_contact);
displayUEmail(user_email);
Loading a value from the sharedPreferences always needs a 2nd parameter, which will be the result when there is nothing saved for this key. For example, if your application is started for the first time, and the user did not have entered anything in the edittexts, then "no name entered yet", and so on are loaded from the sharedPreferences.
and.. thats it so far.
Why did i not provide information on how to store a bitmap in the sharedPreferences?
- sharedPreferences can only store basic Types such as Float, Integer, String, Boolean
- You could save the image into the sd card, but remember: not every device is using a sd card. If your application uses the camera-intent instead, your foto is already saved in the gallery automatically. You can store this path as a String in the sharedPrefs.
We can have method to retrieve the Uri for selected image as below:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri uri = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
// CALL THIS METHOD TO GET THE ACTUAL PATH
File finalFile = new File(getRealPathFromURI(uri));
outputFileUri = Uri.fromFile(finalFile);
stringUri = outputFileUri.toString();
// Log.d(TAG, String.valueOf(bitmap));
userImageView.setImageBitmap(bitmap);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Uimage, stringUri);
editor.apply();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String getRealPathFromURI(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
So now we have String that represents or has been stored with value of Uri for our selected image.
Next is to use this string for sharedpreferences as below:
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Uimage, stringUri);
editor.apply();
Uimage is the key and it has string value stringUri with it! Each time user change the profile pic, we will have updated Uimage and associated stringUri at the same time.
Now, in onCreate method, we will check if there is sharedpreferences available with this value and if so, then we want to display the selected image. It should be noted here that sharedpreferences is used to save and keep the primitive data across re-launching of the app. Editor.putString is used to store some value and sharedpreferences.getString is used to read that value.
if (sharedpreferences.contains(Uimage)){
String imagepath = sharedpreferences.getString(Uimage, "");
uriString = Uri.parse(imagepath);
userImageView.setImageURI(uriString);
}
uriString is Uri!
And it worked!
Next is to send this profile pic to the user profile activity. We will use intent to send the selected pic to user profile activity and sharedpreferences in onCreate method of user profile activity to save and keep that pic there across re-launch as below:
1. Sending pic to the user profile activity using intent in edit profile activity as below:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_save:
Snackbar snackbar = Snackbar
.make(coordinatorLayout, "Saved!", Snackbar.LENGTH_LONG);
snackbar.show();
Intent userProfileIntent = new Intent(EditUserProfile.this, UserProfile.class);
if (sharedpreferences.contains(stringUri)){
userProfileIntent.putExtra(Uimage, stringUri);
}
setResult(RESULT_OK, userProfileIntent);
finish();
}
return true;
}
….and read and handle this intent at user profile activity as below:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case Edit_Profile:
if (resultCode == RESULT_OK) {
String imageIntent = data.getStringExtra(Uimage);
displayUimage(imageIntent);
}
break;
}
}
Where:
public void displayUimage (String imageString){
ImageView importImage = (ImageView) findViewById(R.id.importImage);
imageString = sharedpreferences.getString(Uimage, "");
uriString = Uri.parse(imageString);
importImage.setImageURI(uriString);
}
Intent is used to get the pic from edit profile activity to user profile activity. If we press back or exit the app and re-launch it, user profile activity will lose that pic. In order to save and keep that pic there across re-launching of app, we need to use sharedpreferences there.
Save and Keep that pic there at user profile activity using sharedpreferences as below:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile);
Toolbar userProfileToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(userProfileToolbar);
importImage = (ImageView) findViewById(R.id.importImage);
importImage.setImageResource(R.drawable.defaultprofilepic);
sharedpreferences = getSharedPreferences(Uimage, MODE_PRIVATE);
if (sharedpreferences.contains(Uimage)){
String imagepath = sharedpreferences.getString(Uimage, "");
uriString = Uri.parse(imagepath);
importImage.setImageURI(uriString);
}
}
We first have initialized our importImage with the default one but then we check if there is sharedpreferences with special key is available.
That simply means, if the sharedpreferences contains Uimage (which is possible only if the user have changed the profile pic and the Uimage will be always updated as soon as user change the profile pic) then we will get Uri for that image and set it to importImage so that we will have same profile pic as user have selected at edit profile activity.
Below is the complete Edit profile activity:
public class EditUserProfile extends AppCompatActivity {
private CoordinatorLayout coordinatorLayout;
public static final String Uimage = "Uimagepath";
public static final String Name = "nameKey";
public static final String UContact = "UContact";
public static final String Uemail = "Uemail";
private TextInputLayout inputLayoutName, inputLayoutEmail, inputLayoutContact;
private EditText usernameTextView, userEmailTextView, userContactTextView;
private ImageView userImageView;
SharedPreferences sharedpreferences;
private int PICK_IMAGE_REQUEST = 1;
String stringUri;
Uri outputFileUri;
Uri uriString;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_user_profile);
Toolbar userProfileToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(userProfileToolbar);
inputLayoutName = (TextInputLayout) findViewById(R.id.input_layout_username);
inputLayoutEmail = (TextInputLayout) findViewById(R.id.input_layout_useremail);
inputLayoutContact = (TextInputLayout) findViewById(R.id.input_layout_usercontact);
userImageView = (ImageView) findViewById(R.id.userImage );
usernameTextView = (EditText) findViewById(R.id.username);
userContactTextView = (EditText) findViewById(R.id.usercontact);
userEmailTextView = (EditText) findViewById(R.id.useremail);
Button btnSave = (Button) findViewById(R.id.action_save);
sharedpreferences = getSharedPreferences(Uimage, Context.MODE_PRIVATE);
sharedpreferences = getSharedPreferences(Name, Context.MODE_PRIVATE);
sharedpreferences = getSharedPreferences(UContact, Context.MODE_PRIVATE);
sharedpreferences = getSharedPreferences(Uemail, Context.MODE_PRIVATE);
if (sharedpreferences.contains(Uimage)){
String imagepath = sharedpreferences.getString(Uimage, "");
uriString = Uri.parse(imagepath);
userImageView.setImageURI(uriString);
}
if (sharedpreferences.contains(Name)) {
usernameTextView.setText(sharedpreferences.getString(Name, ""));
}
if (sharedpreferences.contains(UContact)) {
userContactTextView.setText(sharedpreferences.getString(UContact, ""));
}
if (sharedpreferences.contains(Uemail)) {
userEmailTextView.setText(sharedpreferences.getString(Uemail, ""));
}
usernameTextView.addTextChangedListener(new MyTextWatcher(usernameTextView));
userEmailTextView.addTextChangedListener(new MyTextWatcher(userEmailTextView));
userContactTextView.addTextChangedListener(new MyTextWatcher(userContactTextView));
coordinatorLayout = (CoordinatorLayout) findViewById(R.id
.coordinatorLayout);
final ImageButton button = (ImageButton) findViewById(R.id.editImage);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Intent intent = new Intent();
// Show only images, no videos or anything else
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
// Always show the chooser (if there are multiple options available)
startActivityForResult(Intent.createChooser(intent, "Select Pic from"), PICK_IMAGE_REQUEST);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri uri = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
// CALL THIS METHOD TO GET THE ACTUAL PATH
File finalFile = new File(getRealPathFromURI(uri));
outputFileUri = Uri.fromFile(finalFile);
stringUri = outputFileUri.toString();
// Log.d(TAG, String.valueOf(bitmap));
userImageView.setImageBitmap(bitmap);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Uimage, stringUri);
editor.apply();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String getRealPathFromURI(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
/**
* Validating form
*/
private boolean submitForm() {
if (!validateName()) {
return false;
}
if (!validateContact()) {
return false;
}
if (!validateEmail()) {
return false;
}
Snackbar snackbar = Snackbar
.make(coordinatorLayout, "Saved!", Snackbar.LENGTH_LONG);
snackbar.show();
return true;
}
private boolean validateName() {
if (usernameTextView.getText().toString().trim().isEmpty()) {
inputLayoutName.setError(getString(R.string.err_msg_name));
requestFocus(usernameTextView);
return false;
} else {
inputLayoutName.setError(null);
}
return true;
}
private boolean validateEmail() {
String email = userEmailTextView.getText().toString().trim();
if (email.isEmpty() || !isValidEmail(email)) {
inputLayoutEmail.setError(getString(R.string.err_msg_email));
requestFocus(userEmailTextView);
return false;
} else {
inputLayoutEmail.setError(null);
}
return true;
}
private boolean validateContact() {
if (userContactTextView.getText().toString().trim().isEmpty()) {
inputLayoutContact.setError(getString(R.string.err_msg_contact));
requestFocus(userContactTextView);
return false;
} else {
inputLayoutContact.setError(null);
}
return true;
}
private static boolean isValidEmail(String email) {
return !TextUtils.isEmpty(email) && android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
private void requestFocus(View view) {
if (view.requestFocus()) {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}
private class MyTextWatcher implements TextWatcher {
private View view;
private MyTextWatcher(View view) {
this.view = view;
}
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
public void afterTextChanged(Editable editable) {
switch (view.getId()) {
case R.id.username:
validateName();
break;
case R.id.useremail:
validateEmail();
break;
case R.id.usercontact:
validateContact();
break;
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.editprofile_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_save:
if (!submitForm()){
return false;
}
SharedPreferences.Editor editor = sharedpreferences.edit();
TextView usernameTextView = (TextView) findViewById(R.id.username);
String usernameString = usernameTextView.getText().toString();
editor.putString(Name, usernameString);
editor.apply();
TextView ucontactTV = (TextView) findViewById(R.id.usercontact);
String uContactS = ucontactTV.getText().toString();
editor.putString(UContact, uContactS);
editor.apply();
TextView uEmailTV = (TextView) findViewById(R.id.useremail);
String uEmailS = uEmailTV.getText().toString();
editor.putString(Uemail, uEmailS);
editor.apply();
Snackbar snackbar = Snackbar
.make(coordinatorLayout, "Saved!", Snackbar.LENGTH_LONG);
snackbar.show();
Intent userProfileIntent = new Intent(EditUserProfile.this, UserProfile.class);
userProfileIntent.putExtra(Name, usernameString);
userProfileIntent.putExtra(UContact, uContactS);
userProfileIntent.putExtra(Uemail, uEmailS);
if (sharedpreferences.contains(stringUri)){
userProfileIntent.putExtra(Uimage, stringUri);
}
setResult(RESULT_OK, userProfileIntent);
finish();
}
return true;
}
}
Below is the complete User Profile Activity that shows saved profile:
public class UserProfile extends AppCompatActivity {
SharedPreferences sharedpreferences;
public static final String Uimage = "Uimagepath";
public static final String Name = "nameKey";
public static final String UContact = "UContact";
public static final String Uemail = "Uemail";
ImageView importImage;
Uri uriString;
public static final int Edit_Profile = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile);
Toolbar userProfileToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(userProfileToolbar);
importImage = (ImageView) findViewById(R.id.importImage);
importImage.setImageResource(R.drawable.defaultprofilepic);
sharedpreferences = getSharedPreferences(Uimage, MODE_PRIVATE);
sharedpreferences = getSharedPreferences(Name, MODE_PRIVATE);
sharedpreferences = getSharedPreferences(UContact, MODE_PRIVATE);
sharedpreferences = getSharedPreferences(Uemail, MODE_PRIVATE);
if (sharedpreferences.contains(Uimage)){
String imagepath = sharedpreferences.getString(Uimage, "");
uriString = Uri.parse(imagepath);
importImage.setImageURI(uriString);
}
displayMessage(sharedpreferences.getString(Name, ""));
displayUContact(sharedpreferences.getString(UContact, ""));
displayUEmail(sharedpreferences.getString(Uemail, ""));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.userprofile_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_editProfile:
Intent userProfileIntent = new Intent(UserProfile.this, EditUserProfile.class);
startActivityForResult(userProfileIntent, Edit_Profile);
return true;
case R.id.action_dos:
Intent coffeeIntent = new Intent(UserProfile.this, Dos.class);
UserProfile.this.startActivity(coffeeIntent);
return true;
case R.id.action_13:
Intent teaIntent = new Intent(UserProfile.this, thirteen.class);
UserProfile.this.startActivity(teaIntent);
return true;
}
return true;
}
// Call Back method to get the Message form other Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case Edit_Profile:
if (resultCode == RESULT_OK) {
String imageIntent = data.getStringExtra(Uimage);
String name = data.getStringExtra(Name);
String Result_UContact = data.getStringExtra(UContact);
String Result_UEmail = data.getStringExtra(Uemail);
displayUimage(imageIntent);
displayMessage(name);
displayUContact(Result_UContact);
displayUEmail(Result_UEmail);
}
break;
}
}
public void displayMessage(String message) {
TextView usernameTextView = (TextView) findViewById(R.id.importProfile);
usernameTextView.setText(message);
}
public void displayUContact(String contact) {
TextView userContactTextView = (TextView) findViewById(R.id.importContact);
userContactTextView.setText(contact);
}
public void displayUEmail(String email) {
TextView userEmailTextView = (TextView) findViewById(R.id.importEmail);
userEmailTextView.setText(email);
}
public void displayUimage (String imageString){
ImageView importImage = (ImageView) findViewById(R.id.importImage);
imageString = sharedpreferences.getString(Uimage, "");
uriString = Uri.parse(imageString);
importImage.setImageURI(uriString);
}
}
Hope this helps someone!

How to use SharedPreferences to change view visibility in login and logout

How to create SharedPreferences with set visibility in login if the user is successfully login the button will be logout and the login will be gone
public class Login extends ActionBarActivity implements View.OnClickListener{
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
private static String url_check_login = "";
private static final String TAG_SUCCESS = "success";
Context cont=this;
EditText uname, pword;
Boolean nega = false;
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_user);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
uname = (EditText) findViewById(R.id.uname);
pword = (EditText) findViewById(R.id.pword);
Button login = (Button)findViewById(R.id.btnLogin);
login.setOnClickListener(this);
Button register = (Button)findViewById(R.id.btnRegister);
register.setOnClickListener(this);
}
#Override
public void onClick(View v)
{
final int id = v.getId();
switch (id) {
case R.id.btnLogin:
new SubmitLogin().execute();
break;
case R.id.btnRegister:
Intent i = new Intent (this, Registration.class);
startActivity(i);
finish();
break;
// even more buttons here
}
}
class SubmitLogin extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Logging In ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", uname.getText().toString()));
params.add(new BasicNameValuePair("pass", pword.getText().toString()));
JSONObject json = jsonParser.makeHttpRequest(url_check_login, "POST", params);
Log.d("Create Response", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
nega = false;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = prefs.edit();
editor.putString("username", uname.getText().toString());
editor.commit();
Intent gotoLogs = new Intent(cont, MainActivity.class);
startActivity(gotoLogs);
finish();
} else {
nega = true;
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
if (nega) {
new AlertDialog.Builder(cont)
.setTitle("Login Failed")
.setMessage("Wrong Username or Password")
.setNegativeButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
//Close current activity
startActivity(new Intent(this,MainActivity.class));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
To place info into SharedPreferences you should write following:
SharedPreferences sp = getSharedPreferences(PREFERNCES_FILE, MODE_PRIVATE);
sp.edit().putString(PREFERENCES_LOGIN, login).apply();
Variables PREFERNCES_FILE and PREFERENCES_LOGIN should be defined as String:
public static final String PREFERNCES_FILE = "my_preferences_file";
public static final String PREFERENCES_LOGIN = "login";
On logout there should be:
sp.edit().remove(PREFERENCES_LOGIN).apply();
Then to check if there is allready some info call:
boolean isLogged = sp.contains(PREFERENCES_LOGIN);
Then just set needed visibility:
login.setVisibility(isLogged ? View.GONE : View.VISIBLE);
UPDATE
Ok, here is example. This code should be in onCreate:
SharedPreferences sp = getSharedPreferences(PREFERNCES_FILE, MODE_PRIVATE);
boolean isLogged = sp.contains(PREFERENCES_LOGIN);
Button login = (Button)findViewById(R.id.btnLogin);
login.setVisibility(isLogged ? View.GONE : View.VISIBLE);
login.setOnClickListener(this);
Button logout = (Button)findViewById(R.id.btnLogout);
logout.setVisibility(isLogged ? View.VISIBLE : View.GONE);
logout.setOnClickListener(this);
And there should be button in your login_user xml with btnLogout id.
In onClick should be:
#Override
public void onClick(View v)
{
final int id = v.getId();
switch (id) {
case R.id.btnLogin:
SharedPreferences sp = getSharedPreferences(PREFERNCES_FILE, MODE_PRIVATE);
sp.edit().putString(PREFERENCES_LOGIN, login).apply();
findViewById(R.id.btnLogin).setVisibility(View.GONE);
findViewById(R.id.btnLogout).setVisibility(View.VISIBLE);
//another actions after login
break;
case R.id.btnLogout:
SharedPreferences sp = getSharedPreferences(PREFERNCES_FILE, MODE_PRIVATE);
sp.edit().remove(PREFERENCES_LOGIN).apply();
findViewById(R.id.btnLogin).setVisibility(View.VISIBLE);
findViewById(R.id.btnLogout).setVisibility(View.GONE);
//another actions after logout
break;
// even more buttons here
}
}
In login variable should be login data - I don't know where you should get it.

Issues with implementing the login using shared preference

I have mentioned my complete code for the login and logout process to my application. Sometimes this code works but sometimes it just allows me to go to menu activity even without login. FYI: this code really worked earlier once i wanted to implement the remember me option, then only all these issues came up. can anyone check this and find me my issue or suggest me if u got any proper code for this process. when i logout and and open the application sometimes i can see the menu.
I have used shared preference and not using sessions for login and logout. is it correct. Im bit confused i would really appreciate any help. thanx in advance.
login code
public class LoginActivity extends Activity {
ProgressDialog prgDialog;
EditText emailET;
EditText pwdET;
String email;
String password;
Button button;
public static String PREFS_NAME = "mypre";
public static String PREF_EMAIL = "email";
public static String PREF_PASSWORD = "password";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_login);
final Button button = (Button) findViewById(R.id.btlogin);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
String email = emailET.getText().toString();
String password = pwdET.getText().toString();
if (Utility.isNotNull(email) && Utility.isNotNull(password)) {
if (Utility.validate(email)) {
if (emailET.getText().toString().equals(email)
&& pwdET.getText().toString()
.equals(password)) {
CheckBox ch = (CheckBox) findViewById(R.id.ch_rememberme);
if (ch.isChecked())
rememberMe(email, password);
}
new LoginAsyncTask(LoginActivity.this).execute(
email, password);
Toast.makeText(getApplicationContext(),
"Login process started...",
Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getApplicationContext(),
"Login error, invalid email",
Toast.LENGTH_LONG).show();
}
}
else {
Toast.makeText(
getApplicationContext(),
"Login error, don't leave any field blank",
Toast.LENGTH_LONG).show();
}
} catch (Exception ex) {
}
}
});
final TextView textView = (TextView) findViewById(R.id.link_to_landing);
textView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(),
LandingActivity.class);
startActivity(i);
finish();
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
}
});
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
Intent i = new Intent(getApplicationContext(),
LandingActivity.class);
startActivity(i);
overridePendingTransition(R.anim.slide_in_left,
R.anim.slide_out_right);
finish();
return false;
}
return super.onKeyDown(keyCode, event);
}
public void onStart() {
super.onStart();
// read email and password from SharedPreferences
getUser();
}
public void getUser() {
SharedPreferences pref = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
String email = pref.getString(PREF_EMAIL, null);
String password = pref.getString(PREF_PASSWORD, null);
if (email != null || password != null) {
// directly show logout form
showLogout(email);
}
}
public void rememberMe(String user, String password) {
// save email and password in SharedPreferences
getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit()
.putString(PREF_EMAIL, user).putString(PREF_PASSWORD, password)
.commit();
}
public void showLogout(String email) {
// display log out activity
Intent intent = new Intent(this, ActivityMenu.class);
intent.putExtra("user", email);
startActivity(intent);
overridePendingTransition(R.anim.slide_in_left,
R.anim.slide_out_right);
}
}
logout code
final RelativeLayout relativeLayout3 = (RelativeLayout) rootView
.findViewById(R.id.logoutlistview);
relativeLayout3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
SharedPreferences pref = getActivity().getSharedPreferences(
PREFS_NAME, Context.MODE_PRIVATE);
String email = pref.getString(PREF_EMAIL, null);
String password = pref.getString(PREF_PASSWORD, null);
if (email != null || password != null ) {
Editor editor = pref.edit();
editor.clear();
editor.commit();
email = "";
password = "";
firstname = "";
lastname = "";
// show login form
Intent intent = new Intent(getActivity(),
LActivity.class);
startActivity(intent);
intent.addFlags(IntentCompat.FLAG_ACTIVITY_CLEAR_TASK
| Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
else {
}
}
});
use this method to create a sharedPreference and then access it with this same name from any where in any activity within the same app
SharedPreference sp;
sp = getApplicationContext().getSharedPreferences(My_PREFERENCE,
context.MODE_PRIVATE);
Editor e = sp.edit();
e.put(key,value);
e.commit();
and when getting the same sharedPreference in another activity use this method
SharedPreference sp;
sp = getApplicationContext().getSharedPreferences(My_PREFERENCE,
context.MODE_PRIVATE);
sp.get(key,value);
Please check the below link which might help you.
http://androidapplicationdeveloper.weebly.com/login-and-logout-useing-sharedprefrences.html
In your code you have didn't set values of sharedpreference to blank while logout.
Hope it will help you.

Android ClassCastException after reading from SharedPreferences

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

Categories

Resources