I am successfully deleting an Item from the recyclerView. The Items gets deleted successfully, but the recyclerView is not refreshed after the delete operation.
This is my Adapter code :
holder.removeProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences myPrefs = context.getSharedPreferences("loginToken", Context.MODE_PRIVATE);
getToken = myPrefs.getString("token", null);
new AlertDialog.Builder(context)
.setTitle("Remove from Cart")
.setMessage("Are you sure you want to remove this Item from cart ?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
deleteDialog = ProgressDialog.show(context, "",
"Please Wait...", true);
final RequestQueue requestQueue = Volley.newRequestQueue(context);
StringRequest request = new StringRequest(Request.Method.POST,
REMOVE_CART_URL + "?token=" + getToken + "&product_id=" + cartModel.getProductid()
, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String message = jsonObject.getString("success");
if (message.equals("true")) {
Toast.makeText(context, "Item Deleted Successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Some error occurred, Please try again", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("Delete error", e.getLocalizedMessage());
}
deleteDialog.dismiss();
notifyDataSetChanged();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "Some error occurred, Please try again", Toast.LENGTH_SHORT).show();
deleteDialog.dismiss();
}
});
requestQueue.add(request);
}
})
// A null listener allows the button to dismiss the dialog and take no further action.
.setNegativeButton(android.R.string.no, null)
.setIcon(android.R.drawable.ic_delete)
.show();
}
});
The Item after deletion stays there until I close the App and reopen. How do I fix this , so I dont have to reopen app everytime.
Instead of notifyDataSetChanged() write this code:
if (yourAdapterList.size() > 0) {
ourAdapterList.remove(position);
notifyItemRemoved(position);
}
Related
I am trying to make a social app .. and I want when the user clicks the edit category database should be updated to the new value .. but it is like static not changing to new value .. I don't know the problem in logic or in the code ..
private void showCategoryUpdateDialog(String Key) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("تغيير " + Key);
LinearLayout linearLayout = new LinearLayout(getActivity());
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setPadding(15, 10, 15, 10);
RadioButton radioButton = new RadioButton(getActivity());
radioButton.setText("علمي علوم");
RadioButton radioButton2 = new RadioButton(getActivity());
radioButton2.setText("علمي رياضة");
RadioButton radioButton3 = new RadioButton(getActivity());
radioButton3.setText("أدبي");
linearLayout.addView(radioButton);
linearLayout.addView(radioButton2);
linearLayout.addView(radioButton3);
builder.setView(linearLayout);
builder.setPositiveButton("Update", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String value = radioButton.getText().toString().trim();
String value2 = radioButton2.getText().toString().trim();
String value3 = radioButton3.getText().toString().trim();
if (!TextUtils.isEmpty(value)) {
pd.show();
HashMap<String, Object> result = new HashMap<>();
result.put(Key, value);
databaseReference.child(user.getUid()).updateChildren(result)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
pd.dismiss();
Toast.makeText(getActivity(), "Updated...", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
pd.dismiss();
Toast.makeText(getActivity(), "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(getActivity(), "Please enter " + Key, Toast.LENGTH_SHORT).show();
}
if (!TextUtils.isEmpty(value2)) {
pd.show();
HashMap<String, Object> result2 = new HashMap<>();
result2.put(Key, value2);
databaseReference.child(user.getUid()).updateChildren(result2)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
pd.dismiss();
Toast.makeText(getActivity(), "Updated...", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
pd.dismiss();
Toast.makeText(getActivity(), "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(getActivity(), "Please enter " + Key, Toast.LENGTH_SHORT).show();
}
if (!TextUtils.isEmpty(value3)) {
pd.show();
HashMap<String, Object> result3 = new HashMap<>();
result3.put(Key, value3);
databaseReference.child(user.getUid()).updateChildren(result3)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
pd.dismiss();
Toast.makeText(getActivity(), "Updated...", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
pd.dismiss();
Toast.makeText(getActivity(), "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(getActivity(), "Please enter " + Key, Toast.LENGTH_SHORT).show();
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.create().show();
}
In this picture have more details
Emulator
And this GIF from my Database
https://media.giphy.com/media/ZY36QuzJsdXIhIQh7k/giphy.gif
first: make sure that the new value is stored in the database (from the console)
second: after the update is completed onCompleteListener get the data again.
you can listen for this field changes in real-time which could be better than getting the data after every update.
I need help for showing toast and progress dialog inside volley request, and I use a custom adapter file when click on the card will send data with volley, please give better flow or fixing this code.
this is my onBindViewHolder inside adapter file
#Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
final DataPicking task = taskList.get(position);
holder.numberid.setText(task.getNomorid());
holder.nama.setText(task.getNamakonsumen());
holder.rate.setText(task.getRate());
holder.tanggal.setText(task.getTanggal());
holder.salesman.setText(task.getSalesman());
holder.cardList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
new AlertDialog.Builder(view.getContext())
.setTitle("Proses Picking")
.setMessage("Apakah kamu yakin ingin memproses picking data ini?")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String nomorid = taskList.get(position).getNomorid();
PickingActivity picking = new PickingActivity();
picking.kirimData(nomorid);
}})
.setNegativeButton(android.R.string.no, null).show();
}
});
}
and this is kirimData function for send data with volley
public void kirimData(final String nomorid){
// Log.e("ini kirimdata ",nomorid);
// Tag used to cancel the request
String tag_string_req = "req_login";
pDialog.setMessage("Loading ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
Constants.URL_SET_PICKING, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Picking Response: " + response.toString());
//hideDialog();
try {
JSONObject jObj = new JSONObject(response);
Log.e(TAG, "obj: " + jObj.toString());
String error = jObj.getString("status");
Log.e(TAG, "obj: " + error);
// Check for error node in json
if (error.equals("1")) {
// user successfully logged in
// Create login session
mAdapter.notifyDataSetChanged();
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("message");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getBaseContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
/*Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
startActivity(intent);
finish();*/
Log.e(TAG, "Proses Picking Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
"Proses Picking Failed", 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("nomorid", nomorid);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
and this is the error log
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ProgressDialog.setMessage(java.lang.CharSequence)' on a null object reference
at com.sip.gotrack.PickingActivity.kirimData(PickingActivity.java:167)
at com.sip.gotrack.PickingAdapter$1$1.onClick(PickingAdapter.java:69)
please help me for this error
Where is your pDialog being initialized?
Inside kirimData, initialize pDialog like this in the beginning.
pDialog = new ProgressDialog(context);
It seems pDialog is not initialized before this method is called.
My Dialog close
if (status.equals("true")) {
Toast.makeText(context, "" + msg, Toast.LENGTH_LONG).show();
notifyDataSetChanged();
dialog.dismiss();
}
I have used notifyDataSetChanged() but still the Fragment layout is not refreshing or not updating
Adapter.java
holder.txt_payRef_update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (orderlistArrayList.get(position).getPaymentStatus().equals("0")) {
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialog_payment_reference);
Window window = dialog.getWindow();
window.setLayout(Toolbar.LayoutParams.FILL_PARENT, Toolbar.LayoutParams.WRAP_CONTENT);
final TextView txt_orderId = (TextView) dialog.findViewById(R.id.txt_orderId);
final TextView txt_total_amount = (TextView) dialog.findViewById(R.id.txt_total_amount);
final TextView txt_doPayment = (TextView) dialog.findViewById(R.id.txt_doPayment);
final TextView edtxt_order_referenece_id = (EditText) dialog.findViewById(R.id.edtxt_order_referenece_id);
txt_orderId.setText("Order ID " + orderlistArrayList.get(position).getOrderId());
txt_total_amount.setText("Total Due Amount " + (context.getResources().getString(R.string.Rs)) + orderlistArrayList.get(position).getTotalPrice());
edtxt_order_referenece_id.setText(orderlistArrayList.get(position).getPayRef());
txt_doPayment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String Reference_Id = edtxt_order_referenece_id.getText().toString();
if (!Reference_Id.equalsIgnoreCase("")) {
DoUpdatePaymentRef(orderlistArrayList.get(position).getOrderId(), Reference_Id);
// Toast.makeText(context, "Done!!", Toast.LENGTH_LONG).show();
// dialog.dismiss();
} else {
Toast.makeText(context, "Please Put Order Reference ID!!", Toast.LENGTH_LONG).show();
}
}
private void DoUpdatePaymentRef(String orderId, String reference_id) {
progress = new ProgressDialog(context);
progress.setMessage("Please Wait..");
progress.setCancelable(false);
progress.show();
JSONObject params = new JSONObject();
try {
params.put("orderId", orderId);
params.put("payRef", reference_id);
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("Params orderPayRefUpdate--> " + params.toString());
System.out.println(" URL_orderPayRefUpdate--> " + Constant.orderPayRefUpdate);
JsonObjectRequest jsonArrayRequest = new JsonObjectRequest(Request.Method.POST, Constant.orderPayRefUpdate, params,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
String status = "";
progress.dismiss();
System.out.println("orderPayRefUpdate Response -->" + response.toString());
try {
JSONObject objStatus = new JSONObject(response
.toString());
status = objStatus.getString("valid");
String msg = objStatus.getString("msg");
if (status != null && !status.equalsIgnoreCase("")) {
if (status.equals("true")) {
Toast.makeText(context, "" + msg, Toast.LENGTH_LONG).show();
// adapter.notifyDataSetChanged();
dialog.dismiss();
} else {
Toast.makeText(context, "" + msg, Toast.LENGTH_LONG).show();
}
}
} catch (JSONException e) {
progress.dismiss();
e.printStackTrace();
//Toast.makeText(PersonalInfo_QRActivity.this, "e." + e.toString(), Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
System.out.println("Error : " + error.toString());
}
});
jsonArrayRequest.setRetryPolicy(new DefaultRetryPolicy(
30000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
VolleySingleton.getInstance(context).getRequestQueue()
.add(jsonArrayRequest);
}
});
dialog.show();
}
}
});
Fragment.java
adapterOrderList = new AdapterOrderList(getActivity(), orderlistArrayList);
adapterOrderList.notifyDataSetChanged();
grid_view_fragment.setAdapter(adapterOrderList);
Once you updated, you should update the values in your orderlistArrayList
For example if you want to update the text that you have entered in this edit text edtxt_order_referenece_id you should get the strign value from the edit text and you should update it in the item position orderlistArrayList.get(position).setPayRef(edtxt_order_referenece_id.getText().toString())
Once you have done you should call the notifyDataSetChanged(); or notifyItemChanged(position);
I am working on my app, till morning it was working fine. I used volley in my app. suddenly it stopped working . I am not able to send request to server and get response. It goes to onErrorResponse method. Following is my snippet code
private void makeJsonArrayRequestCountry() {
showpDialog();
JsonArrayRequest req = new JsonArrayRequest( myorderlist_url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("ress", response.toString());
placeorderlists=new ArrayList<MyOrderModel>();;
if(response.length() > 0)
{
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
MyOrderModel movie = new MyOrderModel();
movie.setOrder_Id(obj.getString("orderID"));
movie.setOrder_Name(obj.getString("packDesc"));
movie.setOrder_Imgpath(obj.getString("packImagePath"));
movie.setOrder_Img(obj.getString("packImageName"));
movie.setOrder_date(obj.getString("orderDate"));
movie.setOrder_Status(obj.getString("orderStatus"));
movie.setCancel_Status(obj.getString("isCancelled"));
placeorderlists.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
textcounter.setText("Total Order : "+placeorderlists.size());
}
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(MyOrderListActivity.this);
builder.setMessage("You Have No Order");
String positiveText = getString(android.R.string.ok);
builder.setPositiveButton(positiveText,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// positive button logic
Intent intentc=new Intent(MyOrderListActivity.this,OrderActivity.class);
startActivity(intentc);
}
});
String negativeText = getString(android.R.string.cancel);
builder.setNegativeButton(negativeText,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// negative button logic
}
});
AlertDialog dialog = builder.create();
// display dialog
dialog.show();
}
// Parsing json
rcAdapter = new RecyclerViewAdapterMyorderlist(MyOrderListActivity.this, placeorderlists);
rView.setAdapter(rcAdapter);
// notifying list adapter about data changes
// so that it renders the list view with updated data
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("ErrorVolley", "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
hidepDialog();
}
});
MyApplication.getInstance().addToReqQueue(req, "jreq");
}
in my logcat it shows blank message and getting blank toast
VolleyLog.d("ErrorVolley", "Error: " + error.getMessage());
Once check with below code snippet for error.
#Override
public void onErrorResponse(VolleyError error) {
String body;
//get status code here
String statusCode = String.valueOf(error.networkResponse.statusCode));
//get response body and parse with appropriate encoding
if(error.networkResponse.data!=null) {
try {
body = new String(error.networkResponse.data,"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
//do stuff with the body...
}
My app performs uploading operation to backend php server.My problem is i cannot dismiss the progressdialog inside volley Onresponse() method.Onresponse() method gets executed and toast is displayed in background of the Progressdialog so that means Onresponse() gets called currectly.
I declared ProgressDialog variable in public
onCreate() method look like this
ProgressDialog dialog;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.signup);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog=new ProgressDialog(context,ProgressDialog.STYLE_SPINNER);
dialog.setIndeterminate(true);
dialog.show(context,"Signing up","Please wait...");
login_call();
}
Login_call() performs volley request and inside the onResponse() i need to dismiss the dialog but its not working.
public void login_call()
{
RequestQueue queue= Volley.newRequestQueue(getApplicationContext());
StringRequest request = new StringRequest(Request.Method.POST, "http://192.168.56.1/sign.php", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.equals("success"))
{
dialog.dismiss();
getApplicationContext().startActivity(new Intent(getApplicationContext(), MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
}
else
{
dialog.dismiss()
Toast.makeText(getApplicationContext(), response, Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
dialog.dismiss();
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
}
) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> param = new HashMap<>();
param.put("user",user.getText().toString());
param.put("pass",pass.getText().toString());
param.put("name",name.getText().toString());
param.put("mob",mob.getText().toString());
param.put("email",email.getText().toString());
param.put("photo",photo);
return param;
}
};
queue.add(request);
}
Toast message is displaying correctly but progressdialog is not gettting dismissed.
Any ideas to solve the problem??
Just change this :
RequestQueue queue= Volley.newRequestQueue(getApplicationContext());
StringRequest request = new StringRequest(Request.Method.POST, "http://192.168.56.1/sign.php", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
dialog.dismiss(); // write it there
if (response.equals("success")) {
// dialog.dismiss(); remove this from here..!!
getApplicationContext().startActivity(new Intent(getApplicationContext(), MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
);
} else {
Toast.makeText(getApplicationContext(), response, Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
dialog.dismiss();
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
}
Edit : set this
dialog.setIndeterminate(false);
first in first you didn't check all conditions
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.equals("success")) {
dialog.dismiss();
getApplicationContext().startActivity(new Intent(getApplicationContext(), MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
**} else {
Toast.makeText(getApplicationContext(), response, Toast.LENGTH_LONG).show();
}**
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
dialog.dismiss();
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
The else block doesn't hide the dialog so you should change it in this way
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
dialog.dismiss();
if (response.equals("success")) {
getApplicationContext().startActivity(new Intent(getApplicationContext(), MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
} else {
Toast.makeText(getApplicationContext(), response, Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
dialog.dismiss();
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
I think that the mistake is this, of course assuming that your dialog is accessible from the callback
Change your Dialog.show method to use this version: show(Context context, CharSequence title, CharSequence message, boolean indeterminate, boolean cancelable) like this:
final ProgressDialog dialog = ProgressDialog.show(context, "Signing up","Please wait...", false, true);
So your onClick code should change to something like this:
public void onClick(View view) {
final ProgressDialog dialog = ProgressDialog.show(context, "Signing up","Please wait...", false, true);
login_call();
}
Please give this a try and let me know if it helps.