如何执行更新和删除列表视图项行操作,而点击CursorAdapter的按钮 [英] How to Perform Update and Delete operation in listview item row while Click the button in CursorAdapter
问题描述
使用SQLite数据库中,我加入了板球运动员的名字,最后它的列表视图显示名称的帮助。
我添加了更新和CustomCursorAdapter.java.Below删除按钮,我贴的适配器code为:
CustomCursorAdapter.java:
进口android.content.Context;
进口android.database.Cursor;
进口android.view.LayoutInflater;
进口android.view.View;
进口android.view.ViewGroup;
进口android.widget.Button;
进口android.widget.CursorAdapter;
进口android.widget.TextView;
公共类CustomCursorAdapter扩展的CursorAdapter {
公共CustomCursorAdapter(上下文的背景下,光标C){
超(背景下,C);
}
@覆盖
公共查看NewView的(上下文的背景下,光标光标的ViewGroup父){
//当视图第一次将被创建,
//我们需要告诉适配器,怎么每个项目的外观
LayoutInflater充气= LayoutInflater.from(parent.getContext());
查看retView = inflater.inflate(R.layout.single_row_item,父母,假);
返回retView;
}
@覆盖
公共无效bindView(查看视图,上下文的背景下,光标光标){
//这里我们设置我们的数据
//这意味着,需要从游标中的数据,并把它放在意见
TextView的textViewPersonName =(TextView中)view.findViewById(R.id.tv_person_name);
textViewPersonName.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(1))));
//手柄按钮,并添加onClickListeners
按钮deleteBtn =(按钮)view.findViewById(R.id.delete_btn);
按钮updateBtn =(按钮)view.findViewById(R.id.update_btn);
deleteBtn.setOnClickListener(新View.OnClickListener(){
@覆盖
公共无效的onClick(视图v){
notifyDataSetChanged();
}
});
updateBtn.setOnClickListener(新View.OnClickListener(){
@覆盖
公共无效的onClick(视图v){
//做一点事
notifyDataSetChanged();
}
});
}
}
single_row_item.xml:
< XML版本=1.0编码=UTF-8&GT?;
< RelativeLayout的的xmlns:机器人=http://schemas.android.com/apk/res/android
机器人:layout_width =match_parent
机器人:layout_height =match_parent>
<按钮
机器人:ID =@ + ID / update_btn
机器人:layout_width =WRAP_CONTENT
机器人:layout_height =WRAP_CONTENT
机器人:layout_alignParentTop =真
机器人:layout_toLeftOf =@ + ID / delete_btn
机器人:文本=更新/>
<按钮
机器人:ID =@ + ID / delete_btn
机器人:layout_width =WRAP_CONTENT
机器人:layout_height =WRAP_CONTENT
机器人:layout_alignParentRight =真
机器人:layout_alignParentTop =真
机器人:文本=删除/>
<的TextView
机器人:ID =@ + ID / tv_person_name
机器人:layout_width =match_parent
机器人:layout_height =WRAP_CONTENT
机器人:layout_alignBaseline =@ + ID / add_btn
机器人:layout_alignBottom =@ + ID / add_btn
机器人:layout_alignParentLeft =真
机器人:paddingBottom会=5DP
机器人:文本=样本数据
机器人:TEXTSIZE =15sp/>
< / RelativeLayout的>
PersonDatabaseHelper.java:
进口android.content.ContentValues;
进口android.content.Context;
进口android.database.Cursor;
进口android.database.sqlite.SQLiteDatabase;
进口android.database.sqlite.SQLiteOpenHelper;
进口android.util.Log;
公共类PersonDatabaseHelper {
私有静态最后字符串变量= PersonDatabaseHelper.class.getSimpleName();
//数据库配置
//如果你想onUpgrade运行然后更改database_version
私有静态最终诠释DATABASE_VERSION = 1;
私有静态最后弦乐DATABASE_NAME =mydatabase.db;
//表配置
私有静态最后弦乐TABLE_NAME =person_table; //表的名字
私有静态最后弦乐PERSON_TABLE_COLUMN_ID =_id; //需要光标名为_id栏目
私有静态最后弦乐PERSON_TABLE_COLUMN_NAME =PERSON_NAME;
私有静态最后弦乐PERSON_TABLE_COLUMN_PIN =person_pin;
私人DatabaseOpenHelper openHelper;
私人SQLiteDatabase数据库;
//这是一个包装类。这意味着,从外面的世界,任何人都将与PersonDatabaseHelper沟通,
//但引擎盖下居然DatabaseOpenHelper类将执行数据库CRUD操作
公共PersonDatabaseHelper(上下文aContext){
openHelper =新DatabaseOpenHelper(aContext);
数据库= openHelper.getWritableDatabase();
}
公共无效insertData(字符串aPersonName,字符串aPersonPin){
//我们使用ContentValues避免SQL格式错误
ContentValues contentValues =新ContentValues();
contentValues.put(PERSON_TABLE_COLUMN_NAME,aPersonName);
contentValues.put(PERSON_TABLE_COLUMN_PIN,aPersonPin);
database.insert(TABLE_NAME,空,contentValues);
}
公共光标getAllData(){
字符串buildSQL =SELECT * FROM+ TABLE_NAME;
Log.d(TAG,getAllData SQL:+ buildSQL);
返回database.rawQuery(buildSQL,NULL);
}
//这DatabaseOpenHelper类将实际用于执行数据库相关的操作
私有类DatabaseOpenHelper扩展SQLiteOpenHelper {
公共DatabaseOpenHelper(上下文aContext){
超(aContext,DATABASE_NAME,空,DATABASE_VERSION);
}
@覆盖
公共无效的onCreate(SQLiteDatabase sqLiteDatabase){
//在这里创建你的表
字符串buildSQL =CREATE TABLE+ TABLE_NAME +(+ PERSON_TABLE_COLUMN_ID +INTEGER PRIMARY KEY,+
PERSON_TABLE_COLUMN_NAME +TEXT+ PERSON_TABLE_COLUMN_PIN +文本);
Log.d(TAG的onCreate SQL:+ buildSQL);
sqLiteDatabase.execSQL(buildSQL);
}
@覆盖
公共无效onUpgrade(SQLiteDatabase sqLiteDatabase,诠释oldVersion,诠释静态网页){
//数据库模式升级code到这里
字符串buildSQL =DROP TABLE IF EXISTS+ TABLE_NAME;
Log.d(TAG,onUpgrade SQL:+ buildSQL);
sqLiteDatabase.execSQL(buildSQL); //下跌previous表
的onCreate(sqLiteDatabase); //从开始创建表
}
}
}
输出:
在上面的截图,它显示了更新和删除button.If我点击更新按钮,它必须显示一个警告对话框,并编辑指定列表视图的名称,并显示出来。
然后,如果我点击删除按钮,就必须删除相应的列表视图行。
任何人都可以帮我this.Thank你。</ P>
最后,我对我的own.But,而不是使用光标适配器
我使用<$ C做了$ C>底座适配器来获取输出。
我提到这教程。我花了更多的时间来发现这个tutorial.It帮了我的lot.Then我改变了一些修改的头版和我的要求。
我改变我的头版就像this.Below我显示了该变化MainActivity:
MainActivity.java:
公共类MainActivity扩展活动实现OnClickListener {
私人按钮btn_add;
动作条动作条;
私人的ListView列表视图;
DatabaseHelper分贝;
公众的ArrayList&LT;产品型号&GT; _productlist =新的ArrayList&LT;产品型号&GT;();
/ **第一次创建活动时调用。 * /
@覆盖
公共无效的onCreate(包savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.main);
btn_add =(按钮)findViewById(R.id.btn_add);
btn_add.setOnClickListener(本);
列表视图=(ListView控件)findViewById(R.id.listview);
动作条= getActionBar();
ColorDrawable colorDrawable =新ColorDrawable(
Color.parseColor(#000000));
actionBar.setBackgroundDrawable(colorDrawable);
}
@覆盖
保护无效onResume(){
// TODO自动生成方法存根
super.onResume();
_productlist.clear();
DB =新DatabaseHelper(getApplicationContext());
db.getWritableDatabase();
ArrayList的&LT;产品型号&GT;所属类别= db.getProudcts();
的for(int i = 0; I&LT; product_list.size();我++){
串tidno = product_list.get(ⅰ).getIdno();
的System.out.println(tidno&GT;&GT;&GT;&GT;&gt;中+ tidno);
串TNAME = product_list.get(ⅰ).getProductname();
串tprice = product_list.get(ⅰ).getProductprice();
产品型号_ProductModel =新产品型号();
_ProductModel.setIdno(tidno);
_ProductModel.setProductname(TNAME);
_ProductModel.setProductprice(tprice);
_productlist.add(_ProductModel);
}
listview.setAdapter(新ListAdapter(本));
db.close();
}
私有类ListAdapter扩展了BaseAdapter {
LayoutInflater充气;
ViewHolder viewHolder;
公共ListAdapter(上下文的背景下){
// TODO自动生成构造函数存根
充气= LayoutInflater.from(上下文);
}
@覆盖
公众诠释getCount将(){
// TODO自动生成方法存根
返回_productlist.size();
}
@覆盖
公共对象的getItem(INT位置){
// TODO自动生成方法存根
返回的位置;
}
@覆盖
众长getItemId(INT位置){
// TODO自动生成方法存根
返回的位置;
}
@覆盖
公共查看getView(INT位置,查看convertView,ViewGroup中父){
// TODO自动生成方法存根
如果(convertView == NULL){
convertView = inflater.inflate(R.layout.listview_row,NULL);
viewHolder =新ViewHolder();
viewHolder.txt_pname =(TextView中)convertView
.findViewById(R.id.txtdisplaypname);
viewHolder.txt_pprice =(TextView中)convertView
.findViewById(R.id.txtdisplaypprice);
viewHolder.txtidno =(TextView中)convertView
.findViewById(R.id.txtdisplaypid);
convertView.setTag(viewHolder);
} 其他 {
viewHolder =(ViewHolder)convertView.getTag();
}
viewHolder.txt_pname.setText(_productlist.get(位置)
.getProductname()修剪())。
viewHolder.txt_pprice.setText(_productlist.get(位置)
.getProductprice()修剪())。
viewHolder.txtidno.setText(_productlist.get(位置).getIdno()
。修剪());
最终诠释临时=位置;
(convertView.findViewById(R.id.btn_update))
.setOnClickListener(新OnClickListener(){
公共无效的onClick(查看为arg0){
字符串_productid =将String.valueOf(_productlist
获得(临时).getIdno());
串_productname = _productlist.get(临时)
.getProductname();
串_productprice = _productlist.get(临时)
.getProductprice();
意向意图=新的意图(MainActivity.this,
AddUpdateValues.class);
束束=新包();
bundle.putString(ID,_productid);
bundle.putString(名,_productname);
bundle.putString(价格,_productprice);
intent.putExtras(包);
startActivity(意向);
}
});
(convertView.findViewById(R.id.btn_delete))
.setOnClickListener(新OnClickListener(){
公共无效的onClick(查看为arg0){
AlertDialog.Builder alertbox =新AlertDialog.Builder(
MainActivity.this);
alertbox.setCancelable(真正的);
alertbox.setMessage(你确定要删除?);
alertbox.setPositiveButton(是,
新DialogInterface.OnClickListener(){
公共无效的onClick(
DialogInterface为arg0,INT ARG1){
Log.i(&GT;&GT;&GT; TEMP&GT;&GT;&gt;中,温度+);
Log.i(&GT;&GT;&GT; getIdno&GT;&GT;&GT;&GT;&GT;&gt;中,
_productlist.get(临时)
.getIdno()。修剪()
+);
System.out的
.println(&GT;&GT;&GT; getIdno&GT;&GT;&GT;&GT;&GT;&gt;中
+ _productlist
获得(临时)
.getIdno()
。修剪());
db.removeProduct(
_productlist.get(临时)
.getIdno()。修剪()
,);
MainActivity.this.onResume();
Toast.makeText(
getApplicationContext(),
项目中删除......
Toast.LENGTH_SHORT).show();
}
});
alertbox.setNegativeButton(否,
新DialogInterface.OnClickListener(){
公共无效的onClick(
DialogInterface为arg0,INT ARG1){
}
});
alertbox.show();
}
});
返回convertView;
}
}
私有类ViewHolder {
TextView的txt_pname;
TextView的txt_pprice;
TextView的txtidno;
}
@覆盖
公共无效的onClick(视图v){
// TODO自动生成方法存根
开关(v.getId()){
案例R.id.btn_add:
意图addintent =新的意图(MainActivity.this,AddRecord.class);
startActivity(addintent);
打破;
默认:
打破;
}
}
}
我希望这个答案可能是有帮助的人。
With the help of sqlite database I am added the Cricket player name and finally it display the names in listview.
I am added the Update and delete button in CustomCursorAdapter.java.Below I am posted the Adapter code for that:
CustomCursorAdapter.java:
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.TextView;
public class CustomCursorAdapter extends CursorAdapter {
public CustomCursorAdapter(Context context, Cursor c) {
super(context, c);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// when the view will be created for first time,
// we need to tell the adapters, how each item will look
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View retView = inflater.inflate(R.layout.single_row_item, parent, false);
return retView;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
// here we are setting our data
// that means, take the data from the cursor and put it in views
TextView textViewPersonName = (TextView) view.findViewById(R.id.tv_person_name);
textViewPersonName.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(1))));
//Handle buttons and add onClickListeners
Button deleteBtn = (Button)view.findViewById(R.id.delete_btn);
Button updateBtn = (Button)view.findViewById(R.id.update_btn);
deleteBtn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
notifyDataSetChanged();
}
});
updateBtn.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
//do something
notifyDataSetChanged();
}
});
}
}
single_row_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="@+id/update_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toLeftOf="@+id/delete_btn"
android:text="Update" />
<Button
android:id="@+id/delete_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="Delete" />
<TextView
android:id="@+id/tv_person_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/add_btn"
android:layout_alignBottom="@+id/add_btn"
android:layout_alignParentLeft="true"
android:paddingBottom="5dp"
android:text="Sample Data"
android:textSize="15sp" />
</RelativeLayout>
PersonDatabaseHelper.java:
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;
public class PersonDatabaseHelper {
private static final String TAG = PersonDatabaseHelper.class.getSimpleName();
// database configuration
// if you want the onUpgrade to run then change the database_version
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "mydatabase.db";
// table configuration
private static final String TABLE_NAME = "person_table"; // Table name
private static final String PERSON_TABLE_COLUMN_ID = "_id"; // a column named "_id" is required for cursor
private static final String PERSON_TABLE_COLUMN_NAME = "person_name";
private static final String PERSON_TABLE_COLUMN_PIN = "person_pin";
private DatabaseOpenHelper openHelper;
private SQLiteDatabase database;
// this is a wrapper class. that means, from outside world, anyone will communicate with PersonDatabaseHelper,
// but under the hood actually DatabaseOpenHelper class will perform database CRUD operations
public PersonDatabaseHelper(Context aContext) {
openHelper = new DatabaseOpenHelper(aContext);
database = openHelper.getWritableDatabase();
}
public void insertData (String aPersonName, String aPersonPin) {
// we are using ContentValues to avoid sql format errors
ContentValues contentValues = new ContentValues();
contentValues.put(PERSON_TABLE_COLUMN_NAME, aPersonName);
contentValues.put(PERSON_TABLE_COLUMN_PIN, aPersonPin);
database.insert(TABLE_NAME, null, contentValues);
}
public Cursor getAllData () {
String buildSQL = "SELECT * FROM " + TABLE_NAME;
Log.d(TAG, "getAllData SQL: " + buildSQL);
return database.rawQuery(buildSQL, null);
}
// this DatabaseOpenHelper class will actually be used to perform database related operation
private class DatabaseOpenHelper extends SQLiteOpenHelper {
public DatabaseOpenHelper(Context aContext) {
super(aContext, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
// Create your tables here
String buildSQL = "CREATE TABLE " + TABLE_NAME + "( " + PERSON_TABLE_COLUMN_ID + " INTEGER PRIMARY KEY, " +
PERSON_TABLE_COLUMN_NAME + " TEXT, " + PERSON_TABLE_COLUMN_PIN + " TEXT )";
Log.d(TAG, "onCreate SQL: " + buildSQL);
sqLiteDatabase.execSQL(buildSQL);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
// Database schema upgrade code goes here
String buildSQL = "DROP TABLE IF EXISTS " + TABLE_NAME;
Log.d(TAG, "onUpgrade SQL: " + buildSQL);
sqLiteDatabase.execSQL(buildSQL); // drop previous table
onCreate(sqLiteDatabase); // create the table from the beginning
}
}
}
Output:
In that above screenshot,it shows the Update and delete button.If I click the Update button it have to show an alert dialog and edit the name of the specified listview and display it.
Then if I click the Delete button,it have to delete the appropriate listview row.
Anybody can help me with this.Thank you.
Finally I done it on my own.But instead of using Cursor Adapter
I am using Base Adapter
to get the output.
I referred this Tutorial.I took more time to find this tutorial.It helped me a lot.Then I change some modification for the front page and for my requirement.
I change my front page like this.Below I am showing the changes in MainActivity for that:
MainActivity.java:
public class MainActivity extends Activity implements OnClickListener {
private Button btn_add;
ActionBar actionBar;
private ListView listview;
DatabaseHelper db;
public ArrayList<ProductModel> _productlist = new ArrayList<ProductModel>();
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn_add = (Button) findViewById(R.id.btn_add);
btn_add.setOnClickListener(this);
listview = (ListView) findViewById(R.id.listview);
actionBar = getActionBar();
ColorDrawable colorDrawable = new ColorDrawable(
Color.parseColor("#000000"));
actionBar.setBackgroundDrawable(colorDrawable);
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
_productlist.clear();
db = new DatabaseHelper(getApplicationContext());
db.getWritableDatabase();
ArrayList<ProductModel> product_list = db.getProudcts();
for (int i = 0; i < product_list.size(); i++) {
String tidno = product_list.get(i).getIdno();
System.out.println("tidno>>>>>" + tidno);
String tname = product_list.get(i).getProductname();
String tprice = product_list.get(i).getProductprice();
ProductModel _ProductModel = new ProductModel();
_ProductModel.setIdno(tidno);
_ProductModel.setProductname(tname);
_ProductModel.setProductprice(tprice);
_productlist.add(_ProductModel);
}
listview.setAdapter(new ListAdapter(this));
db.close();
}
private class ListAdapter extends BaseAdapter {
LayoutInflater inflater;
ViewHolder viewHolder;
public ListAdapter(Context context) {
// TODO Auto-generated constructor stub
inflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return _productlist.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if (convertView == null) {
convertView = inflater.inflate(R.layout.listview_row, null);
viewHolder = new ViewHolder();
viewHolder.txt_pname = (TextView) convertView
.findViewById(R.id.txtdisplaypname);
viewHolder.txt_pprice = (TextView) convertView
.findViewById(R.id.txtdisplaypprice);
viewHolder.txtidno = (TextView) convertView
.findViewById(R.id.txtdisplaypid);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.txt_pname.setText(_productlist.get(position)
.getProductname().trim());
viewHolder.txt_pprice.setText(_productlist.get(position)
.getProductprice().trim());
viewHolder.txtidno.setText(_productlist.get(position).getIdno()
.trim());
final int temp = position;
(convertView.findViewById(R.id.btn_update))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
String _productid = String.valueOf(_productlist
.get(temp).getIdno());
String _productname = _productlist.get(temp)
.getProductname();
String _productprice = _productlist.get(temp)
.getProductprice();
Intent intent = new Intent(MainActivity.this,
AddUpdateValues.class);
Bundle bundle = new Bundle();
bundle.putString("id", _productid);
bundle.putString("name", _productname);
bundle.putString("price", _productprice);
intent.putExtras(bundle);
startActivity(intent);
}
});
(convertView.findViewById(R.id.btn_delete))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
AlertDialog.Builder alertbox = new AlertDialog.Builder(
MainActivity.this);
alertbox.setCancelable(true);
alertbox.setMessage("Are you sure you want to delete ?");
alertbox.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface arg0, int arg1) {
Log.i(">>>TEMP>>>", temp + "");
Log.i(">>>getIdno>>>>>>",
_productlist.get(temp)
.getIdno().trim()
+ "");
System.out
.println(">>>getIdno>>>>>>"
+ _productlist
.get(temp)
.getIdno()
.trim());
db.removeProduct(
_productlist.get(temp)
.getIdno().trim(),
"", "");
MainActivity.this.onResume();
Toast.makeText(
getApplicationContext(),
"Project Deleted...",
Toast.LENGTH_SHORT).show();
}
});
alertbox.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface arg0, int arg1) {
}
});
alertbox.show();
}
});
return convertView;
}
}
private class ViewHolder {
TextView txt_pname;
TextView txt_pprice;
TextView txtidno;
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btn_add:
Intent addintent = new Intent(MainActivity.this, AddRecord.class);
startActivity(addintent);
break;
default:
break;
}
}
}
I Hope this answer may be helpful to someone.
这篇关于如何执行更新和删除列表视图项行操作,而点击CursorAdapter的按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!