我想点击它来删除一行

时间:2016-08-10 14:38:04

标签: android android-sqlite

在这个应用程序中,用户将产品添加到他们的购物清单中。然后他可以通过切换到下面的类来查看他的产品添加到购物清单。现在我希望用户可以选择通过单击删除产品产品存储在哪一行,我想知道这是怎么回事?谢谢。

DataListActivity

 package ie.example.artur.projectrepeat;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class DataListActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {

    ListView listView;
    SQLiteDatabase sqLiteDatabase;
    DatabaseClass  database;
    Cursor cursor;
    ListDataAdapter listDataAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.data_list_layout);


        listView = (ListView) findViewById(R.id.list_view);
        listDataAdapter = new ListDataAdapter(getApplicationContext(), R.layout.row_layout);
        listView.setAdapter(listDataAdapter);
        listView.setOnItemClickListener(this);
        database = new DatabaseClass(getApplicationContext());

        sqLiteDatabase = database.getReadableDatabase();

        Cursor cursor=database.getInformation(sqLiteDatabase);

        if (cursor.moveToFirst()) {
            do {

                String id, product_name, category;
                id = cursor.getString(0);
                product_name = cursor.getString(1);
                category = cursor.getString(2);
                DataProvider dataProvider = new DataProvider(id, product_name, category);
                listDataAdapter.add(dataProvider);
            } while (cursor.moveToNext()


                    );

        }
    }

   @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        TextView tv = (TextView) view.findViewById(R.id.product_id);
        sqLiteDatabase = database.getReadableDatabase();
        DatabaseClass.DeleteInformation(tv.getText().toString(), sqLiteDatabase);


        listDataAdapter.notifyDataSetChanged();


    }


    }

这是我的数据库

  package ie.example.artur.projectrepeat;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;

/**
 * Created by family on 06/07/2016.
 */
public class DatabaseClass extends SQLiteOpenHelper {
    public static final String DATABASE_Name = "Product.db2";
    public static final String Table_Name = "product_table2";
    public static final String COL_1 = "ID";
    public static final String COL_2 = "Name";
    public static final String COL_3 = "Quantity";
    public static final String COL_4 = "Category";
    public static final String COL_5 = "Importance";
    public DatabaseClass(Context context) {
        super(context, DATABASE_Name, null, 1);

    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table " + Table_Name + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,Quantity TEXT,Category INTEGER,Importance TEXT);");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("Drop Table If Exists" + Table_Name);
        onCreate(db);
    }

    public boolean insertData(String name, String quantity, String category,String importance) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL_2, name);
        contentValues.put(COL_3, quantity);
        contentValues.put(COL_4, category);
        contentValues.put(COL_5, importance);

        long result = db.insert(Table_Name, null, contentValues);

            if (result == -1)
                return false;
            else
                return true;
        }

    public Cursor getAllData() {
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor res = db.rawQuery("select * from " + Table_Name, null);
        return res;
    }

    public boolean updateData(String id,String name,String quantity,String category,String importance ) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL_1, id);
        contentValues.put(COL_2, name);
        contentValues.put(COL_3, quantity);
        contentValues.put(COL_4, category);
        contentValues.put(COL_5, importance);
        db.update(Table_Name,contentValues,"id =?",new String[]{id});
                return true;
    }

   /* public Cursor getCursor(){
        SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();

        queryBuilder.setR
    }
*/
   public Integer DeleteData (String id) {
       SQLiteDatabase db = this.getWritableDatabase();
       return db.delete(Table_Name,"ID = ?",new String[]{id});
   }
    public static void DeleteInformation(String item_name, SQLiteDatabase sqLiteDatabase){

        String selection = COL_1+" LIKE ?";
        String [] selection_args = {item_name};
        sqLiteDatabase.delete(Table_Name,selection,selection_args);

    }

    public Cursor getInformation(SQLiteDatabase sqLiteDatabase)
    {
        Cursor cursor;
        String [] Projections = {COL_1,COL_2,COL_4};

        cursor  = sqLiteDatabase.query(Table_Name,Projections,null,null,null,null,null);
        return cursor;

    }

    public Cursor getItem(String item_name ,SQLiteDatabase sqLiteDatabase){
        String [] Projections = {COL_1,COL_2,COL_3,COL_4,COL_5};
        String selection = COL_1+" LIKE ?";
        String [] selection_args = {item_name};
        Cursor cursor = sqLiteDatabase.query(Table_Name,Projections,selection,selection_args,null,null,null);
        return cursor;

    }


}

数据提供商

package ie.example.artur.projectrepeat;

/**
 * Created by family on 10/08/2016.
 */
public class DataProvider {

    private String id;
    private String product_name;
    private String category;

    public DataProvider(String id,String product_name,String category)
    {
    this.id = id;
    this.product_name=product_name;
    this.category=category;




    }


    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }


    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getProduct_name() {
        return product_name;
    }

    public void setProduct_name(String product_name) {
        this.product_name = product_name;
    }
}

ListDataActivity

package ie.example.artur.projectrepeat;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by family on 10/08/2016.
 */
public class ListDataAdapter extends ArrayAdapter  {
   List list = new ArrayList ();

    public ListDataAdapter(Context context, int resource) {
        super(context, resource);
    }





    static class LayoutHandler
    {
        TextView id,product_name,category;

    }
    @Override
    public void add(Object object) {
        super.add(object);
        list.add(object);
    }

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

    }



    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
       LayoutHandler layoutHandler;
        View row = convertView;
        if(row == null)
        {
            LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = layoutInflater.inflate(R.layout.row_layout,parent,false);
            layoutHandler = new LayoutHandler();
            layoutHandler.id = (TextView) row.findViewById(R.id.product_id);
            layoutHandler.product_name = (TextView) row.findViewById(R.id.product_name);
            layoutHandler.category = (TextView) row.findViewById(R.id.product_category);
            row.setTag(layoutHandler);
        }
        else {
            layoutHandler = (LayoutHandler) row.getTag();

        }
        DataProvider dataProvider = (DataProvider) this.getItem(position);
        layoutHandler.id.setText(dataProvider.getId());
        layoutHandler.product_name.setText(dataProvider.getProduct_name());
        layoutHandler.category.setText(dataProvider.getCategory());



        return row;




    }


    }

2 个答案:

答案 0 :(得分:1)

要执行此操作,您需要在该行上设置OnClickListener,或在具有附加侦听器的单元格中创建一个按钮。然后在侦听器内部从项目数组和数据库中删除该项目。我不打算为你编写代码,而是给你一个OnClickListener的例子:

final Button button = (Button) findViewById(R.id.button_id);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on click 
                // delete this item from the database
                (new DatabaseClass()).DeleteData(list.get(position).id);  
                // delete this item from the list array
                list.remove(position);

                // reload the listview
                adapter.notifyDataSetChanged();
            }
        });

在适配器的getView()方法中,您需要在设置布局处理程序值后立即添加此onclick侦听器。 希望这至少可以让你知道该怎么做。您可以采取一些不同的方法,但我强烈建议不要使整行可点击,而是使用“删除”按钮。并且在执行删除数据的操作之前,请先考虑显示确认模式。

答案 1 :(得分:1)

override fun onCreateLoader(id: Int, args: Bundle?): Loader<Cursor> = TODO()

在ListView上将setOnItemClickListener设置为上面的代码。

我在你的适配器类中添加了removeItemAt方法

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        TextView tv=view.findViewBtId(R.id.product_id);
        databaseObject.DeleteData(tv.getText().toString());
        listAdapter.removeItemAt(position);
         // to close the current activity
         finish();

    }
});