如何使用单击侦听器更新和删除 SQLite 数据库中的列表视图数据? [英] How to update and delete the list View data in SQLite database with click listener?

查看:29
本文介绍了如何使用单击侦听器更新和删除 SQLite 数据库中的列表视图数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<块引用>

我是 SQLite 数据库的初学者.我在从 listView 更新和删除数据时遇到问题.当我单击我的 listView 数据时,我将我的数据插入到 listView 中,它将进入 UpdateActivity.现在我想在新的 UpdateActivity 中获取那些 listView selected 值,以便我可以编辑或删除.如何做到这一点.

<块引用>

ListDataActivity.Java

public void loadData() {//创建一个arraylist,以便我可以加载要添加到arraylist中的数据ArrayListlistData = new ArrayList<>();Cursor cursor = databaseHelper.showAllData();如果 (cursor.getCount() == 0) {Toast.makeText(getApplicationContext(), 无数据可用", Toast.LENGTH_LONG).show();} 别的 {而 (cursor.moveToNext()) {listData.add(cursor.getString(1) + " \t " + cursor.getString(2));}}ArrayAdapteradapter = new ArrayAdapter(this, R.layout.list_item, R.id.textViewId, listData);listView.setAdapter(适配器);listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {@覆盖public void onItemClick(AdapterView<?>adapterView, View view, int position, long id) {String selectedValue = adapterView.getItemAtPosition(position).toString();Toast.makeText(getApplicationContext(), "Selected Value : " + selectedValue,Toast.LENGTH_LONG).show();Intent intent = new Intent(ListDataActivity.this,UpdateActivity.class);开始活动(意图);}});

<块引用>

UpdateActivity.Java

private DatabaseHelper databaseHelper;私人字符串 selectedName;私人字符串 selectedID;@覆盖protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_update);databaseHelper = new DatabaseHelper(this);SQLiteDatabase sqLiteDatabase = databaseHelper.getWritableDatabase();意图 receiveIntent = getIntent();selectedID = receiveIntent.getStringExtra("name");selectedName = receiveIntent.getStringExtra("surName");

<块引用>

当我插入数据时,我点击我的列表,它会进入这种类型的设计更新活动.我想要 UpdateActivity 中的 Clicked Listview 数据.我该如何解决?

解决方案

现在我想在新的 UpdateActity 中获取那些列表视图选定的值,以便我可以编辑或删除.如何做到这一点.

这是一个更新(转到 UpdateActivity)和删除(长按项目时)的工作示例.这使用了一个 CursorAdapter,即股票 SimpleCursorAdapter.对 SQLite 数据使用 Cursor 适配器非常简单.

首先是 DatabaseHelper :-

class DatabaseHelper 扩展 SQLiteOpenHelper {公共数据库助手(@Nullable 上下文上下文){超级(上下文,我的数据库",空,1);}@覆盖public void onCreate(SQLiteDatabase sqLiteDatabase) {sqLiteDatabase.execSQL(CREATE TABLE IF NOT EXISTS mytable (_id INTEGER PRIMARY KEY, name TEXT, surname TEXT, phone TEXT)");/* 添加一些测试数据 */添加(弗雷德",博客",0000000000",sqliteDatabase);add("Jane","Doe","1111111111",sqliteDatabase);添加(玛丽",约翰斯顿",2222222222",sqliteDatabase);添加(汤姆",cobboly",3333333333",sqliteDatabase);添加(安妮",沃克",4444444444",sqliteDatabase);}@覆盖public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {}public long update(long id, String name, String surname, String phone) {长房车 = 0;ContentValues cv = 新的 ContentValues();if (name != null && name.length() > 0) cv.put(name",name);if (surname != null && surname.length() > 0) cv.put(surname",surname);if (phone != null &&phone.length() > 0) cv.put(phone",phone);if (cv.size() > 0) rv = this.getWritableDatabase().update(mytable",cv,_id=?",new String[]{String.valueOf(id)});返回房车;}公共长删除(长 ID){return this.getWritableDatabase().delete("mytable","_id=?",new String[]{String.valueOf(id)});}公共光标 getAll() {返回 this.getWritableDatabase().query("mytable",null,null,null,null,null,null);}公共游标 getById(long id) {return this.getWritableDatabase().query("mytable",null,"_id=?",new String[]{String.valueOf(id)},null,null,null);}私人长添加(字符串名称,字符串姓氏,字符串电话,SQLiteDatabase db){ContentValues cv = 新的 ContentValues();cv.put("name",name);cv.put(姓氏",姓氏);cv.put(电话",电话);返回 db.insert(mytable",null,cv);}public long add(String name, String surname, String phone) {return add(name,surname,phone,this.getWritableDatabase());}}

  • 重要注意事项 光标适配器需要一个 id 列,并将其命名为 _id.
  • 注意这会添加一些测试数据.
  • 包括所有访问方法
    • getAll 返回一个包含表中所有行的 Cursor.
    • 根据传递的值更新更新,它仅用于更新值(例如,由于没有 editSurname EditText,因此传递了 null,因此姓氏保持原样.)
    • getById 根据 id 返回一个包含所有值的游标
    • 不带第 4 个参数的 add 是典型的 add,带第 4 个参数的 add 是允许在 DatabaaeHelper 完全实例化之前在 onCreate 中使用它.

