Android Sharedpreferences Updating Only After App Restart - android

Good Day,
I have read almost all posts in regards with Sharedpreferences on Stackoverflow but none of them seems to answer my question.
I store a Token code in Sharedpreferences after getting it from JSON, when I toast the values all is correct, then I save the string value to Sharedpreferences with the below code:
private String mypreference = "AppData.xml";
private String KeySave = "KeySave";
sharedpreferences = getSharedPreferences(mypreference, Context.MODE_PRIVATE);
String Token = json.optString("TokenFomJSON");
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(KeySave, Token);
editor.commit();
When I look at the XML I can see the saved value, the problem is when I convert the Sharedpreferences again back to String to be used with the below code:
String KeyCaptured = sharedpreferences.getString(KeySave, "");
Then it returns the previous saved key and not the updated one from JSON.
When I restart the application, then the correct key is displayed.
What I have done testing this far.
Changing .commit() to .apply()
I 1st call the JSON via the code below:
GetKey();
private void GetKey() {
JsonObjectRequest jsonObjReq = new JsonObjectRequest(
Request.Method.POST, url, js,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Token", response.toString());
try {
JSONObject json = new JSONObject(response.toString());
String Token = json.optString("TokenFomJSON");
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(KeySave , Token);
editor.commit();
// Toast.makeText(LoginActivity.this, Token, Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Token", "Error: " + error.getMessage());
}
})
}
Then I call it with the below code:
String KeyCaptured = sharedpreferences.getString(KeySave, "");
Other than the above that I have tested, there is not many other suggestions to try, anyone else got some suggestions I could try?
Thank You,
Kind Regards

I have figured it out, I needed to give a delay of 2 sec between the JSON and the request. All working now

Related

Login using Json with shared Preferences

