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

Posted

技术标签:

【中文标题】单击 CursorAdapter 中的按钮时如何在列表视图项目行中执行更新和删除操作【英文标题】:How to Perform Update and Delete operation in listview item row while Click the button in CursorAdapter 【发布时间】:2015-02-14 09:16:00 【问题描述】:

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

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

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_
    android:layout_ >

    <Button
        android:id="@+id/update_btn"
        android:layout_
        android:layout_
        android:layout_alignParentTop="true"
        android:layout_toLeftOf="@+id/delete_btn"
        android:text="Update" />

    <Button
        android:id="@+id/delete_btn"
        android:layout_
        android:layout_
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:text="Delete" />

    <TextView
        android:id="@+id/tv_person_name"
        android:layout_
        android:layout_
        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
        
    

输出:

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

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

任何人都可以帮助我。谢谢。

【问题讨论】:

您不能覆盖光标适配器中的列表内容列表,您必须使用 BaseAdapter 并覆盖活动中的 listitemclick。 使用 BaseAdapter,当你点击更新时,可能会打开一些对话框 @AndroidDeveloper 它似乎与光标适配器一起工作正常。我的所有代码仅与光标适配器相关。可能与光标适配器有关。 光标适配器似乎工作正常。我的所有代码仅与光标适配器有关。光标适配器有可能与@NaveenTamrakar 当我看到您的代码时,您还没有从光标中删除该行。你应该在从光标删除后调用 notifydatasetchanged 【参考方案1】:

最后我自己完成了。但是我没有使用Cursor Adapter,而是使用Base Adapter 来获取输出。

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

我像这样更改我的首页。下面我将显示 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;
        

    


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

【讨论】:

那个链接是代理的

以上是关于单击 CursorAdapter 中的按钮时如何在列表视图项目行中执行更新和删除操作的主要内容,如果未能解决你的问题,请参考以下文章

在 searchview 中键入时如何更改 listview-cursoradapter 中搜索文本的背景颜色?

如何在单击按钮时暂停读取文本文件并在 mfc vc++ 中的单击按钮时恢复它?

如何在按钮单击时关闭 uwp 中的吐司

如何在单击 ListView 中的按钮时取消选中所有列表项

Android:单击片段中的按钮时如何通知活动? [复制]

如何在单击 PHP 中的按钮时动态插入列表框?