-2

I Implemented one code for delete item from ListView. Below is my code where I am using notifyDataSetChanged(), but the list is not refreshing and item is there on click remove button while I used context.recreate() function then all page is loading again and the item is deleted.

 public class Shortlisted_custom  extends ArrayAdapter<String> {

private static final String deleteURL = "http://192.168.2.110/xp/ajax_call.php?action=remove_shortlisted";
private static final String url1 = "http://192.168.2.110/xp/express_intrest.php";
private static final String KEY_MATRI_ID_TO="matriID_to";
private static final String KEY_MATRI_ID_BY="matriID_by";

int pos;

SessionManager session;
public String matri_id_to, matri_id_by, str_gender,strEI;
int selectedPosition;

Button btnremove,btnChat,declineButton;

private NetworkImageView imageView;
private ImageLoader imageLoader;
private String[] ids;
private String[] ages;
private String[] heights;
public String[] communities;
public String[] castes;
public String[] educations;
public String[] occupations;
public String[] incomes;
public String[] pics;
public String[] locations;
public String[] status;
public String[] expressinterest;

private Activity context;

public Shortlisted_custom(Activity context, String[] ids, String[] ages, String[] heights, String[] communities, String[] castes, String[] educations, String[] occupations, String[]incomes, String[]pics, String[] locations,String[] status, String[] expressinterest) {
    super(context, R.layout.custom_shortlist,ids);
    this.context = context;
    this.ids = ids;
    this.ages = ages;
    this.heights = heights;
    this.communities = communities;
    this.castes = castes;
    this.educations = educations;
    this.occupations = occupations;
    this.incomes = incomes;
    this.pics = pics;
    this.locations = locations;
    this.status = status;
    this.expressinterest = expressinterest;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    pos = position;
    LayoutInflater inflater = context.getLayoutInflater();
    final View listViewItem = inflater.inflate(R.layout.custom_shortlist, null, true);
    // Session class instance
    session = new SessionManager(getContext());
    session.checkLogin();
    // get user data from session
    HashMap<String, String> user = session.getUserDetails();

    matri_id_by = user.get(SessionManager.KEY_EMAIL);
    str_gender = user.get(SessionManager.KEY_GENDER);

    String url1 = "https://www.maangal.com/thumb/thumb_";
    String url =url1+pics[position];

    btnremove =(Button) listViewItem.findViewById(R.id.btnRemove);
    btnChat =(Button) listViewItem.findViewById(R.id.VPButton);
    declineButton = (Button)listViewItem.findViewById(R.id.btnEI);
    imageView = (NetworkImageView) listViewItem.findViewById(R.id.offer_image);
    TextView textViewId = (TextView) listViewItem.findViewById(R.id.textViewId);
    TextView textViewName = (TextView) listViewItem.findViewById(R.id.textViewName);
    textViewId.setText(ids[position]);

    if(ages[position].equalsIgnoreCase("null") || status[position].equalsIgnoreCase("deleted")) {
        textViewName.setText("This profile has been Deleted");
        textViewName.setTextColor(Color.RED);
        imageView.setVisibility(View.GONE);
        btnremove.setVisibility(View.GONE);
        btnChat.setVisibility(View.GONE);
        declineButton.setVisibility(View.GONE);
    }
    else {
        imageLoader = CustomVolleyRequest.getInstance(this.getContext()).getImageLoader();
        if (str_gender.equalsIgnoreCase("Male")) {
            imageLoader.get(url, ImageLoader.getImageListener(imageView, R.drawable.image, R.drawable.girl));
        } else {
            imageLoader.get(url, ImageLoader.getImageListener(imageView, R.drawable.image, R.drawable.boy));
        }
        imageView.setImageUrl(url, imageLoader);
        textViewName.setText(ages[position] + " years" + " , " + heights[position] + " cm" + ", " + communities[position] + " : " + castes[position] + " , " + educations[position] + " , " + occupations[position] + " , " + incomes[position] + ", " + locations[position]);
        imageView.setVisibility(View.VISIBLE);
        btnremove.setVisibility(View.VISIBLE);
        btnChat.setVisibility(View.VISIBLE);
        declineButton.setVisibility(View.VISIBLE);
    }

Delete button onClickListener

    btnremove.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            matri_id_to=ids[position];
            selectedPosition = position;
            delete();
            Shortlisted_custom.this.notifyDataSetChanged();
          //  context.recreate();
        }
    });


    btnChat.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(v.getContext(),BlankActivity.class);
            Log.e("Id*******------------",ids[position].toString());
            i.putExtra("ID", ids[position]);
            i.putExtra("gender",str_gender);
            i.putExtra("current_ID",matri_id_by);
            v.getContext().startActivity(i);
        }
    });


    strEI = expressinterest[position];
    Log.e("EI-------------->", strEI.toString());
    if(strEI.toString().equalsIgnoreCase("Accepted")) {
        declineButton.setText(strEI);
        declineButton.setBackgroundColor(Color.parseColor("#FF045B49"));
        declineButton.setEnabled(false);
    }
    else if(strEI.toString().equalsIgnoreCase("Reject")){
        declineButton.setText(strEI);
        declineButton.setBackgroundColor(Color.parseColor("#FF045B49"));
        declineButton.setEnabled(false);
    }
    else if(strEI.toString().equalsIgnoreCase("Declined")){
        declineButton.setText(strEI);
        declineButton.setBackgroundColor(Color.parseColor("#FF045B49"));
        declineButton.setEnabled(false);
    }
    else if(strEI.toString().equalsIgnoreCase("Pending..")){
        declineButton.setText(strEI);
        declineButton.setBackgroundColor(Color.parseColor("#FF045B49"));
        declineButton.setEnabled(false);
    }
    else
    {
        declineButton.setText(strEI);
    }


    declineButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            matri_id_to=ids[position];
            selectedPosition = position;
            express_Intrest();
        }
    });
    return listViewItem;
}

