如何在单击 CursorAdapter 中的按钮时在列表视图项行中执行更新和删除操作

2023-12-10

在 sqlite 数据库的帮助下,我添加了板球运动员姓名,最后它在列表视图中显示了姓名。

我在 CustomCursorAdapter.java 中添加了更新和删除按钮。下面我发布了相应的适配器代码:

自定义CursorAdapter.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:

enter image description here

在上面的屏幕截图中,它显示了更新和删除按钮。如果我单击更新按钮,它必须显示一个警报对话框并编辑指定列表视图的名称并显示它。

然后,如果我单击“删除”按钮,它必须删除相应的列表视图行。

任何人都可以帮我解决这个问题。谢谢。


最后我自己完成了。但不是使用Cursor Adapter我在用Base Adapter得到输出。

我提到了这个Tutorial。我花了更多时间找到这个教程。它对我帮助很大。然后我对首页和我的要求进行了一些修改。

enter image description here

我像这样更改我的首页。下面我将展示 MainActivity 中的更改:

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

    }

}

我希望这个答案对某人有帮助。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在单击 CursorAdapter 中的按钮时在列表视图项行中执行更新和删除操作 的相关文章

随机推荐

  • Spotify 拼图问题

    我正在尝试解决本文中描述的 最佳之前 Spotify 难题page 基本上 输入三个由斜杠分隔的整数 例如 11 3 4 您应该生成一个具有 2011 03 04 格式的最早可能日期的输出 如果没有可能的日期 则应返回原始字符串 后跟 is
  • 使用哪种 MySQL 数据类型来存储布尔值

    由于MySQL似乎没有任何 布尔 数据类型 那么您 滥用 哪种数据类型来在MySQL中存储真 假信息 特别是在写入和读取 PHP 脚本的情况下 随着时间的推移 我使用并看到了几种方法 tinyint 包含值 0 1 的 varchar 字段
  • Crystal Reports 中的条件求和

    我有一些带有价格和数量的行 我只想对数量 gt 5 的价格求和 itemname price Qty apple 20 2 watermelon 10 3 bango 22 6 hashesh 3 9 根据以上数据 我想要得到的总和是 22
  • WPF 组合框“泄漏”内存

    我在 WPF 中遇到了组合框的问题 它们似乎挂在打开的第一个 DataContext 上 当我更改 ComboBox 上的 DataContext 时 子 PopupRoot 对象仍然引用旧的 DataContext 起初我以为我们做错了什
  • ContentTemplate 中绑定和 DataContext 的混淆

    考虑以下样式
  • Sass 循环遍历以数字开头的类名

    我正在循环遍历 sass 中的名称列表 当它到达类名以数字开头的点时 sass 似乎正在中断 事实上 当我注释掉以数值开头的类名时 sass 编译工作得很好 这就是说我无法重命名类名 我怎样才能让它发挥作用 下面是我尝试的代码 each c
  • 如何使用 OpenSSL 编译一个简单的程序?

    我正在尝试编译一个简单的 ssl 程序 它取自 openssl 书籍源代码 该程序有以下文件 common h common c client c server c 我已经安装了 openssl 0 9 7 所以我有与本书相同的版本 我已经
  • 在 wpf 和 gdi+ 之间转换图像时内存消耗过多

    我预计将 TransformedBitmap 转换为 System Drawing Bitmap 时会消耗太多内存 该图像相当大 具有 7360x4912 像素 采用 BGR32 像素格式 总计 144609280 位 138MB 最初 我
  • Google AdWords 转换服务问题 - 异步转换代码

    我从未在网站上实施过 Google Adwords 因此 如果我的 行话 有误 请随时纠正我 我正在开发一个网站 该网站有一个 Google AdWord 广告系列的登录页面 此页面上有一个表单 处理后会将您带到另一个页面并显示 感谢您的请
  • Web api 2 Web 服务中的 Dispose 方法

    我正在使用 Web api 2 Web 服务编写 MVC 5 互联网应用程序 我是否需要 Web 服务中的 DbContext 类的 dispose 方法 默认情况下它不存在 实际上 System Web Http ApiControlle
  • JMS Serializer:如何限制对象图的序列化深度

    也许这只是我对此注释的误解 但它似乎没有按预期工作 我有以下对象图 User gt Company gt Users gt Groups gt Permissions 正如你所看到的 会有一些递归 JMS 很好地处理了这个问题 它不序列化其
  • 使用 CSharpCodeProvider 允许用户创建函数

    我有一个现有的 asp net c 应用程序 我需要为用户提供一种创建灵活规则的方法 以计算给定雇用日期和注册日期的生效日期 可能使用的规则的一些示例 雇用日期或注册日期中较晚的一个 雇用日期 90 天 入学日期后的第一个月 如果注册日期在
  • 无扩展名 URL 尾部斜杠重定向

    我在几个 Dreamhost 域上测试了下面的代码 它可以工作 但 2012 年左右添加的新域除外 RewriteEngine on unless directory remove trailing slash RewriteCond RE
  • asp.net jquery ajax json:交换数据的简单示例

    在两个回复帖子的帮助下解决了问题 见下文 我希望能帮助您获得在浏览器 使用 JavaScript JQuery 和 ASP NET 使用 Visual Studio 2010 之间交换数据 JSON 数据的简单示例 当我单击按钮时 将执行以
  • 在 C 和 C++ 中访问数组超出限制 [重复]

    这个问题在这里已经有答案了 int data 8 data 9 1 C 标准对此有何规定 这是未定义的行为吗 至少C编译器 gcc std c99 pedantic W Wall 没有对此说什么 访问数组边界之外是未定义的行为 从c99标准
  • 获取 UIBezierPath Stroke 的轮廓路径

    我有一个UIBezierPath笔划 现在我想获取笔划的轮廓路径 不是笔划的路径本身 有什么方法可以得到吗 或者至少NSLog the UIBezierPath笔画的轮廓路径 谢谢 您可以使用CGPathCreateCopyByStroki
  • 如何制作一个只能订阅一次的轻量级“Replay”算子?

    在不同的场合我都希望有一个 RxReplay操作符缓冲传入的通知 在第一次订阅时同步重放其缓冲区 然后停止缓冲 这款轻量级Replay运营商应该只能为一名订户提供服务 可以找到此类运算符的一个用例here 在第一次订阅后继续缓冲只是浪费资源
  • Delphi中的串口同步

    我仍然遇到 TComPort 组件的问题 但这一次不是组件本身 而是它背后的逻辑 我有一个设备女巫通过串行端口发送一些 ascii 字符串 我需要解析这些字符串 问题是计算机反应非常快 所以在事件 char 中它只捕获字符串的一部分 字符串
  • 是否可以将 64 位 dll 加载到 32 位进程中?

    是否可以将 64 位 dll 加载到 32 位进程中 一般来说 我知道这不可能发生 然而 也许有一些例外 不可以 64 位进程都无法加载 32 位 DLL 如果您使用的是 64 位操作系统 则可以在 64 位进程中加载 DLL 并通过以下方
  • 如何在单击 CursorAdapter 中的按钮时在列表视图项行中执行更新和删除操作

    在 sqlite 数据库的帮助下 我添加了板球运动员姓名 最后它在列表视图中显示了姓名 我在 CustomCursorAdapter java 中添加了更新和删除按钮 下面我发布了相应的适配器代码 自定义CursorAdapter java