Android: Value out of JSONObject/responseListener - android

I try to save the userid to work with it in a different Activity, but I was not able to get the value out of the try catch statement. I should mention that I am new to Android. (Also the AlertDialog is not working but that is not important). Thanks for help!
EDIT: I just found this out: The code down below is for the "First Screen" (shown by the first start of the App) and after you click on the button you will get to the MainActivity. If I close the App after the First Screen opened MainActivity, and open it again, the SharedPreferences are working perfectly.
button = (Button) findViewById(R.id.savebtn);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
next_page(v);
}
});
}
public void next_page(View v){
final String firstname1 = firstnameFS.getText().toString();
final String lastname1 = lastnameFS.getText().toString();
Response.Listener<String> responseListener = new Response.Listener<String>(){
#Override
public void onResponse(String response){
try{
JSONObject jsonResponse = new JSONObject(response);
boolean success =jsonResponse.getBoolean("success");
int userid = jsonResponse.getInt("userid");
if(success){
AlertDialog.Builder builder3 = new AlertDialog.Builder(FirstScreen.this);
builder3.setMessage("Updated! Id:"+userid);
builder3.create().show();
SharedPreferences mySPR = getSharedPreferences("MySpFile", MODE_PRIVATE);
SharedPreferences.Editor editor = mySPR.edit();
editor.putString("firstnameSP", firstname1);
editor.putInt("useridSP", userid);
editor.commit();
}else{
AlertDialog.Builder builder = new AlertDialog.Builder(FirstScreen.this);
builder.setMessage("Update Failed");
builder.create().show();
}
} catch (JSONException e){
e.printStackTrace();
}
}
};
RegisterRequestFS registerRequestFS =new RegisterRequestFS(firstname1,lastname1, responseListener);
RequestQueue queue = Volley.newRequestQueue(FirstScreen.this);
queue.add(registerRequestFS);

Simply move your shared preferences edit command inside the if(success) block.
After committing the useridSP inside your shared preference retrieve it with this code:
SharedPreferences mySPR = getSharedPreferences("MySpFile", MODE_PRIVATE);
mySPR.getInt("useridSP",-1);
-1 value stays for default value, so be aware that if you get -1 for the useridSP in the new activity you're doing something wrong

Related

Error on Logging in Still prompts but still Logs in

I am developing a mobile application that has 2 types of users.
In my php code, I separated the boolean for each user. success for the client and success1 for the stylist.
When I press log in, the error prompts first following is the fast intent for the successful menu profile.
This is my line of codes from LoginRegister.java
private ProgressBar loading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
final EditText userLoginUsername = (EditText) findViewById(R.id.loginUser);
final EditText userLoginPassword = (EditText) findViewById(R.id.loginPass);
final Button Login = (Button) findViewById(R.id.buttonLogin);
final Button Register = (Button) findViewById(R.id.buttonRegister);
loading = findViewById(R.id.loadinglogin);
//login
Login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String username = userLoginUsername.getText().toString();
final String password = userLoginPassword.getText().toString();
if(!username.isEmpty() && !password.isEmpty()) {
Login.setVisibility(View.GONE);
loading.setVisibility(View.VISIBLE);
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
boolean success1 = jsonResponse.getBoolean("success1");
//Client's Log in
if (success) {
//gikan sa php (green ones) to strings sa android
String username = jsonResponse.getString("username");
String name = jsonResponse.getString("name");
String number = jsonResponse.getString("number");
String gender = jsonResponse.getString("gender");
String address = jsonResponse.getString("address");
String occupation = jsonResponse.getString("occupation");
String birth_date = jsonResponse.getString("birth_date");
String user_type = jsonResponse.getString("user_type");
Intent intent = new Intent(LoginRegister.this, ProfileActivity.class);
//from strings to pass sa lain intents.
intent.putExtra("username",username);
intent.putExtra("number",number);
intent.putExtra("name", name);
intent.putExtra("gender", gender);
intent.putExtra("address", address);
intent.putExtra("occupation", occupation);
intent.putExtra("birthDate", birth_date);
intent.putExtra("userType", user_type);
LoginRegister.this.startActivity(intent);
finish();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(LoginRegister.this);
builder.setMessage("Login Failed! Please provide valid username and password or connect to internet.")
.setNegativeButton("Retry", null)
.create()
.show();
Login.setVisibility(View.VISIBLE);
loading.setVisibility(View.GONE);
}
//Stylist's Log in
if(success1) {
String user_type = jsonResponse.getString("user_type");
Intent intent = new Intent(LoginRegister.this, ProfileActivity.class);
intent.putExtra("userType", user_type);
LoginRegister.this.startActivity(intent);
finish();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(LoginRegister.this);
builder.setMessage("Login Failed! Please provide valid username and password or connect to internet.")
.setNegativeButton("Retry", null)
.create()
.show();
Login.setVisibility(View.VISIBLE);
loading.setVisibility(View.GONE);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
LoginRequest loginRequest = new LoginRequest(username, password, responseListener);
RequestQueue queue = Volley.newRequestQueue(LoginRegister.this);
queue.add(loginRequest);
}else if(username.isEmpty() ){
userLoginUsername.setError("Please insert a username");
}else if(password.isEmpty()){
userLoginPassword.setError("Please put your password");
}
}
});
//register
Register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent Register = new Intent(LoginRegister.this, RegisterCustomerOrStylist.class);
LoginRegister.this.startActivity(Register);
}
});
}
PS they have different datas from different tables. What I did is that I have an if condition that if the boolean of success (client) is true, it passes the data and its else is the alertdialog for error login. After it is another if statement for the success1 (stylist) which has the same logic with client.
If simplified, your code looks like this.
//Client's Log in
if (success) {
} else {
AlertDialog.Builder builder = ...
}
//Stylist's Log in
if(success1) {
} else {
AlertDialog.Builder builder
}
This means if a stylist tries to log in, client's log in block alert dialog will be shown, and vice versa.
So, a flag may be needed to check any success exists.
boolean successAny = success || suucess1;
//Client's Log in
if (success) {
} else {
if (!successAny) {
AlertDialog.Builder builder = ...
}
}
...
NB. A person is a client and also be a stylist case is not intended for this sample.