ListDataActivity

public class ListDataActivity extends AppCompatActivity {列表视图列表视图;SimpleCursorAdapter sca;数据库助手数据库助手;光标光标;@覆盖protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);listview = this.findViewById(R.id.mylistview);databaseHelper = new DatabaseHelper(this);setOrRefreshListView();}/* 处理列表视图 */私有无效 setOrRefreshListView() {游标 = databaseHelper.getAll();/* 获取要列出的数据 *//* 如果是第一次,则设置适配器侦听器等 */如果(sca == null){sca = 新的 SimpleCursorAdapter(这个,android.R.layout.simple_expandable_list_item_2,光标,new String[]{"name","phone"},新的 int[]{android.R.id.text1, android.R.id.text2},0);listview.setAdapter(sca);//将适配器附加到列表视图//setup On Item 点击开始更新活动传递idlistview.setOnItemClickListener(new AdapterView.OnItemClickListener() {@覆盖public void onItemClick(AdapterViewadapterView, View view, int i, long l) {Intent intent = new Intent(ListDataActivity.this,UpdateActivity.class);intent.putExtra(my_id_extra",l);开始活动(意图);}});//设置 on Item LONG 点击删除一行listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {@覆盖public boolean onItemLongClick(AdapterView<?>adapterView, View view, int i, long l) {databaseHelper.delete(l);setOrRefreshListView();//删除后刷新数据返回真;}});} 别的 {sca.swapCursor(光标);//如果不是第一次就告诉适配器数据已经改变了}}@覆盖protected void onResume() {super.onResume();setOrRefreshListView();//返回活动时刷新列表视图}@覆盖受保护的无效 onDestroy() {super.onDestroy();游标.关闭();//清理}}

ListDataActivity 的布局(非常基本的只是一个 ListView):-

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android";xmlns:tools="http://schemas.android.com/tools"机器人:方向=垂直"android:layout_width=match_parent"android:layout_height=match_parent"工具:上下文=.ListDataActivity"><文本视图android:layout_width="wrap_content";android:layout_height="wrap_content";android:text="Hello World!";/><列表视图android:id="@+id/mylistview";android:layout_width=match_parent"android:layout_height="wrap_content";android:background="@color/teal_200";></ListView></LinearLayout>

  • 设置背景以便于查看 ListView.

更新活动 :-

public class UpdateActivity extends AppCompatActivity {数据库助手数据库助手;EditText editName, editPhone;按钮 saveButtonId,showButtonId;长电流ID;@覆盖protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_update);editName = this.findViewById(R.id.editName);editPhone = this.findViewById(R.id.editPhone);saveButtonId = this.findViewById(R.id.savebuttonId);showButtonId = this.findViewById(R.id.showbuttonId);databaseHelper = new DatabaseHelper(this);currentId = this.getIntent().getLongExtra("my_id_extra",-1);如果 (currentId <0 ) {//做一些无效的 id 传递结束();}显示数据();showButtonId.setOnClickListener(new View.OnClickListener() {@覆盖公共无效onClick(查看视图){结束();}});saveButtonId.setOnClickListener(new View.OnClickListener() {@覆盖公共无效onClick(查看视图){databaseHelper.update(currentId,editName.getText().toString(),null,editPhone.getText().toString());}});}私有无效 showData() {Cursor cursor = databaseHelper.getById(currentId);如果 (cursor.moveToFirst()) {editName.setText(cursor.getString(cursor.getColumnIndex("name")));editPhone.setText(cursor.getString(cursor.getColumnIndex("phone")));}游标.关闭();}}