public void express_Intrest(){
    StringRequest stringRequest1 = new StringRequest(Request.Method.POST, url1, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            if(response.trim().equalsIgnoreCase("success")) {
                expressinterest[selectedPosition] = "Pending..";
            }
        }
    },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(getContext(), error.toString(), Toast.LENGTH_LONG).show();
                }
            }) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put(KEY_MATRI_ID_BY,matri_id_by);
            params.put(KEY_MATRI_ID_TO,matri_id_to);
            return params;
        }
    };
    RequestQueue requestQueue = Volley.newRequestQueue(getContext());
    requestQueue.add(stringRequest1);
}

 public void delete(){
    StringRequest stringRequest1 = new StringRequest(Request.Method.POST, deleteURL, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            if(response.trim().equalsIgnoreCase("success")) {
                Log.e("Remove_____________",matri_id_to);
            }
        }
    },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(getContext(), error.toString(), Toast.LENGTH_LONG).show();
                }
            }) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put(KEY_MATRI_ID_BY,matri_id_by);
            params.put(KEY_MATRI_ID_TO,matri_id_to);
            return params;
        }
    };
    RequestQueue requestQueue = Volley.newRequestQueue(getContext());
    requestQueue.add(stringRequest1);
}

Fragment

public class ShortlistTab extends Fragment {
// Session Manager Class
SessionManager session;
String email;
public String JSON_URL;
private ListView listView;
public ShortlistTab() {}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Session class instance
    session = new SessionManager(getActivity());
    // get user data from session
    HashMap<String, String> user = session.getUserDetails();
    email = user.get(SessionManager.KEY_EMAIL);
    JSON_URL = "http://192.168.2.110/xp/shortlistedTab.php?matri_id="+email;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view= inflater.inflate(R.layout.matches_tab, container, false);
    listView = (ListView) view.findViewById(R.id.listView);
    sendRequest();
    return view;
}