How to use a value across all activities?

For example: I have a String value "A". and I have activities : activity_a, activity_b, activity_C.
Can I use value "A" across all activities? If yes how to achieve this?
And not through Intent or send data to another activity.
I am sorry that I am not fluent in English.
I moved a token value in login activity to main activity.
I used Intent and move token login activity. this is my login activity code.
StringRequest stringRequest = new StringRequest(Request.Method.POST, serverURL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
JSONArray jsonArray = new JSONArray(response);
JSONObject json_code = jsonArray.getJSONObject(0);
JSONObject json_token = jsonArray.getJSONObject(1);
String code = json_code.getString("code");
String token = json_token.getString("token");
Intent myIntent = new Intent(loginActivity.this, mainActivity.class);
myIntent.putExtra("token", token);
startActivity(myIntent);
finish();
overridePendingTransition(R.xml.madefadein, R.xml.splashfadeout);
}catch(JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
switch(error.networkResponse.statusCode)
{
case 409:
Toast.makeText(loginActivity.this, error.networkResponse.toString(), Toast.LENGTH_SHORT).show();
break;
}
}
but in main Activity, I tried to declare static like this.
Intent i = new Intent(getIntent());
public static final String token = i.getStringExtra("token");
but it doesn't work.
1.just declare your String as public static String strTmp="A"; in your activity than you can use any where in your project
like this
String strTmp = yourActivity.str;
2. create a new class like this
public class ServiceClass {
public static String strTmp="Data";
}
now you can access this string anywhere in your project like this
String mystr= ServiceClass.strTmp;
3.if you want use hard String than store your string in res/values/string.xml like this
<resources>
<string name="app_name">PatternView</string>
</resources>
than you can use like this
String str = getResources().getString(R.string.app_name);
4. save it in SharedPreferences like this
code for save data in SharedPreferences like this
SharedPreferences myPref;
SharedPreferences.Editor prefEditor;
myPref = getSharedPreferences("TOKENNAME", MODE_PRIVATE);
prefEditor = myPref.edit();
prefEditor.putString("TOKEN", "your token");
prefEditor.apply();
code for retrieve data from SharedPreferences
SharedPreferences myPref;
myPref = getSharedPreferences("TOKENNAME",
MODE_PRIVATE);
String name = myPref.getString("TOKEN", "");