  • showData 按钮返回到 ListDataActivity(我相信这就是您想要的).

结果 :-

  1. 重新开始时:-

  1. 点击 Mary(并将数字编辑为 999999999 但不保存):-

  2. 点击保存(同 2)

  3. 点击显示:-

  1. 长按 Fred :-

  1. 重新启动应用程序:-

I am a beginner with SQLite Database. I have a problem with Update And Delete data from listView. I insert my data in listView when I click my listView data it will go in the UpdateActivity. Now I want To get those listView selected value in the new UpdateActivity so that I can edit or delete. How to do that.

ListDataActivity.Java

public  void loadData() {
                //Create an arraylist so that i can load the data to add in the  arraylist
                ArrayList<String> listData = new ArrayList<>();

                Cursor cursor = databaseHelper.showAllData();

        if (cursor.getCount() == 0) {
            Toast.makeText(getApplicationContext(), "no data is available", Toast.LENGTH_LONG).show();
        } else {
            while (cursor.moveToNext()) {
                listData.add(cursor.getString(1) + " \t " + cursor.getString(2));
            }
        }
                    
                ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.textViewId, listData);
                listView.setAdapter(adapter);

                listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                String selectedValue = adapterView.getItemAtPosition(position).toString();

                Toast.makeText(getApplicationContext(), "Selected Value : " + selectedValue, 
               Toast.LENGTH_LONG).show();
                Intent intent = new Intent(ListDataActivity.this,UpdateActivity.class);
                startActivity(intent);

            }
        });

UpdateActivity.Java

private DatabaseHelper databaseHelper;
    private String selectedName;
    private String selectedID;

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


        databaseHelper = new DatabaseHelper(this);
        SQLiteDatabase sqLiteDatabase = databaseHelper.getWritableDatabase();

        Intent receiveIntent = getIntent();

        selectedID = receiveIntent.getStringExtra("name");

        selectedName = receiveIntent.getStringExtra("surName");

When I insert data then I click on my list it goes into this type of design update activity. I want the Clicked Listview Data in the UpdateActivity. How can I solve that?

解决方案

Now I want To get those listview selected value in the new UpdateActity so that I can edit or delete. How to do that.

Here's a working example that updates (goes to UpdateActivity) and deletes (on Long Click of an Item). This uses a CursorAdapter, namely the stock SimpleCursorAdapter. Using Cursor adapters for SQLite data is pretty simple.

First the DatabaseHelper :-

class DatabaseHelper extends SQLiteOpenHelper {
    public DatabaseHelper(@Nullable Context context) {
        super(context, "mydatabase", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL("CREATE TABLE IF NOT EXISTS mytable (_id INTEGER PRIMARY KEY, name TEXT, surname TEXT, phone TEXT)");
        /* Add some test data */
        add("Fred","Bloggs","0000000000",sqLiteDatabase);
        add("Jane","Doe","1111111111",sqLiteDatabase);
        add("Mary","Johnston","2222222222",sqLiteDatabase);
        add("Tom","cobboly","3333333333",sqLiteDatabase);
        add("Anne","Walker","4444444444",sqLiteDatabase);

    }

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

    }

    public long update(long id, String name, String surname, String phone) {
        long rv = 0;
        ContentValues cv = new ContentValues();
        if (name != null && name.length() > 0) cv.put("name",name);
        if (surname != null && surname.length() > 0) cv.put("surname",surname);
        if (phone != null && phone.length() > 0) cv.put("phone",phone);
        if (cv.size() > 0) rv = this.getWritableDatabase().update("mytable",cv,"_id=?",new String[]{String.valueOf(id)});
        return rv;
    }

    public long delete(long id) {
        return this.getWritableDatabase().delete("mytable","_id=?",new String[]{String.valueOf(id)});
    }

    public Cursor getAll() {
        return this.getWritableDatabase().query("mytable",null,null,null,null,null,null);
    }

    public Cursor getById(long id) {
        return this.getWritableDatabase().query("mytable",null,"_id=?",new String[]{String.valueOf(id)},null,null,null);
    }