private void sendRequest(){

    final ProgressDialog loading = ProgressDialog.show(getActivity(),"Loading Data", "Please wait...",false,false);

    StringRequest stringRequest = new StringRequest(Request.Method.POST,JSON_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    loading.dismiss();
                    Log.e("ShortlistedTab--------",response.trim());
                    showJSON(response);
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                    Toast.makeText(getContext(),error.getMessage(), Toast.LENGTH_LONG).show();
                }
            });
    int MY_SOCKET_TIMEOUT_MS = 30000;
    stringRequest.setRetryPolicy(new DefaultRetryPolicy(
            MY_SOCKET_TIMEOUT_MS, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

    RequestQueue requestQueue = Volley.newRequestQueue(getContext());
    requestQueue.add(stringRequest);
}

protected void showJSON(String json){
    ShortlistMeParseJSON pj = new ShortlistMeParseJSON(json);
    pj.parseJSON();
    Shortlisted_custom cl = new Shortlisted_custom(getActivity(), 
    ShortlistMeParseJSON.ids,ShortlistMeParseJSON.ages, 
    ShortlistMeParseJSON.heights, 
    ShortlistMeParseJSON.communities,ShortlistMeParseJSON.castes,
    ShortlistMeParseJSON.educations,ShortlistMeParseJSON.occupations,
    ShortlistMeParseJSON.incomes,ShortlistMeParseJSON.pics,
    ShortlistMeParseJSON.locations,ShortlistMeParseJSON.status,
    ShortlistMeParseJSON.expressinterest);
    listView.setAdapter(cl);
  }
 }
Vikas Godiyal
  • 117
  • 3
  • 15

2 Answers2

1

Use this adapter class created one custom model for your shortlisted data, also removed some of the global variables please have a look