Login using JSON with shared Preferences When user Enter their Phone Number then user got success from API and go to new activity and after resume app, users state will log in
When user Enter their Phone Number then user got success from API and go to new activity and after resume app, users state will log in
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView3);
usr_number = findViewById(R.id.usr_pass);
go = findViewById(R.id.button);
signup = findViewById(R.id.signup_signup);
go.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getjsondata();
String hhh = usr_number.getText().toString();
url = "http://readnow.flatdeal4u.com/Api/Register.aspx?mobile=" + hhh + "&choice=2";
//Toast.makeText(MainActivity.this, ""+hhh, Toast.LENGTH_SHORT).show();
if (usr_number.getText().toString().isEmpty()) {
usr_number.setError("Enter Phone Number");
Toast.makeText(MainActivity.this, "Enter Details", Toast.LENGTH_SHORT).show();
} else {
if (usr_number.getText().toString().equals("" + hhh)) {
Intent intent = new Intent(MainActivity.this, select_your_exams.class);
startActivity(intent);
pref = PreferenceManager
.getDefaultSharedPreferences(MainActivity.this);
pref.getString("mobilenumber", hhh);
pref.getString("nameofuser", "");
}
}
}
});
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Signup.class);
startActivity(intent);
}
});
}
Here are my JSON method codes:
public void get JSON data) {
final StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener < String > () {
#Override
public void onResponse(String response) {
try {
JSONObject jobj = new JSONObject(response);
JSONArray array = jobj.getJSONArray("userInfos");
//Toast.makeText(MainActivity.this, "data found"+array, Toast.LENGTH_LONG).show();
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
final Phn_modal mo = new Phn_modal();
final String mobile = obj.getString("mobileNumber");
final String name = obj.getString("fullName");
final String email = obj.getString("emailId");
Toast.makeText(MainActivity.this, "Welcome You-" + name, Toast.LENGTH_LONG).show();
mo.setMobile(mobile);
mo.setName(name);
mo.setEmailId(email);
mo.getMobile(mobile);
mo.getMobile(name);
editor.putString("mobilenumber", mobile);
editor.putString("nameofuser", name);
editor.apply();
editor.commit();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "" + error.toString(), Toast.LENGTH_SHORT).show();
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(request);
}
i think your question is , you login first time, and next time you again visit application that time directly go to the activity withouth asking login,
then you can try this.
public void storeString(SharedPreferences sharedPreferences, String key, String value) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
above function is used to store the specific value in our shared prefrence, with given key.
Now when we hint the login button that time if login is success then store the login success value in our prefrence.
this one is usefull for again visit in your application
storeString(mPreferences, "Login_flag", "true");
-> Now, when we again visit application check the our prefrence is true or false.
if our prefrence is true then user already login, not required to login again
Check like this,
if(mPreferences.getString(PreferenceList.LOGIN_FLAG, "false").equals("true")){
//if alredy login then access this
}else{
//if not login then access this
}
if you want to create a login session in your app then you should create an preference class in your project and save data in that class and match the data where you want to use follow this answer to maintain the login session in your app:- Preventing users to login again after closing the app

Store email that are used to log in and show as suggestion on the email input during next Login - Android Application

I am trying to find a way to keep all the email used for login into the application in a device and show them as suggestion or autocomplete when ever a user tries to login in to the application.
I tried using shared preferences and store them into an ArrayList during the login. However each time I login, the email gets replaced with the latest login email instead of adding up.
Example: first i login with admin#admin.com and logout from the system. For next login the suggestion admin#admin.com shows up. However if now i login with employee#employee.com, the old stored email is replaced with the new one.
What I did to get this was first after login I stored the user email from the server response in a shared preference.
Next I put that data into an ArrayList
SharedPreferences getEmail = getSharedPreferences("userEmail", Context.MODE_PRIVATE);
String input_email = getEmail.getString("emp_email", "");
ArrayList<String> userList = new ArrayList<>();
userList.add(input_email);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, userList);
if (userList.size() > 0){
userEmail.setAdapter(adapter);
}
The above code in inside the onCreate method of the login activity. How can i do this.
I am guessing maybe this is not the correct way to remember email address for auto suggestion. If so then please point me to the right direction.
Thank you.
Update
Fetching response from the server in LoginActivity on successful login
public void getDataForId() {
SharedPreferences authToken = getSharedPreferences("authToken", Context.MODE_PRIVATE);
String token = authToken.getString("token", "");
apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
Call<UserResponse> call = apiInterface.getData("Bearer " + token);
call.enqueue(new Callback<UserResponse>() {
#Override
public void onResponse(Call<UserResponse> call, Response<UserResponse> response) {
if (response.isSuccessful()) {
String emp_email = response.body().getUser().getEmail();
ArrayList<String> listEmails = getFromPrefs(this);
if(listEmails == null){
listEmails = new ArrayList<>();
listEmails.add(emp_email);
}
saveToPrefs(this, listEmails);
/*Log.i("MainActivity", "onCreate: " + getFromPrefs(this).toString());
if(!listEmails.contains(emp_email)){
listEmails.add("b#b.b");
}
saveToPrefs(this, listEmails);
Log.i("MainActivity", "onCreate: " + getFromPrefs(this).toString());*/
} else {
}
}
#Override
public void onFailure(Call<UserResponse> call, Throwable t) {
}
});
}
Note that in am getting the email in the variable **emp_email* (assume the other two functions given by you are in the file). What I assume is that the commented out part (after the first email is saved), will start in the onCreate methode for me as after logging out.
there i get the pref data see it the new email matched the pref data and then store it. This is when it is getting replaced.
Try this.
I have edited your code
gist.github.com/adrielAd/b1fbc4f8665183eb195871d21cd415eb
// make listEmails global and also initialise this in onCreate so you get already saved emails when you come to this screen
ArrayList<String> listEmails;
public void getDataForId() {
SharedPreferences authToken = getSharedPreferences("authToken", Context.MODE_PRIVATE);
String token = authToken.getString("token", "");
apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
Call<UserResponse> call = apiInterface.getData("Bearer " + token);
call.enqueue(new Callback<UserResponse>() {
#Override
public void onResponse(Call<UserResponse> call, Response<UserResponse> response) {
if (response.isSuccessful()) {
String emp_email = response.body().getUser().getEmail();
listEmails = getFromPrefs(this);
if(listEmails == null){
listEmails = new ArrayList<>();
listEmails.add(emp_email);
}else{
if(!listEmails.contains(emp_email)){
listEmails.add(emp_email);
}
}
saveToPrefs(this, listEmails);
/*Log.i("MainActivity", "onCreate: " + getFromPrefs(this).toString());
if(!listEmails.contains(emp_email)){
listEmails.add("b#b.b");
}
saveToPrefs(this, listEmails);
Log.i("MainActivity", "onCreate: " + getFromPrefs(this).toString());*/
} else {
}
}
#Override
public void onFailure(Call<UserResponse> call, Throwable t) {
}
});
}
You can do like below.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<String> listEmails = getFromPrefs(this);
if(listEmails == null){
listEmails = new ArrayList<>();
listEmails.add("a#a.a");
}
saveToPrefs(this, listEmails);
Log.i("MainActivity", "onCreate: " + getFromPrefs(this).toString());
if(!listEmails.contains("b#b.b")){
listEmails.add("b#b.b");
}
saveToPrefs(this, listEmails);
Log.i("MainActivity", "onCreate: " + getFromPrefs(this).toString());
}
public static void saveToPrefs(Context context, ArrayList<String> listEmail) {
SharedPreferences appSharedPrefs = PreferenceManager
.getDefaultSharedPreferences(context.getApplicationContext());
SharedPreferences.Editor prefsEditor = appSharedPrefs.edit();
Gson gson = new Gson();
String list = gson.toJson(listEmail);
prefsEditor.putString("list", list);
prefsEditor.commit();
}
public static ArrayList<String> getFromPrefs(Context context) {
SharedPreferences appSharedPrefs = PreferenceManager
.getDefaultSharedPreferences(context.getApplicationContext());
Gson gson = new Gson();
String list = appSharedPrefs.getString("list", "");
ArrayList<String> listEmail = gson.fromJson(list, ArrayList.class);
return listEmail;
}
Here is the screenshot for logs

