0

I have a code where I want to delete item from the list as well as database. I am using RecyclerView and each item has 3 buttons and one of them is delete button. If I click on button then response will come as success and I need item will deleted from there.

Below is my code where item is deleted from the database but not deleted on List.

public class CardAdapter  extends RecyclerView.Adapter<CardAdapter.ViewHolder> {
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";

SessionManager session;
public String matri_id_to, matri_id_by, str_gender;
String str_status,str_EI;

//Imageloader to load image
private ImageLoader imageLoader;
private Context context;

//List to store all superheroes
List<SuperHero> superHeroes;

//Constructor of this class
public CardAdapter(List<SuperHero> superHeroes, Context context){
    super();
    //Getting all superheroes
    this.superHeroes = superHeroes;
    this.context = context;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.superheroes_list_shortlist, parent, false);
    // Session class instance
    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);

    ViewHolder viewHolder = new ViewHolder(v);
    return viewHolder;
}

@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {

    //Getting the particular item from the list
   final SuperHero superHero = superHeroes.get(position);

    //Loading image from url
    imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
    imageLoader.get(superHero.getImageUrl(), ImageLoader.getImageListener(holder.imageView, R.drawable.image, android.R.drawable.ic_dialog_alert));

    holder.imageView.setImageUrl(superHero.getImageUrl(), imageLoader);
    holder.textViewId.setText(superHero.getMglId());
    holder.AgeHeight.setText(superHero.getHeight()+" / "+superHero.getAge());
    holder.Community.setText(superHero.getCommunity()+" / "+superHero.getCaste());
    holder.Occupation.setText(superHero.getOccupation());
    holder.Income.setText(superHero.getIncome());
    holder.ShortlistedOn.setText(superHero.getShortlistOn());
    str_status = superHero.getStatus();
    Log.e("str_shortlist_____",str_status);



    str_EI = superHero.getExpress_Intrest();
    Log.e("str_EI_____",str_EI);
    if(str_EI.toString().equalsIgnoreCase("Accepted")) {
        holder.btnEI.setText(str_EI);
        holder.btnEI.setBackgroundColor(Color.parseColor("#FF045B49"));
        holder.btnEI.setEnabled(false);
    }
    else if(str_EI.toString().equalsIgnoreCase("Reject")){
        holder.btnEI.setText(str_EI);
        holder.btnEI.setBackgroundColor(Color.parseColor("#FF045B49"));
        holder.btnEI.setEnabled(false);
    }
    else if(str_EI.toString().equalsIgnoreCase("Declined")){
        holder.btnEI.setText(str_EI);
        holder.btnEI.setBackgroundColor(Color.parseColor("#FF045B49"));
        holder.btnEI.setEnabled(false);
    }
    else if(str_EI.toString().equalsIgnoreCase("Pending..")){
        holder.btnEI.setText(str_EI);
        holder.btnEI.setBackgroundColor(Color.parseColor("#FF045B49"));
        holder.btnEI.setEnabled(false);
    }
    else
    {
        holder.btnEI.setText(str_EI);
    }


    holder.btnRemove.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            matri_id_to = superHero.getMglId();
            holder.delete(position);
        }
    });

    holder.btnViewProfile.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent n = new Intent(holder.itemView.getContext(),BlankActivity.class);
            String str_id = holder.textViewId.getText().toString();
            n.putExtra("ID",str_id);
            holder.itemView.getContext().startActivity(n);
        }
    });


    holder.btnEI.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            superHero.setExpress_Intrest("Wait...");
            holder.btnEI.setText(superHero.getExpress_Intrest());
            matri_id_to = superHero.getMglId();
            holder.expressInterest(position);
        }
    });

}

public SuperHero getItem(int position){
    return superHeroes.get(position);
}

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

class ViewHolder extends RecyclerView.ViewHolder{
    public NetworkImageView imageView;
    public TextView textViewId;
    public TextView AgeHeight;
    public TextView Community;
    public TextView Occupation;
    public TextView Income;
    public TextView ShortlistedOn;
    public Button btnRemove;
    public Button btnViewProfile;
    public Button btnEI;


