如何使用点击监听器更新和删除SQLite数据库中的列表视图数据?
How to update and delete the list View data in SQLite database with click listener?
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.
这是一个更新(转到 UpdateActivity)和删除(长按项目)的工作示例。这使用 CursorAdapter,即常用的 SimpleCursorAdapter。对 SQLite 数据使用 Cursor 适配器非常简单。
首先是 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());
}
}
- 重要说明 游标适配器需要一个 id 列并将其命名为 _id.
- 注意这增加了一些测试数据。
- 包括所有访问方法
- getAll returns 包含 table.
中所有行的游标
- update 根据传递的值进行更新,它仅适用于更新值(例如,由于没有 editSurname EditText,因此传递了 null,因此姓氏保持原样。)
- getById returns 根据 id
具有所有值的游标
- 不带第四个参数的add是典型的add,带第四个参数的是允许在DatabaaeHelper完全实例化之前在onCreate中使用。
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
}
}
ListDataActivity 的布局(非常基本,只是一个 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>
- 设置背景以便于查看 ListView。
更新活动:-
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 按钮 returns 到 ListDataActivity(我相信这就是您想要的)。
结果 :-
- 重新开始时:-
点击 Mary(并将号码编辑为 999999999 但不保存):-
点击保存(同2)
点击显示:-
- 长按弗雷德:-
- 重新启动应用程序:-
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.
这是一个更新(转到 UpdateActivity)和删除(长按项目)的工作示例。这使用 CursorAdapter,即常用的 SimpleCursorAdapter。对 SQLite 数据使用 Cursor 适配器非常简单。
首先是 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());
}
}
- 重要说明 游标适配器需要一个 id 列并将其命名为 _id.
- 注意这增加了一些测试数据。
- 包括所有访问方法
- getAll returns 包含 table. 中所有行的游标
- update 根据传递的值进行更新,它仅适用于更新值(例如,由于没有 editSurname EditText,因此传递了 null,因此姓氏保持原样。)
- getById returns 根据 id 具有所有值的游标
- 不带第四个参数的add是典型的add,带第四个参数的是允许在DatabaaeHelper完全实例化之前在onCreate中使用。
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
}
}
ListDataActivity 的布局(非常基本,只是一个 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>
- 设置背景以便于查看 ListView。
更新活动:-
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 按钮 returns 到 ListDataActivity(我相信这就是您想要的)。
结果 :-
- 重新开始时:-
点击 Mary(并将号码编辑为 999999999 但不保存):-
点击保存(同2)
点击显示:-
- 长按弗雷德:-
- 重新启动应用程序:-