store edited values in edittext fields after changed paramaters

public class ActivityEditParent extends AppCompatActivity {
private static final String TAG="ActivityEditParent";
CustomEditText etFirstName,etLastName,etEmail,etPhone;
public static ConnectionDetector detector;
private static final String URL = "http://hooshi.me.bh-in-13.webhostbox.net/index.php/parents/editprofile";
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
private CustomButton btnSave;
private String parentFirstName,parentLastName,parentPhone;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_parent);
getSupportActionBar().hide();
detector = new ConnectionDetector(ActivityEditParent.this);
getUIComponents();
}
private void getUIComponents(){
etFirstName = (CustomEditText) findViewById(R.id.edit_first_name);
etLastName = (CustomEditText) findViewById(R.id.edit_last_name);
etEmail = (CustomEditText) findViewById(R.id.edit_email_address);
etPhone = (CustomEditText) findViewById(R.id.edit_phone_number);
btnSave = (CustomButton) findViewById(R.id.btn_save_parent);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editParent();
}
});
TextView title = (TextView) findViewById(R.id.toolbar_title);
ImageButton back = (ImageButton) findViewById(R.id.toolbar_back);
title.setText("Edit parent");
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goBack();
}
});
sharedPreferences = getSharedPreferences(AppConstants.OOSH_PREFERENCES, Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
String fName = sharedPreferences.getString(AppConstants.PARENT_FNAME,AppConstants.fName);
String lName = sharedPreferences.getString(AppConstants.PARENT_LNAME,AppConstants.lName);
String email = sharedPreferences.getString(AppConstants.PARENT_EMAIL,AppConstants.email);
String phone = sharedPreferences.getString(AppConstants.PARENT_MOBILE,AppConstants.mobile);
etFirstName.setText(fName);
etLastName.setText(lName);
etPhone.setText(phone);
etEmail.setText(email);
}
private void goBack() {
startActivity(new Intent(getApplicationContext(), ActivityEditDetails.class));
finish();
}
private void editParent(){
SharedPreferences preferences = getSharedPreferences(AppConstants.OOSH_PREFERENCES, Context.MODE_PRIVATE);
final SharedPreferences.Editor editor = preferences.edit();
JSONObject jsonParam = null;
parentFirstName = etFirstName.getText().toString().trim();
parentLastName = etLastName.getText().toString().trim();
parentPhone = etPhone.getText().toString().trim();
if (detector.checkInternet()){
jsonParam = new JSONObject();
JSONObject header = new JSONObject();
try {
jsonParam.put("parentId",preferences.getString(AppConstants.PARENT_ID,""));
jsonParam.put("parentFN",parentFirstName);
jsonParam.put("parentLN",parentLastName);
jsonParam.put("parentPhone",parentPhone);
jsonParam.put("apiAccessKey",preferences.getString(AppConstants.API_ACCESS_KEY,""));
header.put("parent",jsonParam);
Log.d("POST PARAMETERS:",""+header);
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, URL, header, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Response:",""+response);
String json_status = null;
try {
json_status = response.getString("status");
if (json_status.equalsIgnoreCase("Success")){
Toast.makeText(getApplicationContext(), "changed parent details successfully", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),ActivityHome.class));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
VolleySingleton.getInstance(getApplicationContext()).addToRequestQueue(jsonObjectRequest);
}
}
}
In the response After getting success message I want save the edited details in in respective edit text fields please help.After success message I am moving to home screen through intent and again I get back to this screen it is showing the previous details only.
all happens here :
...
if (json_status.equalsIgnoreCase("Success")){
Toast.makeText(getApplicationContext(), "changed parent details successfully", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),ActivityHome.class));
}
...
once you have a success response save the edited values on the preferences, for example etFirstName, save it is new value to the corresponding preference :
...
if (json_status.equalsIgnoreCase("Success")){
Toast.makeText(getApplicationContext(), "changed parent details successfully", Toast.LENGTH_SHORT).show();
editor.putString(AppConstants.PARENT_FNAME, parentFirstName);
editor.apply(); //don't forget this
startActivity(new Intent(getApplicationContext(),ActivityHome.class));
}
...
any way you're creating the editor but not using it.
you want to save data after download from network or after an edit in edit text fields was made??
if from network add some save method execution statement in code where you download data was successful
if (json_status.equalsIgnoreCase("Success")){
Toast.makeText(getApplicationContext(), "changed parent details successfully", Toast.LENGTH_SHORT).show();
// here you have successful received data so u can map them to edit text or save in shared prefs
// add method to save data here
saveData(response);
startActivity(new Intent(getApplicationContext(),ActivityHome.class));
}
private void saveData(JSONObject response) {
// use JSon response object save here to shared preferences
// see how to load data from json object
// https://processing.org/reference/JSONObject_getString_.html
SharedPreferences sharedPreferences = getSharedPreferences(AppConstants.OOSH_PREFERENCES, Context.MODE_PRIVATE);
sharedPreferences.putString(....).apply;
// or set edit text controls with JSon data
}
to save edit text changes you have two choices :
add to layout save button (you have one) button and set on click listener with method to save data:
btnSave = (CustomButton) findViewById(R.id.btn_save_parent);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveData(v);
}
});
private void saveData(View view) {
// get root view
View rootView = view.getRootView();
// find edit text widget on root view
EditText etFirstName = (EditText) rootView.findViewById(R.id.edit_first_name);
// get string from edit text widget
String firstName = etFirstName.getString.toString();
// get shared preferences
SharedPreferences sharedPreferences = getSharedPreferences(AppConstants.OOSH_PREFERENCES, Context.MODE_PRIVATE);
// save to shared prefs firstName wher NAME_KEY is string to identified your saved data for later use - to load
sharedPreferences.putString(NAME_KEY,firstName).apply;
}
private void loadDataFromSharedPredferences(View view) {
// get shared preferences
SharedPreferences sharedPreferences = getSharedPreferences(AppConstants.OOSH_PREFERENCES, Context.MODE_PRIVATE);
// load data from shared prefs firstName wher NAME_KEY is string to identified data to load
String firstName = sharedPreferences.getString(NAME_KEY,firstName);
// get root view
View rootView = view.getRootView();
// find edit text widget on root view
EditText etFirstName = (EditText) rootView.findViewById(R.id.edit_first_name);
// set string to edit text widget
etFirstName.setText(firstName);
}
add on text change listener for edittext widgets
ps. you need to clarify - write a exactly steps of what you want to do achieve
load data from network ? then save ?
or save request date ?
or save result data ?

