【问题标题】:Listview onlongclick deleteListview onlongclick 删除
【发布时间】:2018-03-05 09:52:57
【问题描述】:

数据库

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;
        }
});

这段代码是数据库Activity

   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);

    }


}

【问题讨论】:

  • 你的吐司上架了吗?
  • 是,但不会删除
  • 从数据库中删除或不从您的视图中删除(您在列表中看到的内容)
  • 使用 sqlite ,当我 setOnItemLongClickListener 吐司出来时,但文字仍然存在。
  • 你也需要更新你的适配器

标签: android listview onlongclicklistener


【解决方案1】:

由于您正在从数据库中删除数据,但附加到适配器的列表仍然包含数据,因此您必须从该位置删除并通知您的适配器。
试试这个代码:

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));

【讨论】:

  • ListView 适配器没有notifyItemRemoved 方法
  • 您是否有附加到适配器的列表?将 yourListName 替换为您的实际列表名称。
  • 我的 listName 是 listView
  • 不,是theList
  • 它已删除,但是当我刷新文本时仍然存在。它不会从数据库中删除
【解决方案2】:

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

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 + " = '"+ id + "'" -->单引号用于文本,not for numbers.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-17
    • 2013-07-12
    相关资源
    最近更新 更多