Listview onlongclick删除

时间:2018-03-05 09:52:58

标签: android listview onlongclicklistener

数据库

package sg.edu.rp.c346.todolist;

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

/**
 * Created by User on 26/12/2017.
 */

public class DatabaseHelper extends SQLiteOpenHelper {
    // final is a constant

    public static final String DATABASE_NAME = "mylist.db";
    public  static final String TABLE_NAME = "mylist_data";
    public static final String COL1 = "ID";
    public static final String COL2 = "ITEM1";

    public DatabaseHelper(Context context){
        super (context, DATABASE_NAME, null , 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String createTable = " CREATE TABLE " + TABLE_NAME +"(ID INTEGER PRIMARY KEY AUTOINCREMENT," +
               " ITEM1 TEXT)";
                db.execSQL(createTable);



    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP IF TABLE EXITS "+ TABLE_NAME);
        onCreate(db);




    }
    public boolean addData(String item1) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL2, item1);


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

        //if date as instered incorrectly it will return -1
        if (result == -1) {
            return false;
        } else {
            return true;
        }
    }
        /**
         * Return all the data from database
         * @return
         */
        //cursor is know indirect subclass
        public Cursor getListContent() {
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor data =db.rawQuery("SELECT * FROM " + TABLE_NAME,null);
        return data;


    }
    /**
     * Returns only the ID that matches the name passed in
     * @param name
     * @return
     */
    public  Cursor getItemID(String name){
        SQLiteDatabase db=this.getWritableDatabase();
        String query = "SELECT "+ COL1 +" FROM "+TABLE_NAME+
                " WHERE "+ COL2 +" = '"+ name +"'";
        Cursor data = db.rawQuery(query,null);
        return data;
    }


    /**
     * Delete from database
     * @param id
     * @param name
     */
    public void deleteName(int id, String name){
        SQLiteDatabase db=this.getWritableDatabase();
        String query= "DELETE FROM "+ TABLE_NAME +" WHERE " + COL1 + " = '"
                + id + "'"+" AND " + COL2 + "= '" + name + "'";
        db.execSQL(query);

    }


}
package sg.edu.rp.c346.todolist;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;

/**
 * Created by User on 26/12/2017.
 */

public class ListDataActivity extends AppCompatActivity {


    DatabaseHelper myDB;
    ListView listView;
    ArrayAdapter<String> listAdapter;
    Button button;
    Button btnRefresh;
    String selectedName;
    int selectedID;



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

        listView = (ListView) findViewById(R.id.listView);
        button = (Button) findViewById(R.id.add);
        btnRefresh = (Button) findViewById(R.id.refresh);
        myDB = new DatabaseHelper(this);

        // get the intent extra from the ListDataActivity
        Intent receivedIntent=getIntent();

        // now get the itemID we passed as an extra
        selectedID=receivedIntent.getIntExtra("id",-1);//NOTE -1 it just a default values

        // now get the name we passed as an extra
        selectedName=receivedIntent.getStringExtra("name");


        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(ListDataActivity.this, MainActivity.class);
                startActivity(intent);
            }
        });

        btnRefresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(ListDataActivity.this, ListDataActivity.class);
                startActivity(intent);
            }
        });


        //populate an ArrayList<String> from the databases and then view it
        final ArrayList<String> theList = new ArrayList<>();
        Cursor data = myDB.getListContent();



        if (data.getCount() == 0) {
            Toast.makeText(ListDataActivity.this, "The database was empty", Toast.LENGTH_LONG).show();
        } else {
            while (data.moveToNext()) {
                // get the value from the database in column 1
                // then add it to the ArrayList
                theList.add(data.getString(1));
                // create the list adapter and set the adapter
                listAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, theList);
                listView.setAdapter(listAdapter);

                // set an onItemClickListen to the listView
                listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                        String name = adapterView.getItemAtPosition(i).toString();


                        Cursor data = myDB.getItemID(name); //get the id assosicated with the name
                        int itemID = 1;
                        while (data.moveToNext()) {
                            itemID = data.getInt(0);
                        }
                        if (itemID > -1) {
                            Intent editScreenIntent = new Intent(ListDataActivity.this, EditDataActivity.class);
                            editScreenIntent.putExtra("id", itemID);
                            editScreenIntent.putExtra("name", name);
                            startActivity(editScreenIntent);
                        } else {
                            Toast.makeText(ListDataActivity.this, "No ID assosciated", Toast.LENGTH_SHORT).show();
                        }

                    }
                });


            }
        }
            listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                @Override
                public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                    myDB.deleteName(selectedID,selectedName);
                    theList.remove(i);
                    listAdapter.notifyDataSetChanged(); //change to your adapter instance here
                    Toast.makeText(ListDataActivity.this, "item removed", Toast.LENGTH_SHORT).show();
                    return true;
                }
            });

        }
        }

如何删除/删除使用数据库中的setOnItemLongClickListener函数,我的代码似乎不会删除。

listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
            myDB.deleteName(selectedID,selectedName);
            Toast.makeText(ListDataActivity.this, "item removed", Toast.LENGTH_SHORT).show();
            return true;
        }
});

此代码是数据库活动

   public void deleteName(int id, String name){
        SQLiteDatabase db=this.getWritableDatabase();
        String query= "DELETE FROM "+ TABLE_NAME +" WHERE " + COL1 + " = '"
                + id + "'"+" AND " + COL2 + "= '" + name + "'";
        db.execSQL(query);

    }


}

2 个答案:

答案 0 :(得分:0)

当您从数据库中删除数据但附加到适配器的列表仍然保存数据时,您必须从该位置删除并通知您的适配器。
试试这个代码:

listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
    @Override
    public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
        myDB.deleteName(theList.get(i));
        theList.remove(i); 
        listAdapter.notifyDataSetChanged();
        Toast.makeText(ListDataActivity.this, "item removed", Toast.LENGTH_SHORT).show();
        return true;
    }
});

如果要删除所选项目,可以使用:

public void deleteName(String name){
    SQLiteDatabase db=this.getWritableDatabase();
    String query= "DELETE FROM "+ TABLE_NAME +" WHERE " + COL2 + "= '" + name + "'";
    db.execSQL(query);

}

并将deleteName()称为:

myDB.deleteName(theList.get(i));

答案 1 :(得分:0)

我认为问题出在您的删除查询

public void deleteName(int id, String name){
        SQLiteDatabase db=this.getWritableDatabase();
        String query= "DELETE FROM "+ TABLE_NAME +" WHERE " + COL1 + " = "
                + String.valueOf(id) +" AND " + COL2 + "= '" + name + "'";
        db.execSQL(query);

  }

COL1 +&#34; =&#39;&#34; + id +&#34;&#39;&#34; - &gt;单引号用于文字not for numbers.