Angel John Angel John - 2 months ago 7
Android Question

Delete data from Json Array in Recyclerview

I'm try to delete data from my json array inside recyclerview. I can able to delete the same data from the server.But it is not reflected on my recyclerview. it is reflected when reloading the activity.

This is my Adapter page

public class RecyclerAdapterMyLink extends
RecyclerView.Adapter<RecyclerAdapterMyLink.ViewHolder> {
List<RecyclerMyLinkModel> mLinks;
private Context context;
private static final String DELETEMYLINK_URL = Config.GET_URL+"deletemylink.php";

public RecyclerAdapterMyLink(List<RecyclerMyLinkModel> mLinks, Context context){
super();
this.mLinks = mLinks;
this.context = context;
}
@Override
public RecyclerAdapterMyLink.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View contactView = inflater.inflate(R.layout.rsmylink_activicty, parent, false);
ViewHolder viewHolder = new ViewHolder(contactView);
return viewHolder;
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
RecyclerMyLinkModel myLinkModel = mLinks.get(position);
holder.txtLinkTitle.setText(myLinkModel.getCaption());
holder.txtLinkTitle.setTag(myLinkModel.getLink());
holder.remove_mylinks.setTag(myLinkModel.getLid());
holder.remove_mylinks.setOnClickListener(clickListener);
holder.remove_mylinks.setTag(holder);
}
View.OnClickListener clickListener = new View.OnClickListener() {
@Override
public void onClick(View view) {

ViewHolder holder = (ViewHolder) view.getTag();
int position = holder.getPosition();
AlertDialog diaBox = AskOption(position);
diaBox.show();
}
};
private AlertDialog AskOption(Integer pos)
{
final Integer post=pos;
AlertDialog myQuittingDialogBox =new AlertDialog.Builder(context)
//set message, title, and icon
.setTitle("Delete")
.setMessage("Do you want to Delete")
.setIcon(R.drawable.heartred)
.setPositiveButton("Delete", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int whichButton) {
RecyclerMyLinkModel feedItem = mLinks.get(post);
Integer lid=feedItem.getLid();
RemoveMyLInk(lid);//Deleted from server
mLinks.remove(post);
notifyItemRemoved(post);;
notifyItemRangeChanged(post, mLinks.size());
dialog.dismiss();
}

})
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {

dialog.dismiss();

}
})
.create();
return myQuittingDialogBox;
}

@Override
public int getItemCount() {
return mLinks.size();
}

public static class ViewHolder extends RecyclerView.ViewHolder {
public ImageView remove_mylinks;
public TextView txtLinkTitle;
public ViewHolder(View itemView) {
super(itemView);
remove_mylinks = (ImageView) itemView.findViewById(R.id.remove_mylinks);

txtLinkTitle = (TextView) itemView.findViewById(R.id.txtLinkTitle);

}

}
private void RemoveMyLInk(Integer lkid)
{

class RemoveMyLinkUser extends AsyncTask<Integer, Void, String>
{
@Override
protected String doInBackground(Integer... params) {
Integer myNum = params[0];
try {

URL url = new URL(DELETEMYLINK_URL); // here is your URL path

JSONObject postDataParams = new JSONObject();
postDataParams.put("l_id", myNum);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode=conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader in=new BufferedReader(new
InputStreamReader(
conn.getInputStream()));

StringBuffer sb = new StringBuffer("");
String line="";

while((line = in.readLine()) != null) {

sb.append(line);
break;
}

in.close();
return sb.toString();

}
else {
return new String("false : "+responseCode);
}
}
catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}

@Override
protected void onPreExecute() {
super.onPreExecute();

}

@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);

if ("Some Problem Occurs Try Again".equals(s))
{
Toast.makeText(context,s,Toast.LENGTH_LONG).show();
}
else if("Successfully Deleted".equals(s))
{
Toast.makeText(context,s,Toast.LENGTH_LONG).show();

}

}


}
RemoveMyLinkUser ch = new RemoveMyLinkUser();
ch.execute(lkid);
}
public String getPostDataString(JSONObject params) throws Exception {

StringBuilder result = new StringBuilder();
boolean first = true;

Iterator<String> itr = params.keys();

while(itr.hasNext()){

String key= itr.next();
Object value = params.get(key);

if (first)
first = false;
else
result.append("&");

result.append(URLEncoder.encode(key, "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(value.toString(), "UTF-8"));

}
return result.toString();
}
}


This is my Recyclerview layout

enter image description here

Answer

For information Integer is not int, Integer is an Object. So please change the Integer to int. Like this

private AlertDialog AskOption(int pos)
{
final int post=pos;
AlertDialog myQuittingDialogBox =new AlertDialog.Builder(context)
        //set message, title, and icon
        .setTitle("Delete")
        .setMessage("Do you want to Delete")
        .setIcon(R.drawable.heartred)
        .setPositiveButton("Delete", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int whichButton) {
                    RecyclerMyLinkModel feedItem = mLinks.get(post);
                    Integer lid=feedItem.getLid();
                    RemoveMyLInk(lid);//Deleted from server
                    mLinks.remove(post);
                    notifyItemRemoved(post);;
                    notifyItemRangeChanged(post, mLinks.size());
                    dialog.dismiss();
            }

        })
        .setNegativeButton("cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {

                dialog.dismiss();

            }
        })
        .create();
return myQuittingDialogBox;
}

Credits @Selvin

This answer is just only for information to others