public class Shortlisted_custom extends BaseAdapter {
private static final String deleteURL = "http://192.168.2.110/xp/ajax_call.php?action=remove_shortlisted";
private static final String url1 = "http://192.168.2.110/xp/express_intrest.php";
private static final String KEY_MATRI_ID_TO = "matriID_to";
private static final String KEY_MATRI_ID_BY = "matriID_by";

public String matri_id_by, str_gender;

Button btnremove, btnChat, declineButton;

TextView textViewId,tvAgeHeight,tvCommunity,tvOccupation,tvIncome,tvShortlistedOn,AgeHeight,Community,Occupation,Income,ShortlistedOn;

private NetworkImageView imageView;
private ImageLoader imageLoader;

private ArrayList<ShortListedModel> shortListedModels;

private Activity context;

public Shortlisted_custom(Activity context, String[] ids, String[] ages, String[] heights, String[] communities, String[] castes, String[] educations, String[] occupations, String[] incomes, String[] pics, String[] locations, String[] status, String[] expressinterest, String[] shortlistedOn) {
    this.context = context;

    // Session class instance
    SessionManager session = new SessionManager(context);
    session.checkLogin();
    // get user data from session
    HashMap<String, String> user = session.getUserDetails();

    matri_id_by = user.get(SessionManager.KEY_EMAIL);
    str_gender = user.get(SessionManager.KEY_GENDER);


    shortListedModels = new ArrayList<>();
    for (int i = 0; i < ids.length; i++) {
        ShortListedModel model = new ShortListedModel(ids[i], ages[i], heights[i], communities[i],
                castes[i], educations[i], occupations[i], incomes[i], pics[i],
                locations[i], status[i], expressinterest[i], shortlistedOn[i]);
        shortListedModels.add(model);
    }
}

@Override
public int getCount() {
    return shortListedModels.size();
}

@Override
public Object getItem(int position) {
    return null;
}

@Override
public long getItemId(int position) {
    return 0;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = context.getLayoutInflater();
    final View listViewItem = inflater.inflate(R.layout.custom_shortlist, null, true);

    String url1 = "https://www.maangal.com/thumb/thumb_";
    String url = url1 + shortListedModels.get(position).pic;

    btnremove = (Button) listViewItem.findViewById(R.id.btnRemove);
    btnChat = (Button) listViewItem.findViewById(R.id.VPButton);
    declineButton = (Button) listViewItem.findViewById(R.id.btnEI);
    imageView = (NetworkImageView) listViewItem.findViewById(R.id.offer_image);

    textViewId = (TextView) listViewItem.findViewById(R.id.textViewId);
    tvAgeHeight = (TextView) listViewItem.findViewById(R.id.tvAgeHeight);
    tvCommunity = (TextView) listViewItem.findViewById(R.id.tvCommunity);
    tvOccupation = (TextView) listViewItem.findViewById(R.id.tvOccupation);
    tvIncome = (TextView) listViewItem.findViewById(R.id.tvIncome);
    tvShortlistedOn = (TextView) listViewItem.findViewById(R.id.tvShortlistedOn);
    AgeHeight = (TextView) listViewItem.findViewById(R.id.AgeHeight);
    Community = (TextView) listViewItem.findViewById(R.id.Community);
    Occupation = (TextView) listViewItem.findViewById(R.id.Occupation);
    Income = (TextView) listViewItem.findViewById(R.id.Income);
    ShortlistedOn = (TextView) listViewItem.findViewById(R.id.ShortlistedOn);
    textViewId.setText(ids[position]);

    if (shortListedModels.get(position).age.equalsIgnoreCase("null") || shortListedModels.get(position).status.equalsIgnoreCase("deleted")) {
        tvAgeHeight.setText("This profile has been Deleted");
        tvAgeHeight.setTextColor(Color.RED);
        tvCommunity.setVisibility(View.GONE);
        tvOccupation.setVisibility(View.GONE);
        tvIncome.setVisibility(View.GONE);
        tvShortlistedOn.setVisibility(View.GONE);
        AgeHeight.setVisibility(View.GONE);
        Community.setVisibility(View.GONE);
        Occupation.setVisibility(View.GONE);
        Income.setVisibility(View.GONE);
        ShortlistedOn.setVisibility(View.GONE);
        imageView.setVisibility(View.GONE);
        btnremove.setVisibility(View.GONE);
        btnChat.setVisibility(View.GONE);
        declineButton.setVisibility(View.GONE);
    } else {
        imageLoader = CustomVolleyRequest.getInstance(this.context).getImageLoader();
        if (str_gender.equalsIgnoreCase("Male")) {
            imageLoader.get(url, ImageLoader.getImageListener(imageView, R.drawable.image, R.drawable.girl));
        } else {
            imageLoader.get(url, ImageLoader.getImageListener(imageView, R.drawable.image, R.drawable.boy));
        }
        imageView.setImageUrl(url, imageLoader);
        AgeHeight.setText(ages[position]+" years , "+ heights[position]);
        Community.setText(communities[position]+" / "+castes[position]);
        Occupation.setText(occupations[position]);
        Income.setText(incomes[position]);
        ShortlistedOn.setText(shortlistedOn[position]);

        tvCommunity.setVisibility(View.VISIBLE);
        tvOccupation.setVisibility(View.VISIBLE);
        tvIncome.setVisibility(View.VISIBLE);
        tvShortlistedOn.setVisibility(View.VISIBLE);
        AgeHeight.setVisibility(View.VISIBLE);
        Community.setVisibility(View.VISIBLE);
        Occupation.setVisibility(View.VISIBLE);
        Income.setVisibility(View.VISIBLE);
        ShortlistedOn.setVisibility(View.VISIBLE);
        imageView.setVisibility(View.VISIBLE);
        btnremove.setVisibility(View.VISIBLE);
        btnChat.setVisibility(View.VISIBLE);
        declineButton.setVisibility(View.VISIBLE);
    }

    btnremove.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            delete(position);
        }
    });


    btnChat.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(v.getContext(), BlankActivity.class);
            Log.e("Id*******------------", shortListedModels.get(position).id.toString());
            i.putExtra("ID", shortListedModels.get(position).id);
            i.putExtra("gender", str_gender);
            i.putExtra("current_ID", matri_id_by);
            v.getContext().startActivity(i);
        }
    });


    String strEI = shortListedModels.get(position).expressinterest;
    Log.e("EI-------------->", strEI.toString());
    if (strEI.toString().equalsIgnoreCase("Accepted")) {
        declineButton.setText(strEI);
        declineButton.setBackgroundColor(Color.parseColor("#FF045B49"));
        declineButton.setEnabled(false);
    } else if (strEI.toString().equalsIgnoreCase("Reject")) {
        declineButton.setText(strEI);
        declineButton.setBackgroundColor(Color.parseColor("#FF045B49"));
        declineButton.setEnabled(false);
    } else if (strEI.toString().equalsIgnoreCase("Declined")) {
        declineButton.setText(strEI);
        declineButton.setBackgroundColor(Color.parseColor("#FF045B49"));
        declineButton.setEnabled(false);
    } else if (strEI.toString().equalsIgnoreCase("Pending..")) {
        declineButton.setText(strEI);
        declineButton.setBackgroundColor(Color.parseColor("#FF045B49"));
        declineButton.setEnabled(false);
    } else {
        declineButton.setText(strEI);
    }


    declineButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            express_Intrest(position);
        }
    });
    return listViewItem;
}

