如何在Android中的Recycler View中实现的按钮单击中从Sqlite中删除数据

时间:2017-03-08 08:07:43

标签: android sqlite android-recyclerview

当我们点击recyclerView内的删除图片按钮时,我需要从数据库中删除项目。

这是篮子活动 BasketMain.java 包in.haazir.haazir.basket;

            import android.app.ActionBar;
            import android.content.Intent;
            import android.support.v7.app.AppCompatActivity;
            import android.os.Bundle;
            import android.support.v7.widget.DefaultItemAnimator;
            import android.support.v7.widget.DividerItemDecoration;
            import android.support.v7.widget.LinearLayoutManager;
            import android.support.v7.widget.RecyclerView;
            import android.support.v7.widget.Toolbar;
            import android.util.Log;
            import android.view.Menu;
            import android.view.MenuItem;
            import android.view.View;
            import android.widget.ImageButton;
            import android.widget.ListView;
            import android.widget.Toast;

            import java.util.ArrayList;
            import java.util.List;
            import java.util.jar.Attributes;

            import in.haazir.haazir.R;
            import in.haazir.haazir.demo;
            import in.haazir.haazir.recycleviewlistner.RecyclerTouchListener;
            import in.haazir.haazir.sqllitedatabase.DatabaseOperations;

            public class BasketMain extends AppCompatActivity {

                private RecyclerView haazirBasket;
                DatabaseOperations basketobj;
                List<DataofBasket> data=new ArrayList<>();
                AdapterBasket mAdapter;
                AdapterBasket mAdapter2;
                private Toolbar mToolbar;
                DataofBasket dob = new DataofBasket();
                public int counter=0;

                public String name;
                @Override
                protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_basket_main);
                    //deletecartitem = (ImageButton)findViewById(R.id.basketdeleteitembtn);
                    this.setTitle("Basket");
                    this.getSupportActionBar().setDisplayHomeAsUpEnabled(true); // we use this when we use app compact else if we use actionbar then "this.getActionBar().setDisplayHomeAsUpEnabled(true);"
                    haazirBasket = (RecyclerView) findViewById(R.id.basketmain);
                    haazirBasket.setLayoutManager(new LinearLayoutManager(BasketMain.this));
                    haazirBasket.setItemAnimator(new DefaultItemAnimator());
                    //haazirService.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
                    haazirBasket.addItemDecoration(new in.haazir.haazir.recycleviewlistner.DividerItemDecoration(getApplicationContext()));
                    basketobj = new DatabaseOperations(this);
                    data = basketobj.getAllProducts();
                    mAdapter = new AdapterBasket(BasketMain.this,data);

                    haazirBasket.setAdapter(mAdapter);



                    haazirBasket.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), haazirBasket, new RecyclerTouchListener.ClickListener() {
                        @Override
                        public void onClick(View view, int position) {
                            Toast.makeText(getApplicationContext(), "clicked", Toast.LENGTH_SHORT).show();
                            // mAdapter.deleteListener(getApplicationContext());

                            DataofBasket dob = data.get(position);
                            name = dob.serviceName;
                            // mAdapter2 = new AdapterBasket(name,getApplicationContext());
                            /*if (counter > 0) {
                                float r = basketobj.DeletRecord(name);
                                Log.e("deletItem: ", "" + r);
                                data = basketobj.getAllProducts();
                                mAdapter = new AdapterBasket(BasketMain.this, data);

                                haazirBasket.setAdapter(mAdapter);
                            }*/
                        }



                        @Override
                        public void onLongClick(View view, int position) {

                        }
                    }));



                }
                String getName()
                {
                    return name;
                }

                void updateCounter()
                {
                    counter++;
                }
                void deletItem(int pos)
                {
                            // mAdapter.deleteListener(getApplicationContext());
                    data = basketobj.getAllProducts();
                    DataofBasket dob = data.get(pos);
                    name = dob.serviceName;

                            float r =basketobj.DeletRecord(name);
                            Log.e("deletItem: ",""+r );
                            data = basketobj.getAllProducts();
                            mAdapter = new AdapterBasket(BasketMain.this, data);

                            haazirBasket.setAdapter(mAdapter);

                        }




                @Override
                public boolean onCreateOptionsMenu(Menu menu) {
                    // Inflate the menu; this adds items to the action bar if it is present.
                    getMenuInflater().inflate(R.menu.menu_main, menu);
                    return true;
                }

                @Override
                public boolean onOptionsItemSelected(MenuItem item) {
                    // Handle action bar item clicks here. The action bar will
                    // automatically handle clicks on the Home/Up button, so long
                    // as you specify a parent activity in AndroidManifest.xml.
                    switch (item.getItemId()) {
                        case android.R.id.home:
                            // app icon in action bar clicked; goto parent activity.
                            this.finish();
                            return true;
                        case R.id.action_settings:
                            return true;
                        case R.id.cart:
                            return true;
                        default:
                            return super.onOptionsItemSelected(item);

                    }

                }



            }

这是我用于recyclerView适配器

