How to save a string globally? - android

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

Related

Android Sharedpreferences Updating Only After App Restart

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

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

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.

why its showing nullpointerexception? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I know this is a really common topic but I'm getting this error and don't know why. The code is working absolutely fine in Eclipse but crashing on Button click in Studio. The only difference I can think of is Request.Method instead of Method as in Eclipse. Earlier I thought its because, the values from edittext are not getting. But its showing in Toast.
Error
01-13 11:13:34.242 14427-14427/com.sam.sports E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.sam.sports, PID: 14427
java.lang.NullPointerException
at com.sam.sports.LoginPage.checkLogin(LoginPage.java:180)
at com.sam.sports.LoginPage.access$200(LoginPage.java:28)
at com.sam.sports.LoginPage$1.onClick(LoginPage.java:80)
at android.view.View.performClick(View.java:4562)
at android.view.View$PerformClick.run(View.java:18918)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5388)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:655)
at dalvik.system.NativeStart.main(Native Method)
01-13 11:13:38.996 14427-14427/com.sam.sports I/Process: Sending signal. PID: 14427 SIG: 9
public class LoginPage extends AppCompatActivity {
private static final String TAG = RegisterPage.class.getSimpleName();
private Button btnLogin;
private Button btnLinkToRegister;
private EditText inputEmail;
private EditText inputPassword;
private ProgressDialog pDialog;
private SessionManager session;
private SQLiteHandler db;
String name;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loginpage);
inputEmail = (EditText) findViewById(R.id.email_login);
inputPassword = (EditText) findViewById(R.id.password_login);
btnLogin = (Button) findViewById(R.id.login_btn);
btnLinkToRegister = (Button) findViewById(R.id.btnLinktoRegd);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// SQLite database handler
db = new SQLiteHandler(getApplicationContext());
// Session manager
session = new SessionManager(getApplicationContext());
// Check if user is already logged in or not
if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
Intent intent = new Intent(LoginPage.this, HomePage.class);
startActivity(intent);
finish();
}
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String email = inputEmail.getText().toString().trim();
String password = inputPassword.getText().toString().trim();
// Check for empty data in the form
if (!email.isEmpty() && !password.isEmpty()) {
// login user
checkLogin(email, password);
//Toast.makeText(getApplicationContext(), email + "\n" + password, Toast.LENGTH_LONG ).show();
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(), "Please enter the credentials!", Toast.LENGTH_LONG).show();
}
}
});
// Link to Register Screen
btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startActivity(new Intent(LoginPage.this, RegisterPage.class));
finish();
}
});
}
/**
* function to verify login details in mysql db
* */
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(Request.Method.POST,
AppConfig.URL_LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
String status = jObj.getString("status");
// Now check status value
if (status.equals("0")) {
Toast.makeText(getApplicationContext(), "Email or Password may be incorrect! Please try again.", Toast.LENGTH_LONG).show();
}else if(status.equals("1")){
// user successfully logged in
// Create login session
session.setLogin(true);
// Now store the user in SQLite
JSONObject userData = jObj.getJSONObject("userData");
String uid = userData.getString("id");
String name = userData.getString("name");
String email = userData.getString("email");
String created_at = userData.getString("created_at");
// Inserting row in users table
db.addUser(name, email, uid, created_at);
// Launch main activity
startActivity(new Intent(LoginPage.this, HomePage.class));
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();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, 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("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
Although this is not a solution to your problem(for solution look below), refactoring the checkLogin Method will definetly help alot in finding the cause of the error. Due to the fact that the checkLogin method was way to long I've move some of the code into other methods.
Copy it, run it and let us know which line throws the error.
/**
* function to verify login details in mysql db
* */
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(Request.Method.POST,
AppConfig.URL_LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
hideDialog();
checkStatus();
}
}, 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("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void checkStatus() {
try {
JSONObject jObj = new JSONObject(response);
String status = jObj.getString("status");
// Now check status value
if (status.equals("0")) {
processStatusZero();
}else if(status.equals("1")){
processStatusOne(jObj);
} else {
processStatusError(jObj);
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
private void processStatusZero() {
Toast.makeText(getApplicationContext(), "Email or Password may be incorrect! Please try again.", Toast.LENGTH_LONG).show();
}
private void processStatusOne(JSONObject jObj) {
// user successfully logged in
// Create login session
session.setLogin(true);
// Now store the user in SQLite
JSONObject userData = jObj.getJSONObject("userData");
String uid = userData.getString("id");
String name = userData.getString("name");
String email = userData.getString("email");
String created_at = userData.getString("created_at");
// Inserting row in users table
db.addUser(name, email, uid, created_at);
// Launch main activity
startActivity(new Intent(LoginPage.this, HomePage.class));
finish();
}
private void processStatusError(JSONObject jObj) {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(), errorMsg, Toast.LENGTH_LONG).show();
}
Now for the actual solution: you need to add AppControler to the Android Manifest. You do this by adding the following lines in your manifest file:
<application
android:name=".AppController"
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme">
This way AppController.getInstance() will stop returning null.

Android - trouble updating SQLite after success webrequest on return statement

I have a function that uses StringRequest to send a post request to my server. The script on the server side updates the database with the user's new settings.
The server side script returns 1 on success and 0 on failure, with appropriate message too. What I have tried to do with the StringRequest function is a similar thing.
public int updateLiveSettings(Switch discoverySwitch, Switch menSwitch, Switch womenSwitch) {
// Tag used to cancel the request
final String email = db.getFromTable(getActivity(), "email", SQLiteHandler.TABLE_LOGIN, "WHERE _id="+uid);
final String discovery = switchValue(discoverySwitch);
final String men = switchValue(menSwitch);
final String women = switchValue(womenSwitch);
final String tag_string_req = "update_settings";
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_UPDATE_SETTINGS, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Response: ", response.toString());
try {
JSONObject jObj = new JSONObject(response);
success = jObj.getInt("success");
// Check for error node in json
if (success == 1) {
Log.i(tag_string_req, success+" - yes");
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getActivity(),errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error: ", error.getMessage());
Toast.makeText(getActivity(),
error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("tag", tag_string_req);
params.put("account", discovery);
params.put("men", men);
params.put("women", women);
params.put("email", email);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
return success;
}
Success is always returned as either 1 or 0. I then use this to update the stored settings in the SQLite database.
womenSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// do something, the isChecked will be
//Log.i("live attempt", updateLiveSettings(discoverySwitch, menSwitch, womenSwitch)+"");
if(updateLiveSettings(discoverySwitch, menSwitch, womenSwitch) == 1){
Log.i("womenswitch", "live update success");
if(isChecked==true){
Log.i("womenswitch", "is checked");
db.update(SQLiteHandler.TABLE_SETTINGS, "women=1", "uid="+uid);
}else{
Log.i("wpmenswitch", "is not checked");
db.update(SQLiteHandler.TABLE_SETTINGS, "women=0", "uid="+uid);
if(menSwitch.isChecked()==false){
menSwitch.setChecked(true);
db.update(SQLiteHandler.TABLE_SETTINGS, "men=1", "uid="+uid);
}
}
}
}
});
The problem I'm having is that even when the update is successful and the correct int is returned the local database isn't updated.
It basically never gets passed if(updateLiveSettings(discoverySwitch, menSwitch, womenSwitch) == 1) I get nothing in the LogCat so I can only assume I'm doing this incorrectly.
Any help would be great :)
This is the nature of an asynchronous request.
When you look at the image at Send a Request (and at your code), you can see that the request is put into a request queue. Only when the request is performed or a result taken from the cache, it will return to your main thread in the form of the onResponse or onErrorResponse method.
But when the result is delivered to your application, your method updateLiveSettings has already returned and delivered whatever was in the success variable. You can see this order of events, when you add a Log output after the if statement.
To update the database based on the success result, you must do this inside the onResponse method, e.g.
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// ...
updateLiveSettings(discoverySwitch, menSwitch, womenSwitch, isChecked);
}
and in updateLiveSettings()
public void onResponse(String response) {
Log.d("Response: ", response.toString());
try {
JSONObject jObj = new JSONObject(response);
int success = jObj.getInt("success");
// Check for error node in json
if (success == 1) {
Log.i(tag_string_req, success+" - yes");
if (isChecked==true){
Log.i("womenswitch", "is checked");
db.update(SQLiteHandler.TABLE_SETTINGS, "women=1", "uid="+uid);
} else {
Log.i("wpmenswitch", "is not checked");
db.update(SQLiteHandler.TABLE_SETTINGS, "women=0", "uid="+uid);
}
} else {
// ...

Categories

Resources