androidlistView连接Sqlite数据库listview长按点击事件

本文详细介绍了如何在Android应用中使用SQLite数据库与ListView组件进行整合,实现数据的展示与长按删除功能。从数据库建表、ListView初始化到数据查询与显示,再到自定义长按事件实现数据删除,提供了一套完整的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近在学习的时候要使用listview显示数据库的内容记录一下。

1.数据库(建表语句)

public class Sql extends SQLiteOpenHelper {
    public Sql( Context context) {
        super(context, "Srt.db", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL("create table User( name text , pass text )");
     

    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }

这样我们就创建了一张名为User的表了

2.listView的初始化

       ListView listView;    
    listView = (ListView) findViewById(R.id.list_forgot);

        adapter = new SimpleAdapter(this,
                list,
                R.layout.simple_fz,
                new String[]{"text1", "text2"},
                new int[]{R.id.textview_1, R.id.textview_2});

在这里我们看见一个新的布局

那就让我们来看看它(这个布局是设置listview的显示样式的)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/textview_1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="TextView" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/textview_2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="TextView" />
    </LinearLayout>
</LinearLayout>

3.加入我们的Sql数据

加入之前我们需要先查询一下

  Cursor cursor = db.rawQuery("select * from User", null);

之后我们就可以添加进去了

if (cursor.moveToFirst()) {
            do {
                pname = cursor.getString(cursor.getColumnIndex("name"));
                pass = cursor.getString(cursor.getColumnIndex("pass"));
                Log.d("Srt", pname);
                Log.d("Srt", pass);
                Map map = new HashMap();
                map.put("text1", pname);
                map.put("text2", pass);
                list.add(map);
            }
            while (cursor.moveToNext());
        }

这样我们的Sql的数据就可以添加到我们的Listview里面了

但不要忘记我们的listview增加适配器

     listView.setAdapter(adapter);

 

最后我做了一个长按删除数据时间

    //长按点击事件
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, final int argindex, long l) {
                 final SQLiteDatabase database = sql.getWritableDatabase();
                HashMap<String,String> map2=(HashMap<String,String>)listView.getItemAtPosition(argindex);
             title  =map2.get("text1");
                AlertDialog.Builder builder = new AlertDialog.Builder(Forgot.this);
                builder.setMessage("你确定要删除这个账号吗?");
                builder.setTitle("提示");

                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        list.remove(argindex);
                        adapter.notifyDataSetChanged();
                    database.delete("User","name=?",new String[]{title});
                    database.close();
                    db.close();

            Toast.makeText(getApplicationContext(),title,Toast.LENGTH_LONG).show();



                    }
                });
                //添加AlertDialog.Builder对象的setNegativeButton()方法
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });

                builder.create().show();
                return false;


            }


        });

最后附上全部代码(里面有我几次失败的尝试哈哈)

package cn.srt.materiallogin;


import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Forgot  extends AppCompatActivity {
    String title;
    ListView listView;
    Sql sql;
    SQLiteDatabase db;
    SimpleAdapter adapter;
    String pname, pass;
    List<Map<String, Object>> list = new ArrayList<>();
    int index = 0;
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.forgot);
        listView = (ListView) findViewById(R.id.list_forgot);
        sql = new Sql(getApplicationContext());
        db = sql.getWritableDatabase();
         /*
            第三次尝试(成功)绑定数据库
         */
        adapter = new SimpleAdapter(this,
                list,
                R.layout.simple_fz,
                new String[]{"text1", "text2"},
                new int[]{R.id.textview_1, R.id.textview_2});
        adapter.notifyDataSetChanged();
        listView.setAdapter(adapter);

        Cursor cursor = db.rawQuery("select * from User", null);
        if (cursor.moveToFirst()) {
            do {
                pname = cursor.getString(cursor.getColumnIndex("name"));
                pass = cursor.getString(cursor.getColumnIndex("pass"));
                Log.d("Srt", pname);
                Log.d("Srt", pass);
                Map map = new HashMap();
                map.put("text1", pname);
                map.put("text2", pass);
                list.add(map);
            }
            while (cursor.moveToNext());
        }

        //长按点击事件
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, final int argindex, long l) {
                 final SQLiteDatabase database = sql.getWritableDatabase();
                HashMap<String,String> map2=(HashMap<String,String>)listView.getItemAtPosition(argindex);
             title  =map2.get("text1");
                AlertDialog.Builder builder = new AlertDialog.Builder(Forgot.this);
                builder.setMessage("你确定要删除这个账号吗?");
                builder.setTitle("提示");

                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        list.remove(argindex);
                        adapter.notifyDataSetChanged();
                    database.delete("User","name=?",new String[]{title});
                    database.close();
                    db.close();

            Toast.makeText(getApplicationContext(),title,Toast.LENGTH_LONG).show();



                    }
                });
                //添加AlertDialog.Builder对象的setNegativeButton()方法
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });

                builder.create().show();
                return false;


            }


        });

//        String delectName = list.get(index).get("text1").toString();
//        String delectPass = list.get(index).get("text2").toString();
//        Cursor cursor = db.query("namepass",
//                null,
//                null,
//                null,
//                null,
//                null,
//                null);
//            if (cursor.moveToFirst()){
//                do {
//                    String mtext = cursor.getString(cursor.getColumnIndex("name"));//得到数据库中的数据
//                    String mtime = cursor.getString(cursor.getColumnIndex("pass"));
//                     = new Date();
//
//                }while (cursor.moveToNext());
//            }


            /*
               第二次尝试
             */
        //Cursor c=db.query("namepass",
        //        null,
        //        null,
        //        null,
        //        null,
        //        null,
        //        null);
        //String[] from  ={"name","pass"};
        //int[] to = {R.id.textview_1,R.id.textview_2};
        //adapter = new SimpleCursorAdapter(this,
        //        R.layout.simple_fz,
        //        c,
        //        from,
        //        to);
        //listView.setAdapter(adapter);
            /*
            第一次尝试(失败)
             */
        //        Cursor cursor = db.rawQuery("select name , pass , id as _id from namepass;",null);
        //        while (cursor.moveToNext()){
        //            danyuan p = new danyuan();
        //            p.name =cursor.getString(cursor.getColumnIndex("name"));
        //            p.pass=cursor.getInt(cursor.getColumnIndex("pass"));
        //            lists.add(p);
        //        }
        //        List<HashMap<String ,Object>> map = new ArrayList<>();
        //        for (danyuan d: lists){
        //            HashMap<String ,Object> hashMap = new HashMap<>();
        //            hashMap.put("text1",d.name);
        //            hashMap.put("text2",d.pass);
        //            map.add(hashMap);
        //        }
        //   simpleAdapter  = new SimpleAdapter(this,
        //                map,
        //                R.layout.simple_fz,
        //                new String[]{"text1","text2"},
        //              new int[]{R.id.textview_1,R.id.textview_2} );
        //        listView.setAdapter(simpleAdapter);

    }
}

转载请注明出处

需要源码的可以点击这里

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值