Correct way of getting a Json position

After the login I get this response from the webserver..
{"success":" Bem vindo lu#lu.com"}{"nomeusuario":"Lu Zimermann"}{"enderecousuario":"Rua Pedro Alves 270. Centro. Casa."}{"telefoneusuario":"(42) 3623-8052"}
Ok. Now My android code.
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if(jsonObject.names().get(0).equals("success")){
Toast.makeText(getApplicationContext(),jsonObject.getString("success"),Toast.LENGTH_SHORT).show();
//startActivity(new Intent(getApplicationContext(),Restaurantes.class));
}else {
Toast.makeText(getApplicationContext(), jsonObject.getString("error"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
This code Toast the following message. "Bem vindo lu#lu.com"
What I want is:
How can I get the other infos and pass it to a String.
Email = "lu#lu.com"
Endereco = "Rua Pedro..."
Name = "Lu Zimermann"
Soo I can use it later on the app.
Thanks.
Now the response is the right way you can do this to save data..
first wirte a custion class for Preferennce
SharedPreferenceCustom
public class SharedPreferenceCustom {
private Context mContext;
private String defValue = "";
public SharedPreferenceCustom(Context context) {
this.mContext = context;
}
public void setSharedPref(String inputKey, Object inputValue) {
final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(inputKey, String.valueOf(inputValue));
editor.apply();
}
public String getSharedPref(String inputKey) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
return sharedPreferences.getString(inputKey, defValue);
}
}
Now for saving the data, in the activity
try {
JSONObject response = new JSONObject(new String(response_from_server))
SharedPreferenceCustom sp = new SharedPreferenceCustom(Activity.this);
sp.setSharedPref("key_1", response.getString("nomeusuario")); // use key as per needed
sp.setSharedPref("key_2", response.getString("enderecousuario"));
sp.setSharedPref("key_3", response.getString("telefoneusuario"));
sp.setSharedPref("key_4", response.getString("success"));
} catch (JSONException e) {
e.printStackTrace();
}
And for getting the data call sp.getSharedPref("key"); pass the key for getting the corresponding data
EDIT: you can also write individual function in SharedPreferenceCustion to store different data type, or you can use just this, But it might create some conflicts for certain data types,
Hope this helps :) :)
To get access to the other keys, you can use the get(key) on the jsonObject object. Here are the code changes you need to make:
try {
JSONObject jsonObject = new JSONObject(response);
if(jsonObject.names().get(0).equals("success")){
Toast.makeText(getApplicationContext(),jsonObject.getString("success"),Toast.LENGTH_SHORT).show();
{"success":" Bem vindo lu#lu.com"}{"nomeusuario":"Lu Zimermann"}{"enderecousuario":"Rua Pedro Alves 270. Centro. Casa."}{"telefoneusuario":"(42) 3623-8052"}
//here I am just getting the other properties/keys
String nomeusuario = jsonObject.getString("nomeusuario");
String enderecousuario = jsonObject.getString("enderecousuario");
String telefoneusuario = jsonObject.getString("telefoneusuario");
//here you could do whatever you like - I am just making a Toast as an example:
Toast.makeText(getApplicationContext(), nomeusuario+ ", "+enderecousuario+ ", "+telefoneusuario ,Toast.LENGTH_LONG).show();
}else {
Toast.makeText(getApplicationContext(), jsonObject.getString("error"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
I hope this helps you - give it a try and let me know.
By the way, I am assuming the JSON that you are getting is proper.
There are several ways you can do that.
First of all you need to store them into variable/s.
You can choose to keep it as JSON var, as HashMap or each variable separate as String.
The second action is to access it from any place. This depends on how long to you want the information alive.
If you want them live for just as long as the app is live then the I suggest to create a Global Java class with set/get of your variable.
You could also store it in SharedPreferences or sqlite database for permanent.
Try following
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
if(jsonObject.names().get(0).equals("success")){
//Toast.makeText(getApplicationContext(),jsonObject.getString("success"),Toast.LENGTH_SHORT).show();
JSONObject jsonObject = new JSONObject(response);
Iterator<String> keys = jsonObject.keys();
String values = "";
while(keys.hasNext()){
String keyName = keys.next();
values = jsonObject.getString(keyName) + "\n";
}
Toast.makeText(getApplicationContext(),values,Toast.LENGTH_SHORT).show();
//startActivity(new Intent(getApplicationContext(),Restaurantes.class));
}else {
Toast.makeText(getApplicationContext(), jsonObject.getString("error"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}

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.

Categories

Resources