How do I implement Facebook auto-login on Android (Facebook SDK 4.0.0)?

I'm using Android Studio and Facebook SDK 4.0.0. Currently I'm able to successfully login. However, when I restart the app I have to sign in again. How can I implement auto-login so that the app automatically connects with my Facebook account when I start it? I've tried the 'Session' class but it won't work since it has been replaced by 'LoginManager'.
As per the facebook developers' site:
The Android and iOS SDKs don't currently support re-authentication.
Visit following link to know details:
https://developers.facebook.com/docs/facebook-login/reauthentication
first get username id using sharedPreference like this:
private SharedPreferences settings ;
private void graphRequest(AccessToken accessToken) {
settings = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences.Editor editor = settings.edit();
GraphRequest request = GraphRequest.newMeRequest(accessToken,
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse
response) {
try {
String email = "";
if (object.has("email")) {
email = object.getString("email");
}
String id = object.getString("id");
String name = object.getString("name");
String gender = object.getString("gender");
editor.putString("username", id);
editor.putString("name", name);
editor.putString("gender", gender);
editor.putString("email", email);
editor.apply();
startActivity(new Intent(mContext,
MainActivity.class));
finish();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender");
request.setParameters(parameters);
request.executeAsync();
}
Check condition OnResume() like this:
#Override
protected void onResume() {
settings =PreferenceManager.getDefaultSharedPreferences(this);
if (!TextUtils.isEmpty(settings.getString("username", ""))) {
startActivity(new Intent(mContext, MainActivity.class));
finish();
}
Profile profile = Profile.getCurrentProfile();
super.onResume();
}

unexpected response code 400 volley android

The code I've written is to connect my android studio to wamp server mysql. I try to retrieve login information from mysql to android. However it keep showing me unexpected response code 400. How should i change my code?
#Override
protected void onResume() {
super.onResume();
//In onresume fetching value from sharedpreference
SharedPreferences sharedPreferences =
getSharedPreferences(Config.SHARED_PREF_NAME,Context.MODE_PRIVATE);
//Fetching the boolean value form sharedpreferences
loggedIn = sharedPreferences.getBoolean(Config.LOGGEDIN_SHARED_PREF,
false);
//If we will get true
if(loggedIn){
//We will start the Profile Activity
Intent intent = new Intent(LoginActivity.this,
PofileActivity.class);
startActivity(intent);
}
}
private void login(){
//Getting values from edit texts
final String email = editTextEmail.getText().toString().trim();
final String password = editTextPassword.getText().toString().trim();
//Creating a string request
StringRequest stringRequest = new StringRequest(Request.Method.POST,
Config.LOGIN_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//If we are getting success from server
if(response.equalsIgnoreCase(Config.LOGIN_SUCCESS)){
//Creating a shared preference
SharedPreferences sharedPreferences =
LoginActivity.this.getSharedPreferences(Config.SHARED_PREF_NAME,
Context.MODE_PRIVATE);
//Creating editor to store values to shared
preferences
SharedPreferences.Editor editor =
sharedPreferences.edit();
//Adding values to editor
editor.putBoolean(Config.LOGGEDIN_SHARED_PREF,
true);
editor.putString(Config.EMAIL_SHARED_PREF, email);
//Saving values to editor
editor.commit();
//Starting profile activity
Intent intent = new Intent(LoginActivity.this,
PofileActivity.class);
startActivity(intent);
}else{
//If the server response is not success
//Displaying an error message on toast
Toast.makeText(LoginActivity.this, "Invalid username
or password", Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Error: " + error.getMessage());
//You can handle error here if you want
}
}){
#Override
public Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
//Adding parameters to request
params.put("Content-Type", "application/json");
params.put(Config.KEY_EMAIL, email);
params.put(Config.KEY_PASSWORD, password);
//returning parameter
return params;
}
};
//Adding the string request to the queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
#Override
public void onClick(View v) {
//Calling the login function
login();
}
This is common issue when using volley library. You may not be setting the right headers when you are making the request that is why it gives us 400 Bad Request error.
You may need to override the getBodyContentType() method in order to get the Content-Type header to update correctly.
public String getBodyContentType()
{
return "application/xml";
}
I have written a blog explaining the issue and how to resolve the same. Please refer here for resolution.

How to save a string globally?

I want to ask if is it possible to store a string globally for me to call in any other activity? Like for example the String email in my code, I want to save it globally so I can call it from other activity.
I tried using intent to carry data but it does not seem to work for my code.
private void checkLogin(final String email, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_login";
pDialog.setMessage("Logging in ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
// user successfully logged in
// Create login session
session.setLogin(true);
// Launch main activity
Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
startActivity(intent);
finish();
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "login");
params.put("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
You can use global variable, but most of the time you shouldn't use this.
Are global variables bad?
You have to know if this variable is used in most of your application (lot of class need an access to it, and be careful about threads to not have a concurrency issue). If it's the case you can maybe use a global, which is a bad idea in my opinion. You also can do a singleton class.
But if you just try to send your variable between two view, I think you should use this
You can use SharedPreferences to save data to preference and use it any Activity.
You can use this method to save your email String into SharedPreferences.
public void saveValueToPrefrence(Context mContext, String key, String value) {
SharedPreferences pref = mContext.getSharedPreferences("UserData", 0);
SharedPreferences.Editor editor = pref.edit();
editor.putString(key, value);
editor.apply();
}
You can get email String in any other Activity using below method:
public String getValueFromPrefrence(Context mContext, String key) {
SharedPreferences pref = mContext.getSharedPreferences("UserData", 0);
return pref.getString(key, "");
}
You can use this method to save your email String:
saveValueToPrefrence(ActivityName.this,"email",email)
You can get email String like this:
String email = getValueFromPrefrence(ActivityName.this,"email")
Basically you need Activity's Context to save and get value from SharedPreferences.
I hope it helps you.
#FreeYourSoul is correct.
But as an answer to this question, there are multiple ways to do this. The easiest way would be to simply create a Static class that has a hashmap inside it that you can manipulate with any class.
Likely not your best choice, but it certainly is possible

Categories

Resources