    private long add(String name, String surname, String phone, SQLiteDatabase db) {
        ContentValues cv = new ContentValues();
        cv.put("name",name);
        cv.put("surname",surname);
        cv.put("phone",phone);
        return db.insert("mytable",null,cv);
    }

    public long add(String name, String surname, String phone) {
        return add(name,surname,phone,this.getWritableDatabase());
    }
}

  • IMPORTANT NOTE Cursor adapters require an id column and that it be named _id.
  • NOTE this adds some testing data.
  • All access methods are included
    • getAll returns a Cursor with ALL rows from the table.
    • update updates according to the values passed, it caters for only updating the values (e.g. as there is no editSurname EditText, null is passed so the surname stays as it was.)
    • getById returns a cursor with all values according to the id
    • add without the 4th parameter is the typical add, the one with the 4th parameter is to allow it's use in onCreate before the DatabaaeHelper has been fully instantiated.

ListDataActivity

public class ListDataActivity extends AppCompatActivity {

    ListView listview;
    SimpleCursorAdapter sca;
    DatabaseHelper databaseHelper;
    Cursor cursor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listview = this.findViewById(R.id.mylistview);
        databaseHelper = new DatabaseHelper(this);
        setOrRefreshListView();
    }

    /* handles the ListView */
    private void setOrRefreshListView() {
        cursor = databaseHelper.getAll(); /* Gets the data to be listed */
        /* If first time then setup the adapter listeners etc */
        if (sca == null) {
            sca = new SimpleCursorAdapter(
                    this,
                    android.R.layout.simple_expandable_list_item_2,
                    cursor,
                    new String[]{"name","phone"},
                    new int[]{android.R.id.text1, android.R.id.text2},
                    0
            );
            listview.setAdapter(sca); // attach the adapter to the listview
            // setup On Item Click to start the update activity passing the id
            listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    Intent intent = new Intent(ListDataActivity.this,UpdateActivity.class);
                    intent.putExtra("my_id_extra",l);
                    startActivity(intent);
                }
            });
            // setup the on Item LONG Click to delete a row
            listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                @Override
                public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                    databaseHelper.delete(l);
                    setOrRefreshListView(); // after deletion refresh the data
                    return true;
                }
            });
        } else {
            sca.swapCursor(cursor); // if not the first time just tell the adapter the data has changed
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        setOrRefreshListView(); // refresh the listview when returning to the activity
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        cursor.close(); // clean up
    }
}

The layout for ListDataActivity (very basic just a ListView) :-

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ListDataActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

    <ListView
        android:id="@+id/mylistview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/teal_200"
        >
    </ListView>

</LinearLayout>

  • background set so it's easy to see the ListView.

UpdateActivity :-

public class UpdateActivity extends AppCompatActivity {

    DatabaseHelper databaseHelper;
    EditText editName, editPhone;
    Button saveButtonId,showButtonId;
    long currentId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update);
        editName = this.findViewById(R.id.editName);
        editPhone = this.findViewById(R.id.editPhone);
        saveButtonId = this.findViewById(R.id.savebuttonId);
        showButtonId = this.findViewById(R.id.showbuttonId);
        databaseHelper = new DatabaseHelper(this);
        currentId =  this.getIntent().getLongExtra("my_id_extra",-1);
        if (currentId < 0 ) {
            // do something as invalid id passed
            finish();
        }
        showData();
        showButtonId.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        saveButtonId.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                databaseHelper.update(currentId,editName.getText().toString(),null,editPhone.getText().toString());
            }
        });
    }

    private void showData() {
        Cursor cursor = databaseHelper.getById(currentId);
        if (cursor.moveToFirst()) {
            editName.setText(cursor.getString(cursor.getColumnIndex("name")));
            editPhone.setText(cursor.getString(cursor.getColumnIndex("phone")));
        }
        cursor.close();
    }
}

  • showData button returns to ListDataActivity (I believe that's what you wanted).

Result :-

  1. When started anew :-

  1. Click on Mary (and edit number to 999999999 but not save) :-

  2. Click Save (same as 2)

  3. Click Show :-

  1. Long Click Fred :-

  1. Restart the App :-

这篇关于如何使用单击侦听器更新和删除 SQLite 数据库中的列表视图数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