I am making an application which has a profile section for user data. Where a person can update the data such as college, university, branch. I have saved this data in shared preference when the person logged in the application and from that shared preference data, all the information of a user has been provided. How to instantly change the preferences data and set to the whole app. Well I am new in developing field os need help in getting things done.
Here is my code for updating user data activity
public void edit_user_data(){
final String str_new_name = _edit_prof_name_.getText().toString().trim();
linearLayout.setVisibility(View.VISIBLE);
ObjectAnimator flip = ObjectAnimator.ofFloat(imgSpoon, "rotationY", 0f, 180f);
flip.setDuration(800);
flip.setRepeatCount(Animation.INFINITE);
flip.start();
StringRequest strReq = new StringRequest(Request.Method.POST,
URLconstant.USER_UPDATE, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
linearLayout.setVisibility(View.INVISIBLE);
try {
JSONObject data = new JSONObject(response);
JSONObject updatedata = data.optJSONObject("data");
int intError = updatedata.getInt("status");
boolean error = (intError > 0) ? true : false;
if(intError == 1){
String msg = updatedata.optString("msg");
Toast.makeText(ActivityUserEditProfile.this, msg, Toast.LENGTH_SHORT).show();
JSONArray data_array = new JSONArray("data");
for (int i = 0;i<=data_array.length();i++){
JSONObject data_obj = data_array.getJSONObject(i);
/* UserProfileData userdata = new UserProfileData();
userdata.setFullname(data_obj.getString("fullname"));
userdata.setUniverId(data_obj.getString("univer_id"));
userdata.setMuniversity(data_obj.getString("university"));
userdata.setCollegeid(data_obj.getString("collegeid"));
userdata.setMcollege(data_obj.getString("college"));
userdata.setBranchid(data_obj.getString("branchid"));
userdata.setMbranch(data_obj.getString("branch"));
userdata.setSemid(data_obj.getString("semid"));
userdata.setMsemester(data_obj.getString("semester"));
userdata.setUserImage(data_obj.getString("user_image"));
userdata.setUserId(data_obj.getString("user_id"));
userdata.setPassword(data_obj.getString("password"));
updated_info(data_obj);
SharedPreferences preferences = getApplicationContext().getSharedPreferences(SHARED_PRE_LOGIN_REGISTRATION, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
*//* preferences.edit().remove(FULL_NAME);
preferences.edit().remove(UNIVER_ID);
preferences.edit().remove(BRANCH_ID);
preferences.edit().remove(COLLEGE_ID);
preferences.edit().remove(SEM_ID);*//*
editor.clear();
editor.commit();
PreferenceHelper preferenceHelper = new PreferenceHelper();
preferenceHelper.getInstance(context).setBranchid(userdata.getBranchid());
preferenceHelper.getInstance(context).setCollegeid(userdata.getCollegeid());
preferenceHelper.getInstance(context).setEnrollno(userdata.getEnrollno());
preferenceHelper.getInstance(context).setFullname(userdata.getFullname());
preferenceHelper.getInstance(context).setMobile(userdata.getMobile());
preferenceHelper.getInstance(context).setSemid(userdata.getSemid());
preferenceHelper.getInstance(context).setUniverId(userdata.getUniverId());
preferenceHelper.getInstance(context).setUserId(userdata.getUserId());
preferenceHelper.getInstance(context).setUserImage(userdata.getUserImage());
preferenceHelper.getInstance(context).setMuniversity(userdata.getMuniversity());
preferenceHelper.getInstance(context).setMcollege(userdata.getMcollege());
preferenceHelper.getInstance(context).setMbranch(userdata.getMbranch());
preferenceHelper.getInstance(context).setMsemester(userdata.getMsemester());
preferenceHelper.getInstance(context).setPassword(userdata.getPassword());*/
}
}else{
String msg = updatedata.optString("msg");
Toast.makeText(ActivityUserEditProfile.this, msg, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_SHORT).show();
// pDialog.hide();
linearLayout.setVisibility(View.INVISIBLE);
}
}){
//adding parameters to the request
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("fullname",str_new_name);
params.put("univer_id",u_id);
params.put("collegeid",c_id);
params.put("branchid",b_id);
params.put("semid",s_id);
params.put("mobile",PreferenceHelper.getInstance(getApplicationContext()).getMobile());
return params;
}
};
MySingleton.getInstance(this).addToRequestQueue(strReq);
}
For this You can do this
SharedPreferences.OnSharedPreferenceChangeListener spChanged = new
SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
// your stuff here
}
};
For Details can you follow this android developer Documentation
Related
When I put something wrong, I receive everything in onResponse but it does not go for the function resultado() and when I put all the data well, it goes to the function resultaod() but only until the time to assign the values to usuario and from the toast it is not executed.
Login Activity
public class LoginActivity extends AppCompatActivity {
private RelativeLayout parentLayout;
private EditText txtUsuario, txtContraseña;
private TextView txtVersion;
private CheckBox chxRecordar;
private Button btnEntrar;
private SharedPreferences myPreferences;
private Usuario usuario;
private String codes, status, token;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
iniciarComponentes();
btnEntrar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
verificarInicio();
}
});
}
private void iniciarComponentes() {
parentLayout = findViewById(R.id.parent_layout);
txtUsuario = findViewById(R.id.txt_usuario);
txtContraseña = findViewById(R.id.txt_password);
chxRecordar = findViewById(R.id.chx_recordar);
btnEntrar = findViewById(R.id.btn_entrar);
txtVersion = findViewById(R.id.txt_version);
txtVersion.setText("Version " + BuildConfig.VERSION_NAME);
myPreferences = PreferenceManager.getDefaultSharedPreferences(this);
}
private void verificarInicio() {
String url = Common.BASE_URL + "usuario";
if (validarSesion()) {
Log.d("verificarInicio: ", url);
final String usuario = txtUsuario.getText().toString();
final String contraseña = txtContraseña.getText().toString();
final android.app.AlertDialog dialog = new SpotsDialog.Builder().setContext(this).setMessage("Cargando...").setCancelable(false).build();
dialog.show();
RequestQueue requestQueue = Volley.newRequestQueue(LoginActivity.this);
final StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
codes = jsonObject.getString("code");
status = jsonObject.getString("status");
token = jsonObject.getString("token");
resultado(codes, status, jsonObject, token);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Snackbar.make(parentLayout, error.getMessage(), Snackbar.LENGTH_LONG).show();
dialog.dismiss();
}
}) {
#Override
protected Map<String, String> getParams() {
HashMap<String, String> parametros = new HashMap<>();
parametros.put("dni", usuario);
parametros.put("password", contraseña);
return parametros;
}
};
requestQueue.add(stringRequest);
requestQueue.addRequestFinishedListener(new RequestQueue.RequestFinishedListener<String>() {
#Override
public void onRequestFinished(Request<String> request) {
if (dialog.isShowing())
dialog.dismiss();
}
});
}
}
private void resultado(String codes, String status, JSONObject jsonObject, String token) throws JSONException {
if (codes.equals("100")) {
JSONArray array = jsonObject.getJSONArray("result");
JSONObject dato = array.getJSONObject(0);
usuario = new Usuario(dato.getString("NombreCompleto"),
dato.getString("estado"),
dato.getString("foto"),
dato.getString("nombre_Aso"),
dato.getString("nombre_Red"),
dato.getString("sexo_Pro"),
dato.getInt("campana"));
Toast.makeText(LoginActivity.this, status, Toast.LENGTH_SHORT).show();
Common.USUARIO_DNI = txtUsuario.getText().toString();
guardarUsuario(token);
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.putExtra(Common.USUARIO, usuario);
startActivity(intent);
finish();
} else if (codes.equals("200")) {
Snackbar.make(parentLayout, status, Snackbar.LENGTH_LONG).show();
} else if (codes.equals("203")) {
Snackbar.make(parentLayout, status, Snackbar.LENGTH_LONG).show();
}
}
private boolean validarSesion() {
if (TextUtils.isEmpty(txtUsuario.getText()) || TextUtils.isEmpty(txtContraseña.getText())) {
Snackbar.make(parentLayout, "Ingrese su usuario y contraseña", Snackbar.LENGTH_SHORT).show();
return false;
}
return true;
}
private void guardarUsuario(String token) {
SharedPreferences.Editor myEditor = myPreferences.edit();
if (chxRecordar.isChecked()) {
if (!myPreferences.contains(Common.USUARIO)) {
myEditor.putString(Common.USUARIO, txtUsuario.getText().toString());
myEditor.putString(Common.CONTRASEÑA, txtContraseña.getText().toString());
myEditor.putBoolean(Common.CHECK_ESTADO, chxRecordar.isChecked());
myEditor.putString(Common.TOKEN, token);
myEditor.apply();
if (Common.USUARIO_DNI.isEmpty()) {
Common.USUARIO_DNI = myPreferences.getString(Common.USUARIO, "");
}
}
} else {
myEditor.clear();
myEditor.commit();
}
}
}
The whole code is not executed, only a part, I do not know why, I would be grateful if you helped me
check that recibe in a catch, the problem is when get the string for the jsonObject
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
codes = jsonObject.getString("code");
status = jsonObject.getString("status");
token = jsonObject.getString("token");
resultado(codes, status, jsonObject, token);
} catch (JSONException e) {
e.printStackTrace();
}
}
I am trying to implement a functionality i.e. if the network connection is on then app will hit the api. I have added network connectivity code in parent activity and calling a method from its fragment but I am getting null object reference error. I am adding code. Please check.
Parent Activity Code to Call Function From Fragment:
private void showSnack(boolean isConnected) {
String message;
int color;
if (isConnected) {
**FinalizePreOrderFragment finalizePreOrderFragment = new FinalizePreOrderFragment(this);
finalizePreOrderFragment.finalizePreOrderApi();**
}
Code for Fragment to Call Api
public void finalizePreOrderApi() {
// pBar.setVisibility(View.VISIBLE);
String tag_json_obj = "json_obj_req";
String url = Constants.Pre_Order;
HashMap<String, String> params = new HashMap<String, String>();
final SessionManager sessionManager = new SessionManager(getActivity());
HashMap<String, String> loggedDetails = sessionManager.getLoggedUserDetails();
params.put("api_token", loggedDetails.get("api_token"));
params.put("user_id", loggedDetails.get("id"));
params.put("shops_order_list", lis);
Log.e("TAG", "preOrderApi: " + params);
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e("pre_order_response", response.toString());
try {
if (response.has("error")) {
Toast.makeText(getActivity(), response.getString("error"), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getActivity(), response.getString("success"), Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
Activity activity = getActivity();
if (activity != null && isAdded()) {
Toast.makeText(activity, R.string.some_error_occured, Toast.LENGTH_LONG).show();
}
}
// pBar.setVisibility(View.GONE);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: " + error.getMessage());
Activity activity = getActivity();
if (activity != null && isAdded()) {
Toast.makeText(activity, R.string.some_error_occured, Toast.LENGTH_LONG).show();
pBar.setVisibility(View.GONE);
}
}
});
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
}
I am using SharedPreference at below point :
final SessionManager sessionManager = new SessionManager(getActivity());
HashMap<String, String> loggedDetails = sessionManager.getLoggedUserDetails();
I am saving my preferences in session manager class. And getting error at below point:
public SessionManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
You can add this in your getLoggedUserDetails() method.
SharedPreferences prefs = getSharedPreferences(YOUR_PREFRENCE_KEY, MODE_PRIVATE);
//Lets say you have stored user_id in object retrieve it
int mUserId = prefs.getInt("user_id", 0);//default is 0
if (mUserId >0)
//Return your Object
else
//User is not logged in or stored in Prefrences
Sorry if this post is not correctly filled but ill try to do my best. I am attempting to create an android app with android studio where i need a TinderLike swipe holder.
For this purpose i am using this library: CardStackView
Everything is working fine if i use the default code to populate the pictures.
private List<TouristSpot> createTouristSpots() {
List<TouristSpot> spots = new ArrayList<>();
spots.add(new TouristSpot("Yasaka Shrine", "Kyoto", "https://source.unsplash.com/Xq1ntWruZQI/600x800"));
spots.add(new TouristSpot("Fushimi Inari Shrine", "Kyoto", "https://source.unsplash.com/NYyCqdBOKwc/600x800"));
spots.add(new TouristSpot("Bamboo Forest", "Kyoto", "https://source.unsplash.com/buF62ewDLcQ/600x800"));
spots.add(new TouristSpot("Brooklyn Bridge", "New York", "https://source.unsplash.com/THozNzxEP3g/600x800"));
spots.add(new TouristSpot("Empire State Building", "New York", "https://source.unsplash.com/USrZRcRS2Lw/600x800"));
spots.add(new TouristSpot("The statue of Liberty", "New York", "https://source.unsplash.com/PeFk7fzxTdk/600x800"));
spots.add(new TouristSpot("Louvre Museum", "Paris", "https://source.unsplash.com/LrMWHKqilUw/600x800"));
spots.add(new TouristSpot("Eiffel Tower", "Paris", "https://source.unsplash.com/HN-5Z6AmxrM/600x800"));
spots.add(new TouristSpot("Big Ben", "London", "https://source.unsplash.com/CdVAUADdqEc/600x800"));
spots.add(new TouristSpot("Great Wall of China", "China", "https://source.unsplash.com/AWh9C-QjhE4/600x800"));
return spots;
}
But when i try to change the default population code with a code that retrieve information from a database, nothing is displayed anymore.
private List<TouristSpot> createTouristSpots() {
final List<TouristSpot> spots = new ArrayList<>();
String url = AppData.api + "radar_2.php";
alerttext.setVisibility(View.VISIBLE);
SharedPreferences token = getApplicationContext().getSharedPreferences(AppData.sp_user_info, 0);
String user_id = token.getString(AppData.sp_user_id, "0");
UserData userData=new AppData().getUserData();
Map<String, String> params = new HashMap<String, String>();
params.put("user_id", user_id);
params.put("number", String.valueOf(n));
params.put("gender", userData.getLooking_gender());
params.put("looking_age_start",userData.getLooking_age_start());
params.put("looking_age_end", userData.getLooking_age_end());
params.put("latitude", userData.getLatitude());
params.put("longitude", userData.getLongitude());
params.put("distance", "100");
CustomRequest jsObjRequest = new CustomRequest(Request.Method.POST, url, params, new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response)
{
if (n == 1)
{
SharedPreferences.Editor editor = pref.edit();
editor.putString("MATCHDATALIST", response.toString());
editor.commit();
}
try
{
String str = response.getString("Error");
if (str.equals("None"))
{
JSONArray jsonArray = response.getJSONArray("Responsedata");
//Toast.makeText(getActivity(), jsonArray.toString(), Toast.LENGTH_LONG).show();
for (int i = 0; jsonArray.length() > i; i++)
{
JSONObject jsonObject = jsonArray.getJSONObject(i);
spots.add(new TouristSpot(jsonObject.getString("user_id"),jsonObject.getString("username"),jsonObject.getString("hometown"),jsonObject.getString("age"),jsonObject.getString("gender"),jsonObject.getString("profile_image"),jsonObject.getString("interests"),jsonObject.getString("distance")));
}
alerttext.setVisibility(View.GONE);
} else {
//Toast.makeText(getActivity(), response.getString("Error"), Toast.LENGTH_LONG).show();
}
} catch (JSONException e)
{
e.printStackTrace();
}
}
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError response)
{
//Toast.makeText(getActivity(), response.toString(), Toast.LENGTH_LONG).show();
}
});
jsObjRequest.setRetryPolicy(new DefaultRetryPolicy(15000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(jsObjRequest);
//Toast.makeText(getActivity(), spots.toString(), Toast.LENGTH_LONG).show();
return spots;
}
In my OnCreateView, i am calling the function reload();
private void reload() {
cardStackView.setVisibility(View.GONE);
adapter = createTouristSpotCardAdapter();
cardStackView.setAdapter(adapter);
cardStackView.setVisibility(View.VISIBLE);
}
private TouristSpotCardAdapter createTouristSpotCardAdapter() {
final TouristSpotCardAdapter adapter = new TouristSpotCardAdapter(getApplicationContext());
adapter.addAll(createTouristSpots());
return adapter;
}
I did checked the JSONArray to string and all information retrieved from the database is inside it.
PS: the TouristSpot is adapted to contain all the variables from the database.
If some one could bring me on the correct path to make it working with values retrieved from my database, i would be very gratfull
Sincerely,
Jeremy
I'm using volley to get response from API but the response consist of STATE_ID:STATE_NAME pair (i.e. value:value pair) and I need both side's values in different Strings. I need these values to put in a spinner so that when user selects a State I can get its corresponding ID also.
// JSON response
{
"1": "West bengal",
"3": "Himachal Pradesh",
"4": "Maharashtra",
"11": "Queensland"
}
My Code
public class MainActivity extends AppCompatActivity {
private static final String STATE = "MY_API";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void login(View v){
loginRequest();
}
private void loginRequest() {
StringRequest stringRequest = new StringRequest(Request.Method.POST, STATE,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(MainActivity.this, response, Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "VolleyError" + error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("country_id","2");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
}
You already have the iterate() method as we discussed in comments.
Done some work to give you value :
try {
JSONObject jsonObject = new JSONObject(response);
for (String key : iterate(jsonObject.keys()))
{
Toast.makeText(this, "Key : "+key+" Value: "+jsonObject.optString(key), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
Please refer the iterate method from this answer. I have posted this as a new answer because OP was unable to make it for the values..!!
I used iterator to find a key. May this will help:
private void parseRespone(String response){
try {
JSONObject MainjsonObject = new JSONObject(response)
Iterator<String> iter= MainjsonObject.keys();
//To get keys of an object
while (iter.hasNext())
{
String key = (String)iter.next();
//Object value = jsonobj.get(key); //To use by object
String valueStr = jsonobj.get.getString(key);
Log.i("Jsonparsing", "key= "+key + "\n Value=" +valueStr );
Toast.makeText(getActivity(),"key= "+ key + "\n value= " + valueStr ,Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
}
I could find an unknown key by this.
Please check in a Log in your android studio...
here I have put Toast also..
And call this function here...
...........
#Override
public void onResponse(String response) {
parseRespone(response); //Function to parse json
}
Thanks..
It will be much better if you consider changing your response to something like this:
[
{"ID":"1","name": "West bengal"},
{"ID":"3","name": "Himachal Pradesh"},
{"ID":"4","name": "Maharashtra"},
{"ID":"11","name": "Queensland"}
]
You can use jsonObject.names() (or keys() for an Iterator) to retrieve all keys.
After that you can iterate through the array using the keys and store your strings.
https://developer.android.com/reference/org/json/JSONObject.html#names()
https://developer.android.com/reference/org/json/JSONObject.html#keys()
I tried this solution and it worked out.`Here, "key" will toast the key_value[1,3,4,11] and value will print the names[West bengal,Himachal Pradesh,Maharashtra,Queensland].
JSONObject list_object = inner_json_object.getJSONObject("");
for (String key : iterate(list_object.keys()))
{
// here key will be containing your OBJECT NAME YOU CAN SET IT IN TEXTVIEW.
Toast.makeText(Activity.this, ""+key, Toast.LENGTH_SHORT).show();
String value = bank_list_object.optString(key);
}`
private <T> Iterable<T> iterate(final Iterator<T> i){
return new Iterable<T>() {
#Override
public Iterator<T> iterator() {
return i;
}
};
}
I have a switch as shown below.
I enter the League's name,and a league is created via a web service.
The switch code is.
aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
openLeague="OPEN";
}else{
openLeague = "CLOSED";
}
}
});
The button code...
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
session = new SessionManager(getApplicationContext());
leagueName = teamTextField.getText().toString();
if (!leagueName.isEmpty()) {
createLeague(leagueName, username, password, start, end, openLeague);
} else {
Toast.makeText(getApplicationContext(),
"Please enter your details!", Toast.LENGTH_LONG)
.show();
}
}
});
The createLeague(...) contains the web service. I am posting six variables. The one I am interested is the open_league.
private void createLeague(final String leagueName, final String username, final String password,final String start,final String end,final String openLeague) {
String tag_json_obj = "json_obj_req";
final HashMap<String, String> postParams = new HashMap<String, String>();
postParams.put("league_name",leagueName);
postParams.put("username",username);
postParams.put("password",password);
postParams.put("league_start",start);
postParams.put("league_finish",end);
postParams.put("open_league",openLeague);
Response.Listener<JSONObject> listener;
Response.ErrorListener errorListener;
final JSONObject jsonObject = new JSONObject(postParams);
JsonObjectRequest jsonObjReq = new JsonObjectRequest(AppConfig.URL_CREATE_LEAGUE, jsonObject,
new com.android.volley.Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("TAG", response.toString());
try {
if (response.getString("status").equals("success")){
Intent i = new Intent(CreateLeague.this, League.class);
startActivity(i);
finish();
}
} catch (JSONException e) {
Log.e("TAG", e.toString());
}
//pDialog.dismiss();
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//VolleyLog.d("TAG", "Error: " + error.getMessage());
//pDialog.dismiss();
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
// VolleySingleton.getInstance(getApplicationContext()).addToRequestQueue(jsonObjRequest);
}
I put a breakpoint before this line
sonObjectRequest jsonObjReq = new JsonObjectRequest(AppConfig.URL_CREATE_LEAGUE, jsonObject,
new com.android.volley.Response.Listener<JSONObject>()
to check the json I am sending. So when the switch is open I get.
{
"league_start":"28-07-2015 09:37:43",
"username":"cerberus_30#gmail.com",
"league_finish":"11-08-2015 09:37:43",
"league_name":"Samsung League",
"password":"larissa",
"open_league":"OPEN"
}
You see the open_league json variable is open. However when the switch is closed,the open_league variable is null! Why is this? I have put in my switch listener the open_league to be "OPEN" when it is on when CLOSED when it is OFF. Thanks.
Your mistake is simple, just fix this,
open_league = "CLOSED";
You haven't initialized the variable but is trying to use it.
When the Switch is opened there is no problem, as the variable has been assigned to "OPEN"
But when you are trying to use it in the closed state, you are getting null values as the variable haven't been initialized
Always remember to initialize the variables to the default values in this kind of scenarios. In your case the default value is "CLOSED" to just initialize it to "CLOSED".