SharedPreferences on a null object reference - android

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

Related

How to call more than one api in single activity by making separate class for all volley operations

I have created a separate class in which I have defined all about volley and in another activity, I have directly pass URL, CONTEXT and Get Response...
but in my NavDrawerActivity.java how do I call the subCategoryJSON(); method without writing my volley code again as I have done with mainCategoryJSON(); method in which I just simply pass the URL, method type.
Also is this a correct approach I am doing or there need to be some modification in the code, what I want is that wherever I am using API in my project and using volley for it, I don't have to write code again and again just simply pass the URL,method type
VolleyResponseListener.java
public interface VolleyResponseListener {
void onResponse(String response, String tag);
void onError(VolleyError error, String tag);
}
CustomStringRequestVolley.java
public class CustomStringRequestVolley {
private String url;
private String tag;
Context ctx;
private VolleyResponseListener volleyResponseListener;
public CustomStringRequestVolley(String url, String tag,Context ctx,VolleyResponseListener volleyResponseListener){
this.url = url;
this.tag = tag;
this.ctx=ctx;
this.volleyResponseListener = volleyResponseListener;
sendRequest();
}
private void sendRequest() {
final ProgressDialog pDialog = new ProgressDialog(ctx);
pDialog.setMessage("Loading ...");
pDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET,url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("catresponse", "response " + response);
if (pDialog.isShowing()) {
pDialog.dismiss();
}
volleyResponseListener.onResponse(response, tag);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
VolleySingleton.getInstance(ctx).addToRequestQueue(stringRequest);
}
}
NavDrawerActivity.java
public class NavDrawerActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, VolleyResponseListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nav_drawer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mainCategoryJSON();
subCategoryJSON();
}
private void mainCategoryJSON() {
CustomStringRequestVolley request1 = new CustomStringRequestVolley(URLs.categoryURL, "TAG1", this, this);
}
#Override
public void onResponse(String response, String tag) {
switch (tag) {
case "TAG1":
try {
Log.i("Responseeeeeezaq :", response.toString() + " " + tag);
JSONObject obj = new JSONObject(response);
JSONArray productArray = obj.getJSONArray("categories");
for (int i = 0; i < productArray.length(); i++) {
JSONObject productObject = productArray.getJSONObject(i);
CategoryModelClass categoryModelClass = new CategoryModelClass();
categoryModelClass.setCategoryID(productObject.getInt("Category-Id"));
categoryModelClass.setCategoryName(productObject.getString("Category-Name"));
categoryModelClass.setCategoryImg(productObject.getString("Category-Image"));
categoryArrayList.add(categoryModelClass);
Log.d("zpuyi", String.valueOf(categoryArrayList));
}
categoryAdapter.notifyDataSetChanged();
} catch (Exception e) {
e.printStackTrace();
}
break;
}
}
#Override
public void onError(VolleyError error, String tag) {
VolleyLog.e("Error: ", error.getMessage());
}
private void subCategoryJSON() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, URLs.subcategoryURL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("subcategoryJsonResponse", response.toString());
try {
JSONObject obj = new JSONObject(response);
JSONArray productArray = obj.getJSONArray("sub-categories");
for (int i = 0; i < productArray.length(); i++) {
JSONObject productObject = productArray.getJSONObject(i);
SubCategoryModelClass subCategoryModelClass = new SubCategoryModelClass();
subCategoryModelClass.setSubCategory_Id(productObject.getInt("Subcategories-Id"));
subCategoryModelClass.setCat_id(productObject.getInt("categories-Id"));
subCategoryModelClass.setSubCategory_Name(productObject.getString("Subcategories-Name"));
subCategoryModelClass.setSubCategory_Img(productObject.getString("Subcategories-Image"));
subCategoryModelClassList.add(subCategoryModelClass);
Log.d("subCategoryArraylist", String.valueOf(subCategoryModelClassList));
}
for (int i = 0; i < subCategoryModelClassList.size(); i++) {
subcategory_id = subCategoryModelClassList.get(i).getSubCategory_Id();
category_id = subCategoryModelClassList.get(i).getCat_id();
subcategory_name = subCategoryModelClassList.get(i).getSubCategory_Name();
// subcategory_desc = subCategoryModelClassList.get(i).getSubCategory_Desc();
subcategory_image = subCategoryModelClassList.get(i).getSubCategory_Img();
Log.d("fdsaff", subcategory_image);
SQLiteDatabase database = dbHelper.getWritableDatabase();
dbHelper.insertSubCategoryProduct(subcategory_id, category_id, subcategory_name, "https://www.ecrm.sample.in/app/img/"+subcategory_image, database);
dbHelper.close();
}
subCategoryAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
VolleySingleton.getInstance(getApplicationContext()).addToRequestQueue(stringRequest);
}
}
You have written the answer correctly but you are not implementing the written custom volley class code in the activity class.
First Define the interface class for the Volley as below,
Now implement the volley interface in the java class where you have written the custom volley class as below:
CustomStringRequestVolley.java
public class CustomStringRequestVolley implements volleyCallback {
public Context context;
public CustomStringRequestVolley(Context context) {
this.context = context;
}
public interface volleyCallback {
void onSuccess(String result);
void onError(String error);
}
public void callGetServer(String URL, final
volleyCallback callback){
if (!checkInternetConnection(context)) {
showNoInternetDialogue(context);
return;
}
RequestQueue requestQueue = Volley.newRequestQueue(context);
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL, new
Response.Listener<String>() {
#Override
public void onResponse(String response) {
callback.onSuccess(response);
}
}, error -> {
if (error.networkResponse == null){
if (error.getClass().equals(TimeoutError.class)){
Toast.makeText(context, "Timeout.Please try again",
Toast.LENGTH_SHORT).show();
}else if (error.getClass().equals(NoConnectionError.class)){
Toast.makeText(context, "Timeout.Please try again", Toast.LENGTH_SHORT).show();
}else if (error.getClass().equals(NetworkError.class)) {
Toast.makeText(context, "Network Error.Please try again", Toast.LENGTH_SHORT).show();
}else if (error.getClass().equals(ParseError.class)){
Toast.makeText(context, "Parse error", Toast.LENGTH_SHORT).show();
}else if (error.getClass().equals(ServerError.class)){
Toast.makeText(context, "Server Error.Please try again", Toast.LENGTH_SHORT).show();
}
else {
parseVolleyError(error);
}
}
}
) {
#Override
protected Map<String, String> getParams() {
return new HashMap<>();
}
#Override
public Map<String, String> getHeaders() {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/x-www-form-urlencoded");
return headers;
}
};
//setting up the retry policy for slower connections
int socketTimeout = 120000;//120000 milli seconds - change to what you want
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
requestQueue.add(stringRequest);
}
}
Now use this Custom volley class in every activity you required. It reduces you
boilerplate code
NavDrawerActivity.java
CustomStringRequestVolley customStringRequestVolley;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_starting_point_navigation);
customStringRequestVolley = new CustomStringRequestVolley(this);
}
private void subCategoryJSON() {
customStringRequestVolley.callGetServer(URLs.subcategoryURL,new volleyCallback() {
#Override
public void onSuccess(String result) {
try {
JSONObject obj = new JSONObject(response);
JSONArray productArray = obj.getJSONArray("sub-categories");
for (int i = 0; i < productArray.length(); i++) {
JSONObject productObject = productArray.getJSONObject(i);
SubCategoryModelClass subCategoryModelClass = new SubCategoryModelClass();
subCategoryModelClass.setSubCategory_Id(productObject.getInt("Subcategories-Id"));
subCategoryModelClass.setCat_id(productObject.getInt("categories-Id"));
subCategoryModelClass.setSubCategory_Name(productObject.getString("Subcategories-Name"));
subCategoryModelClass.setSubCategory_Img(productObject.getString("Subcategories-Image"));
subCategoryModelClassList.add(subCategoryModelClass);
Log.d("subCategoryArraylist", String.valueOf(subCategoryModelClassList));
}
for (int i = 0; i < subCategoryModelClassList.size(); i++) {
subcategory_id = subCategoryModelClassList.get(i).getSubCategory_Id();
category_id = subCategoryModelClassList.get(i).getCat_id();
subcategory_name = subCategoryModelClassList.get(i).getSubCategory_Name();
// subcategory_desc = subCategoryModelClassList.get(i).getSubCategory_Desc();
subcategory_image = subCategoryModelClassList.get(i).getSubCategory_Img();
Log.d("fdsaff", subcategory_image);
SQLiteDatabase database = dbHelper.getWritableDatabase();
dbHelper.insertSubCategoryProduct(subcategory_id, category_id, subcategory_name, "https://www.ecrm.sample.in/app/img/"+subcategory_image, database);
dbHelper.close();
}
subCategoryAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onError(String error) {
//show error code
}
});
}
Let me know after you try this #Abhishek

I try to login but it does not run the whole query

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();
}
}