public void express_Intrest(final int positionToExpress) {
    StringRequest stringRequest1 = new StringRequest(Request.Method.POST, url1, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            if (response.trim().equalsIgnoreCase("success")) {
                shortListedModels.get(positionToExpress).expressinterest = "Pending..";
                notifyDataSetChanged();
            }
        }
    },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(context, error.toString(), Toast.LENGTH_LONG).show();
                }
            }) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put(KEY_MATRI_ID_BY, matri_id_by);
            params.put(KEY_MATRI_ID_TO, shortListedModels.get(positionToExpress).id);
            return params;
        }
    };
    RequestQueue requestQueue = Volley.newRequestQueue(context);
    requestQueue.add(stringRequest1);
}

public void delete(final int positionToRemove) {
    StringRequest stringRequest1 = new StringRequest(Request.Method.POST, deleteURL, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            if (response.trim().equalsIgnoreCase("success")) {
                shortListedModels.remove(positionToRemove);
                notifyDataSetChanged();
            }
        }
    },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(context, error.toString(), Toast.LENGTH_LONG).show();
                }
            }) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put(KEY_MATRI_ID_BY, matri_id_by);
            params.put(KEY_MATRI_ID_TO, shortListedModels.get(positionToRemove).id);
            return params;
        }
    };
    RequestQueue requestQueue = Volley.newRequestQueue(context);
    requestQueue.add(stringRequest1);
}

private class ShortListedModel {
    private String id;
    private String age;
    private String height;
    private String communitie;
    private String caste;
    private String education;
    private String occupation;
    private String income;
    private String pic;
    private String location;
    private String status;
    private String expressinterest;
    private String shortlistedOn;


    public ShortListedModel(String id, String age, String height, String communitie, String caste,
                            String education, String occupation, String income, String pic, String location,
                            String status, String expressinterest, String shortlistedOn ) {
        this.id = id;
        this.age = age;
        this.height = height;
        this.communitie = communitie;
        this.caste = caste;
        this.education = education;
        this.occupation = occupation;
        this.income = income;
        this.pic = pic;
        this.location = location;
        this.status = status;
        this.expressinterest = expressinterest;
        this.shortlistedOn=shortlistedOn;
    }
  }
}
Vikas Godiyal
  • 117
  • 3
  • 15
Satender Kumar
  • 627
  • 4
  • 7
-1

You need to use Arraylist instead of Array for dynamically update array data. Then you can remove item from arraylist dynamically on delete and notifydatasetchanged() for refresh listview.

Samir Bhatt
  • 3,041
  • 2
  • 25
  • 39
  • we can not use onResponse(strong text) because this is ArrayAdapter – Vikas Godiyal Oct 17 '17 at 05:42
  • It seems like you have used array. you have to remove item before notifydatasetchanged. So, you have to take Arraylist instead of Array So, you can dynamically remove item from selected position and notifydatasetchanged. So, it will update your list. – Samir Bhatt Oct 17 '17 at 05:46
  • NotifydatasetChanged will only refresh your listview. If you want to remove any item, you have to remove that item from array and then refresh listview with NotifyDatasetChanged. – Samir Bhatt Oct 17 '17 at 05:57
  • Yep I know @SamirBhatt I tried it but nothing change on result – Vikas Godiyal Oct 17 '17 at 06:00
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/156882/discussion-between-samir-bhatt-and-vikas-godiyal). – Samir Bhatt Oct 17 '17 at 06:49