    //Initializing Views
    public ViewHolder(final View itemView) {
        super(itemView);
        imageView = (NetworkImageView) itemView.findViewById(R.id.imageViewHero);
        textViewId = (TextView) itemView.findViewById(R.id.textViewId);
        AgeHeight = (TextView) itemView.findViewById(R.id.AgeHeight);
        Community = (TextView) itemView.findViewById(R.id.Community);
        Occupation = (TextView) itemView.findViewById(R.id.Occupation);
        Income = (TextView) itemView.findViewById(R.id.Income);
        ShortlistedOn = (TextView) itemView.findViewById(R.id.shortlistOn);
        btnRemove = (Button) itemView.findViewById(R.id.btnRemove);
        btnViewProfile = (Button) itemView.findViewById(R.id.buttonViewProfile);
        btnEI = (Button) itemView.findViewById(R.id.btnExpressIntrest);
    }


    public void expressInterest(final int position) {
        StringRequest stringRequest1 = new StringRequest(Request.Method.POST, url1, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if(response.trim().equalsIgnoreCase("success")) {
                    superHeroes.get(position).setExpress_Intrest("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,matri_id_to);
                return params;
            }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(context);
        requestQueue.add(stringRequest1);
    }

    public void delete(final int position) {
        StringRequest stringRequest1 = new StringRequest(Request.Method.POST, deleteURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (response.trim().equalsIgnoreCase("success")) {
                    superHeroes.get(position);
                    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,matri_id_to);
                return params;
            }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(context);
        requestQueue.add(stringRequest1);
      }
    } 
   }    
Dharmishtha
  • 1,313
  • 10
  • 21
pb007
  • 153
  • 1
  • 5
  • 13

2 Answers2

2

put this code on onResponse-

superHeros.remove(position);
notifydatasetchanged(); 
KeLiuyue
  • 8,149
  • 4
  • 25
  • 42
  • Yes it's working. should I used superHeroes.get(position); before superHeros.remove(position) – pb007 Dec 09 '17 at 05:09
  • @Khalil, There is an exception when there is less item and remove all the item then it gives IndexOutOfBoundsException on superHeros.remove(position); – pb007 Dec 12 '17 at 04:24
1

Try this .

if(superHeroes.size > 0){
    superHeroes.remove(position);
    notifyDataSetChanged();
}

//Delete data from database
DBConstant.dbHelper.deleterow(DBConstant.sqliteDatabase, position);

Hope it helps .

Dharmishtha
  • 1,313
  • 10
  • 21
  • There is an exception when there is less item and remove all the item then it gives IndexOutOfBoundsException on superHeros.remove(position); – pb007 Dec 12 '17 at 04:25
  • 1
    then put one condition before `superHeroes.remove(position);` . Condition is `if(superHeroes.size()>0){.. //}`. – Dharmishtha Dec 12 '17 at 05:20
  • I thing, I do not need this line (DBConstant.dbHelper.deleterow(DBConstant.sqliteDatabase, position);) because m using server MYSQLi – pb007 Dec 12 '17 at 05:33
  • In question you have mentioned that you also want to delete from database , so i have gave you for that purpose . use if need otherwise not. – Dharmishtha Dec 12 '17 at 05:36
  • If I click on button then the Id will go to the database query which is on MYSQL in php and then it will deleted which is work properly. I need item will deleted from the List – pb007 Dec 12 '17 at 05:40
  • `superHeroes.remove(position); notifyDataSetChanged();` delete from the list . and don't use `DBConstant.dbHelper.deleterow(DBConstant.sqliteDatabase, position);` this line. – Dharmishtha Dec 12 '17 at 05:44
  • It's working for me. I was taking about RecyclerView List, But it's fine for me thanks – pb007 Dec 12 '17 at 05:46