AdapterBasket.java 包in.haazir.haazir.basket;

            /**
             * Created by Dell on 3/4/2017.
             */
            import android.content.Context;
            import android.support.v7.widget.RecyclerView;
            import android.util.Log;
            import android.view.LayoutInflater;
            import android.view.View;
            import android.view.ViewGroup;
            import android.widget.ImageView;
            import android.widget.TextView;

            import com.bumptech.glide.Glide;

            import java.util.Collections;
            import java.util.List;

            import in.haazir.haazir.R;
            import in.haazir.haazir.haazirservices.DataofServices;
            import android.content.Context;
            import android.support.v7.widget.RecyclerView;
            import android.view.LayoutInflater;
            import android.view.View;
            import android.view.ViewGroup;
            import android.widget.Button;
            import android.widget.ImageButton;
            import android.widget.ImageView;
            import android.widget.TextView;
            import android.widget.Toast;
            import android.widget.ToggleButton;

            import com.bumptech.glide.Glide;

            import java.util.Collections;
            import java.util.List;

            import in.haazir.haazir.R;
            import in.haazir.haazir.haazirservices.DataofServices;
            import in.haazir.haazir.sqllitedatabase.DatabaseOperations;

            /**
             * Created by hp.com on 10-02-2017.
             */
            public class AdapterBasket extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

                public Context context;
                private LayoutInflater inflater;
                List<DataofBasket> data= Collections.emptyList();
                DataofBasket current;
                DataofBasket current1;
                int currentPos=0;
                public int count = 1;
                DatabaseOperations dbobj;
                MyHolder holder;
               public String name;


                // create constructor to innitilize context and data sent from MainActivity
                public AdapterBasket(Context context, List<DataofBasket> data){
                    this.context=context;
                    inflater= LayoutInflater.from(context);
                    this.data=data;
                }

                public AdapterBasket(String name, Context context){
                    this.name=name;
                    inflater= LayoutInflater.from(context);

                }
                // Inflate the layout when viewholder created
                @Override
                public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                    View view=inflater.inflate(R.layout.container_basket, parent,false);
                    holder=new MyHolder(view);
                    return holder;
                }

                // Bind data
                @Override
                public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

                    // Get current position of item in recyclerview to bind data and assign values from list
                    final MyHolder myHolder = (MyHolder) holder;
                    current = data.get(position);
                    myHolder.textServiceName.setText(current.serviceName);


                    // load image into imageview using glide
                    Glide.with(context).load(current.serviceImage)
                            .placeholder(R.drawable.grocery)
                            .error(R.drawable.maggie)
                            .into(myHolder.serviceImageHaazir);
            /*myHolder.deletecartitem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Log.e( "onClick: ","button clicked "+current.serviceName );
                    DatabaseOperations basketobj = new DatabaseOperations(context);
                    BasketMain bm = new BasketMain();
                    float r =basketobj.DeletRecord(current.serviceName);
                    Log.e( "onClick: ",""+r );
                    //data = basketobj.getAllProducts();
                    //AdapterBasket ad = new AdapterBasket(context, data);

                    //ad.setAdapter(mAdapter);
                }
            });

            */
                }
                // return total item from List
                @Override
                public int getItemCount() {
                    return data.size();
                }

                public void delete(int position) { //removes the row
                   current1 = data.get(position);
                    Log.e( "onClick: ","button clicked "+current1.serviceName );
                    BasketMain bm = new BasketMain();
                    //bm.deletItem(current1.serviceName);
                    //bm.updateCounter();
                    DatabaseOperations dbo = new DatabaseOperations(context);
                    float r = dbo.DeletRecord(name);
                    Log.e("deletItem: ", "" + r);
                    //data = dbo.getAllProducts();

                    //data.remove(position);
                    //notifyItemRemoved(position);
                }




                class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

                    TextView textServiceName;
                    ImageView serviceImageHaazir;
                    ImageButton deletecartitem;

                    // create constructor to get widget reference
                    public MyHolder(View itemView) {
                        super(itemView);
                        textServiceName = (TextView) itemView.findViewById(R.id.productdisplatnameidbasket);
                        serviceImageHaazir = (ImageView) itemView.findViewById(R.id.imagebasket);

                        deletecartitem = (ImageButton) itemView.findViewById(R.id.basketdeleteitmebutton);
                        deletecartitem.setOnClickListener(this);
                    }

                    @Override
                    public void onClick(View view) {
                        BasketMain bm = new BasketMain();
                        bm.deletItem(getAdapterPosition());
                        delete(getAdapterPosition());
                    }
                }




            }

2 个答案:

答案 0 :(得分:1)

让我们先纠正代码:

1)当您显示活动的回收者视图时。它确实意味着,活动存在。无需创建新的活动实例。您在MyHolder的onClick方法中创建的。删除此BasketMain bm = new BasketMain();

2)传递活动参考

 i. implement own interface in an activity 

 ii. pass this reference while initiating adapter

 iii. pass it to MyHolder, so that in the onclick you can call activity method like activityReference.deleteItem(int position);

 iv. You can set tag of  current (DataofBasket) to deleteitem button. so that you will get the clicked item's data in the onclick() method.

3)成功使用正确的数据调用活动方法后,您可以根据需要执行任何操作。

答案 1 :(得分:0)

好的,所以我得到了答案。 我们只需要在适配器的构造函数中初始化需要上下文的对象。因为其他地方使用的上下文给出了Null指针异常。