Can we change the backgroud color of Linearlayout of Fragmet A from another Fragment B ? without getting error

I want change the background color of of LinearLayout of Fragment A from Fragment B .These fragments are in same viewpager in sliding tabs.
The data of both fragment are dynamically changed from server.Here I have to click a textview of Fragment B then its linearlayout's color be changed manually(POST method) but due to net slow the background color of Fragment A (Because the textview of Fragment A is already selected so its color is already set.) is not removed from LinearLayout(GET method). But after sometime it will disappear .
So I want to set color manually till color is to be loaded. To make good user interface while clicking on textview for selection package.
MinPackageFragment
public class MinPackageFragment extends Fragment {
ConnectionDetector connectionDetector = new ConnectionDetector(getActivity());
private View mView;
private TextView nepal_minimum_package_price, nepal_minimum_package_plan;
private LinearLayout nepal_minimum_package_linearlayout;
private String GET_NEPAL_MIN_PACKAGE_URL;
private String CHECK_CURRENT_PACKAGE_URL;
private WebView webview;
private String minPackagePrice;
private String minPackageItem;
private int THIS_ID;
private String CHOOSE_PACKAGE;
private int currentId;
private int CURRENT_PACKAGE_ID;
private ProgressDialog mProgressDialog;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.fragment_min_package, container, false);
SharedPreferences pref = this.getActivity().getSharedPreferences("MyPref", MODE_PRIVATE);
String token = pref.getString("token1", "empty");
THIS_ID = 1001;
GET_NEPAL_MIN_PACKAGE_URL = "http://insocify.com/api/packages";
CHECK_CURRENT_PACKAGE_URL = "http://insocify.com/api/user/packages?token=" + token;
CHOOSE_PACKAGE = "http://insocify.com/api/user/package/choose/1001?token=" + token;
webview = (WebView) mView.findViewById(R.id.minimumNepaliListWebView);
webview.getSettings().setJavaScriptEnabled(true);
if (getActivity() != null) {
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.setMessage("Loading...");
}
showDialog();
nepal_minimum_package_price = mView.findViewById(R.id.nepal_minimum_package_price);
nepal_minimum_package_plan = mView.findViewById(R.id.nepal_minimum_package_plan);
nepal_minimum_package_linearlayout = mView.findViewById(R.id.nepal_minimum_package_linearlayout);
nepal_minimum_package_plan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// I want change here the background color of linearlayout of another fragment but getting error
showDialog();
choosePackage();
nepal_minimum_package_plan.setText("Your Plan");
nepal_minimum_package_linearlayout.setBackgroundResource(R.drawable.background_square_selected);
}
});
setContentFromServer();
SharedPreferences pref123 = getActivity().getSharedPreferences("minnepaldata", MODE_PRIVATE);
String avgprice = pref123.getString("mineprice", minPackagePrice);
String avgitems = pref123.getString("minitems", minPackageItem);
nepal_minimum_package_price.setText(avgprice);
webview.loadData(avgitems, "text/html; charset=utf-8", "UTF-8");
chooseNepaliPackage();
if (CURRENT_PACKAGE_ID == THIS_ID) {
nepal_minimum_package_plan.setText("Your Plan");
nepal_minimum_package_linearlayout.setBackgroundResource(R.drawable.background_square_selected);
}
return mView;
}
private void choosePackage() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, CHOOSE_PACKAGE, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject responceData = new JSONObject(response);
int status = responceData.getInt("status");
if (status == 1) {
JSONObject data = responceData.getJSONObject("data");
Log.v("mydata1", data + "");
String currentDataStr = data.getString("current");
Log.v("currentStr", "" + currentDataStr);
JSONObject currentData = new JSONObject(currentDataStr);
if (currentData != null) {
currentId = currentData.getInt("id");
if (currentId == 1001) {
nepal_minimum_package_plan.setText("Your Plan");
nepal_minimum_package_linearlayout.setBackgroundResource(R.drawable.background_square_selected);
nepal_minimum_package_plan.setEnabled(false);
hideDialog();
nepal_minimum_package_linearlayout.setVisibility(View.VISIBLE);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hideDialog();
Toast.makeText(getActivity(), "Please check your network.", Toast.LENGTH_SHORT).show();
nepal_minimum_package_linearlayout.setVisibility(View.VISIBLE);
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
private void setContentFromServer() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, GET_NEPAL_MIN_PACKAGE_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject responceData = new JSONObject(response);
JSONArray jsonNepal = responceData.getJSONArray("1");
JSONObject silver = jsonNepal.getJSONObject(0);
JSONObject gold = jsonNepal.getJSONObject(1);
JSONObject platinum = jsonNepal.getJSONObject(2);
String name = silver.getString("name");
minPackagePrice = silver.getString("price");
minPackageItem = silver.getString("includes");
if (getActivity() != null) {
SharedPreferences pref123 = getActivity().getSharedPreferences("minnepaldata", MODE_PRIVATE);
SharedPreferences.Editor editor = pref123.edit();
editor.putString("mineprice", minPackagePrice);
editor.putString("minitems", minPackageItem);
editor.apply();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "Please check your network.", Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
private void chooseNepaliPackage() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, CHECK_CURRENT_PACKAGE_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject responceData = new JSONObject(response);
hideDialog();
int status = responceData.getInt("status");
if (status == 1) {
JSONObject data = responceData.getJSONObject("data");
String currentDataStr = data.getString("current");
Log.v("currentStr", "" + currentDataStr);
JSONObject currentData = new JSONObject(currentDataStr);
if (currentData != null) {
CURRENT_PACKAGE_ID = currentData.getInt("id");
if (CURRENT_PACKAGE_ID == 1001) {
nepal_minimum_package_plan.setText("Your Plan");
nepal_minimum_package_linearlayout.setBackgroundResource(R.drawable.background_square_selected);
nepal_minimum_package_plan.setEnabled(false);
nepal_minimum_package_linearlayout.setVisibility(View.VISIBLE);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hideDialog();
if (getActivity() != null) {
Toast.makeText(getActivity(), "Please check your network.", Toast.LENGTH_SHORT).show();
}
nepal_minimum_package_linearlayout.setVisibility(View.VISIBLE);
}
});
if (getActivity() != null) {
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
}
public void showDialog() {
if (mProgressDialog != null && !mProgressDialog.isShowing())
mProgressDialog.show();
}
public void hideDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing())
mProgressDialog.dismiss();
}
}
MaxPackageFragment
public class MaxPackageFragment extends Fragment {
ConnectionDetector connectionDetector = new ConnectionDetector(getActivity());
private WebView maximumNepaliListWebView;
private View maxView;
private TextView nepal_maximum_package_plan, nepal_maximum_package_price;
private String GET_NEPAL_PACKAGE_URL;
private String maxPackageprice;
private String maxPackageitems;
private String CHECK_CURRENT_PACKAGE_URL;
private LinearLayout nepal_maximum_package_linearlayout;
private String CHOOSE_PACKAGE;
private int THIS_ID;
private int currentId;
private int CURRENT_PACKAGE_ID;
private ProgressDialog mProgressDialog;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
maxView = inflater.inflate(R.layout.fragment_max_package, container, false);
SharedPreferences pref = this.getActivity().getSharedPreferences("MyPref", MODE_PRIVATE);
String token = pref.getString("token1", "empty");
THIS_ID = 1003;
GET_NEPAL_PACKAGE_URL = "http://insocify.com/api/packages";
CHECK_CURRENT_PACKAGE_URL = "http://insocify.com/api/user/packages?token=" + token;
CHOOSE_PACKAGE = "http://insocify.com/api/user/package/choose/1003?token=" + token;
nepal_maximum_package_linearlayout = maxView.findViewById(R.id.nepal_maximum_package_linearlayout);
maximumNepaliListWebView = maxView.findViewById(R.id.maximumNepaliListWebView);
if (getActivity() != null) {
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.setMessage("Loading...");
}
showDialog();
nepal_maximum_package_plan = maxView.findViewById(R.id.nepal_maximum_package_plan);
nepal_maximum_package_price = maxView.findViewById(R.id.nepal_maximum_package_price);
nepal_maximum_package_plan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDialog();
// I want change here the background color of linearlayout of another fragment but getting error
choosePackage();
nepal_maximum_package_plan.setText("Your Plan");
nepal_maximum_package_linearlayout.setBackgroundResource(R.drawable.background_square_selected);
}
});
setItemToLayout();
SharedPreferences pref1 = getActivity().getSharedPreferences("maxnepaldata", MODE_PRIVATE);
String maxprice = pref1.getString("maxprice", maxPackageprice);
String maxitems = pref1.getString("maxitems", maxPackageitems);
nepal_maximum_package_price.setText(maxprice);
maximumNepaliListWebView.loadData(maxitems, "text/html; charset=utf-8", "UTF-8");
chooseNepaliPackage();
if (CURRENT_PACKAGE_ID == THIS_ID) {
nepal_maximum_package_plan.setText("Your Plan");
nepal_maximum_package_linearlayout.setBackgroundResource(R.drawable.background_square_selected);
}
return maxView;
}
private void choosePackage() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, CHOOSE_PACKAGE, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject responceData = new JSONObject(response);
int status = responceData.getInt("status");
if (status == 1) {
JSONObject data = responceData.getJSONObject("data");
String currentDataStr = data.getString("current");
JSONObject currentData = new JSONObject(currentDataStr);
if (currentData != null) {
currentId = currentData.getInt("id");
if (currentId == 1003) {
nepal_maximum_package_plan.setText("Your Plan");
nepal_maximum_package_linearlayout.setBackgroundResource(R.drawable.background_square_selected);
nepal_maximum_package_plan.setEnabled(false);
hideDialog();
}
}
}
else {
JSONArray errordata = responceData.getJSONArray("errors");
String errormessage = errordata.getJSONObject(0).getString("message");
Toast.makeText(getActivity(), "" + errormessage, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hideDialog();
Toast.makeText(getActivity(), "Please check your network.", Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
private void setItemToLayout() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, GET_NEPAL_PACKAGE_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject responceData = new JSONObject(response);
Log.v("responceData", "onResponse: " + responceData);
JSONArray jsonNepal = responceData.getJSONArray("1");
JSONObject silver = jsonNepal.getJSONObject(0);
JSONObject gold = jsonNepal.getJSONObject(1);
JSONObject platinum = jsonNepal.getJSONObject(2);
String name = platinum.getString("name");
maxPackageprice = platinum.getString("price");
maxPackageitems = platinum.getString("includes");
if (getActivity() != null) {
SharedPreferences pref1 = getActivity().getSharedPreferences("maxnepaldata", MODE_PRIVATE);
SharedPreferences.Editor editor = pref1.edit();
editor.putString("maxprice", maxPackageprice);
editor.putString("maxitems", maxPackageitems);
editor.apply();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "Please check your network.", Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
private void chooseNepaliPackage() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, CHECK_CURRENT_PACKAGE_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject responceData = new JSONObject(response);
hideDialog();
int status = responceData.getInt("status");
if (status == 1) {
JSONObject data = responceData.getJSONObject("data");
String currentDataStr = data.getString("current");
Log.v("currentStr", "" + currentDataStr);
JSONObject currentData = new JSONObject(currentDataStr);
if (currentData != null) {
CURRENT_PACKAGE_ID = currentData.getInt("id");
if (CURRENT_PACKAGE_ID ==1003){
nepal_maximum_package_plan.setText("Your Plan");
nepal_maximum_package_linearlayout.setBackgroundResource(R.drawable.background_square_selected);
nepal_maximum_package_plan.setEnabled(false);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
hideDialog();
if (getActivity() != null) {
Toast.makeText(getActivity(), "Please check your network.", Toast.LENGTH_SHORT).show();
}
}
});
if (getActivity() != null) {
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
}
public void showDialog() {
if (mProgressDialog != null && !mProgressDialog.isShowing())
mProgressDialog.show();
}
public void hideDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing())
mProgressDialog.dismiss();
}
}
There are three fragments in same viewpager of fragment,within three tabs.
If your fragment is in same Activity, You can use the FragmentManager. findFragmentById(int id) which return by invoke Fragment.getFragmentManager() method to retrieve the reference of another fragment
then invoke the method to change the background color

How to update the user data instantly in my application?

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

Android Volley Request Identity onErrorResponse Section

public void getTestDats(String unique_id) {
final String tag = "testList";
String url = Constants.BASE_URL + "test_module.php";
Map<String, String> params = new HashMap<String, String>();
params.put("user_id", SharedPreferenceUtil.getString(Constants.PrefKeys.PREF_USER_ID, "1"));
params.put("unique_id", unique_id);//1,2,3,4,5
DataRequest loginRequest = new DataRequest(Method.POST, url, params, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
switch (response.optInt("unique_id")) {
case 1:
//task 1
break;
case 2:
//task 2
break;
default:
//nothing
}
}
}, new ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//I want to know which unique_id request is failed
}
});
loginRequest.setRetryPolicy(new DefaultRetryPolicy(20000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(loginRequest, tag);
}
I'm trying to identity which request is failed with having unique_id.
I'm calling getTestDats("1") function with unique_id. And function called 10 times and all the api call in addToRequestQueue.
When API go into Success part its working as per code.
But when API go into Error part I didn't identity the request.
Is there any way to know my request param so I can retry with particular unique_id request.
set a field in loginRequest and in onErrorResponse access the field like loginRequest.getUniqueId()
Alternatively, create a seperate class that implements Response.Listener and ErrorListener
Response Listener class:
public class MyReponseListener implements Response.Listener<JSONOBject>{
private long uniqId;
public MyResponseListener(long uniqId){
this.uniqId = uniqId;
}
#Override
public void onResponse(JSONObject response) {
System.out.println("response for uniqId " + uniqId);
// do your other chit chat
}
}
ErrorListener class:
public class MyErrorListener implements ErrorListener{
private long uniqId;
public MyErrorListener(long uniqId){
this.uniqId = uniqId;
}
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("Error for uniqId : " + uniqId);
}
}
Now call it like:
DataRequest loginRequest = new DataRequest(Method.POST, url, params, new MyResponeListener(uniqId), new MyErrorListener(uniqId));
Now if you want some code of the calling class to be accessible in the ErrorListener class then do the following:
1. In calling class put the codes you want to access in methods
2. Create an interface with those method
3. The calling class will implement that interface
4. Pass the interface to constructor of the MyErrorListener or MyResponseListener
for example an activity calls the volley request, on error you want to show a message.
put that show error codes in a method:
public void showMessage(int errorCode){
//message according to code
}
now create an interface
public interface errorMessageInterface{
void showMessage(int errorCode);
}
the activity will implement errorMessageInterface and pass this to the constructor of MyErrorListener and save it in a field.
Inside onErrorResponse, you will call
field.showMessage()
You can parse error response in the same way as you parse success response. I use similar solution in my projects.
public class VolleyErrorParser {
private VolleyError mError;
private String mBody;
private int mUniqueId = -1;
public VolleyErrorParser(VolleyError e){
mError = e;
parseAnswer();
parseBody();
}
private void parseBody() {
if (mBody==null)
return;
try{
JSONObject response = new JSONObject(mBody);
mUniqueId = response.getOptInt("unique_id");
}catch (JSONException e){
e.printStackTrace();
}
}
private void parseAnswer() {
if (mError!=null&&mError.networkResponse!=null&&mError.networkResponse.data!=null){
mBody = new String(mError.networkResponse.data);
}
}
public String getBody(){
return mBody;
}
public int getUniqueId(){
return mUniqueId;
}
}
Use:
...
, new ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
int id = new VolleyErrorParse(error).getUniqueId();
switch (id) {
case -1:
//unique id not found in the answer
break;
case 1:
//task 1
break;
case 2:
//task 2
break;
default:
//nothing
}
}
}
...
Just add this code to identify which type of error you are facing.Add this in your onError() method :
if (error instanceof TimeoutError) {
Log.e(TAG, "TimeoutError");
} else if (error instanceof NoConnectionError) {
Log.e(TAG,"tNoConnectionError");
} else if (error instanceof AuthFailureError) {
Log.e(TAG,"AuthFailureError");
} else if (error instanceof ServerError) {
Log.e(TAG,"ServerError");
} else if (error instanceof NetworkError) {
Log.e(TAG,"NetworkError");
} else if (error instanceof ParseError) {
Log.e(TAG,"ParseError");
}
Log the unique_id before making a request i.e; after params.put("unique_id", unique_id);//1,2,3,4,5. And also once you get the response in onResponse() method. And cross verify what exactly is happening.
most of the solutions here will "work" but they are too complex .. for me :)
here is the simplest option with least code change I can think of:
...
final Map<String, String> params = new HashMap<String, String>();
params.put("user_id", SharedPreferenceUtil.getString(Constants.PrefKeys.PREF_USER_ID, "1"));
params.put("unique_id", unique_id);//1,2,3,4,5
DataRequest loginRequest = new DataRequest(Method.POST, url, params, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
switch (params.get("unique_id")) {
case 1:
//task 1
break;
case 2:
//task 2
break;
default:
//nothing
}
}
...
All the above answers seem to be correct.But i recommend you to do this in an optimized way. If you will add error handling code in all onErrorResponse() then it will create duplication. So create a seperate method in Utils or some other class and just call that method by passing error object to the method. Also you can inflate some dialog or toast to display an error message.
public static void handleError(final Context context, String alertTitle,
Exception exception, String logTag) {
if (context != null) {
if (exception instanceof TimeoutError)
message = context.getString(R.string.TimeoutError);
else if (exception instanceof NoConnectionError)
message = context.getString(R.string.NoConnectionError);
else if (exception instanceof AuthFailureError)
message = context.getString(R.string.AuthFailureError);
else if (exception instanceof ServerError)
message = context.getString(R.string.ServerError);
else if (exception instanceof NetworkError)
message = context.getString(R.string.NetworkError);
else if (exception instanceof ParseError)
message = context.getString(R.string.ParseError);
message = exception.getMessage();
DialogHelper.showCustomAlertDialog(context, null,
alertTitle, message, "ok",
new OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
}
}, null, null);
}
}
I think you have to make one conman method on Base class. As given bellow which I used in my code for calling php web api
/**
* <h1> Use for calling volley webService </h1>
*
* #param cContext Context of activity from where you call the webService
* #param mMethodType Should be POST or GET
* #param mMethodname Name of the method you want to call
* #param URL Url of your webService
* #param mMap Key Values pairs
* #param initialTimeoutMs Timeout of webService in milliseconds
* #param shouldCache Web Api response are stored in catch(true) or not(false)
* #param maxNumRetries maximum number in integer for retries to execute webService
* #param isCancelable set true if you set cancel progressDialog by user event
* #param aActivity pass your activity object
*/
public void callVolley(final Context cContext, String mMethodType, final String mMethodname, String URL,
final HashMap<String, String> mMap, int initialTimeoutMs, boolean shouldCache, int maxNumRetries,
Boolean isProgressDailogEnable, Boolean isCancelable, final Activity aActivity) {
mMap.put("version_key_android",BuildConfig.VERSION_NAME+"");
if (!isOnline(cContext)) {
//showErrorDailog(aActivity, Constant.PleaseCheckInternetConnection, R.drawable.icon);
} else {
StringRequest jsObjRequest;
int reqType = 0;
String RequestURL = URL.trim();
queue = Volley.newRequestQueue(cContext);
if (isProgressDailogEnable) {
customLoaderDialog = new CustomLoaderDialog(cContext);
customLoaderDialog.show(isCancelable);
customLoaderDialog.dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
// finish();
}
});
}
if (mMethodType.trim().equalsIgnoreCase("GET"))
reqType = com.android.volley.Request.Method.GET;
else if (mMethodType.trim().equalsIgnoreCase("POST"))
reqType = com.android.volley.Request.Method.POST;
if (RequestURL.equals(""))
RequestURL = Constant.BASE_URL;
else
RequestURL = URL;
if (Constant.d) Log.d("reqType", reqType + "");
jsObjRequest = new StringRequest(reqType, RequestURL, new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (Constant.d) Log.d("response==>" + mMethodname, "" + response);
if (customLoaderDialog != null) {
try {
customLoaderDialog.hide();
} catch (Exception e) {
e.printStackTrace();
}
}
if (response == null || response.length() == 0) {
IVolleyRespose iVolleyRespose = (IVolleyRespose) aActivity;
iVolleyRespose.onVolleyResponse(404, response, mMethodname);
} else {
JSONObject json_str;
try {
json_str = new JSONObject(response);
int status = json_str.getInt("status");
if (status == 100) {
AlertDialog alertDialog = new AlertDialog.Builder(aActivity).create();
alertDialog.setTitle(getResources().getString(R.string.app_name));
alertDialog.setMessage(json_str.getString("message") + "");
alertDialog.setCancelable(false);
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
try {
Intent viewIntent =
new Intent("android.intent.action.VIEW",
Uri.parse(Constant.playStoreUrl));
startActivity(viewIntent);
}catch(Exception e) {
Toast.makeText(getApplicationContext(),"Unable to Connect Try Again...",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
dialog.dismiss();
// return;
}
});
alertDialog.show();
} else {
IVolleyRespose iVolleyRespose = (IVolleyRespose) aActivity;
iVolleyRespose.onVolleyResponse(RESPONSE_OK, response, mMethodname);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError arg0) {
// TODO Auto-generated method stub
IVolleyRespose iVolleyError = (IVolleyRespose) aActivity;
iVolleyError.onVolleyError(404, "Error", mMethodname);
if (customLoaderDialog != null) {
customLoaderDialog.hide();
}
}
}) {
#Override
protected Map<String, String> getParams() {
String strRequest = "";
try {
strRequest = getWebservicejsObjRequestforvolley(mMethodname, mMap);
if (Constant.d) Log.d("Request==>", strRequest + "");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Map<String, String> params = new HashMap<>();
params.put("json", strRequest);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
};
//if(Constant.d) Log.d("Request==>", jsObjRequest+"");
jsObjRequest.setTag(mMethodname);
jsObjRequest.setShouldCache(shouldCache);
jsObjRequest.setRetryPolicy(new DefaultRetryPolicy(initialTimeoutMs, maxNumRetries, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(jsObjRequest);
}
}
Please observe that here we make one interface for getting response and error.
Using Interface you can get method name on both response and error so you can identify which web api is successfully called and which give error. You should extend base class to Activity and also implement Interface which you made for getting volley response. Here in above code I show how to bind interface to activity. when you call api by passing activity context.

Categories

Resources