编辑/删除Android的SQLite的数据基行 [英] Edit/Delete rows of SQLite-data-base in android

查看:121
本文介绍了编辑/删除Android的SQLite的数据基行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用本教程写一个Android程序,显示在ListView数据库中的字段。现在我要对它们进行编辑(编辑/删除)ActionMode的按钮。

请你帮我写的编辑和删除code?
这是我的项目code:

MyActivity.java类:

 公共类MyActivity延伸活动{
私人的ListView ListView的;
私人DataBaseClass classDB;
私人SQLiteDatabase SQLDB;
私人的ArrayList<串GT; ID =新的ArrayList<串GT;(); //誓言ID
私人的ArrayList<串GT;数=新的ArrayList<串GT;(); //誓言文本ListView.MultiChoiceModeListener回调;@覆盖
公共无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.main);    回调=新ListView.MultiChoiceModeListener(){
        @覆盖
        公共布尔onCreateActionMode(ActionMode模式,菜单菜单){
            mode.setTitle(演示);
            。getMenuInflater()膨胀(R.menu.action_mode_menu,菜单);
            返回true;
        }        @覆盖
        在prepareActionMode公共布尔(ActionMode模式,菜单菜单){
            返回true;
        }        @覆盖
        公共布尔onActionItemClicked(ActionMode模式,菜单项项){
            开关(item.getItemId()){
            案例R.id.editBTN:
                editBTN(); //编辑方法
                mode.finish();
                打破;
            案例R.id.deleteBTN:
                 AlertDialog.Builder构建=新AlertDialog.Builder(MyActivity.this);
                build.setMessage(你要删除\\ r \\ n吗?+ adapter.getPropertiesByPosition(adapter.selectedViewsPositions.get(0),头衔));                如果(adapter.selectedViewsPositions.size()== 1){
                    //build.setTitle(\"Do要删除)?;                    build.setMessage(你要删除\\ r \\ n吗?+ adapter.getPropertiesByPosition(adapter.selectedViewsPositions.get(0),头衔));
                }其他{
                    //build.setTitle(\"Delete)?;
                    build.setMessage(删除这些+ adapter.selectedViewsPositions.size()+保存的网页?);
                }                build.setPositiveButton(删除,
                        新DialogInterface.OnClickListener(){                            公共无效的onClick(DialogInterface对话,诠释它){
                                ProgressDialog PD =新ProgressDialog(MyActivity.this);
                                pd.setMessage(删除的项目......);
                                pd.setIndeterminate(假);
                                pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                                pd.setMax(adapter.selectedViewsPositions.size());
                                pd.setCancelable(假);
                                pd.setCanceledOnTouchOutside(假);                                pd.show();                                classDB =新DataBaseClass(MyActivity.this);
                                SQLDB = classDB.getWritableDatabase();                                对于(整数位置:adapter.selectedViewsPositions){
                                    sqlDB.delete(DataBaseClass.TABLE_NAME,DataBaseClass.COLUMN_ID +=+ adapter.getPropertiesByPosition(位置,ID),NULL);
                                    pd.setProgress(adapter.selectedViewsPositions.indexOf(位置));                                }
                                sqlDB.close();
                                pd.hide();
                                pd.cancel();                                //Toast.makeText(MyActivity.this,\"Deleted+ gridAdapter.selectedViewsPositions.size()+保存网页,Toast.LENGTH_LONG).show();
                                mode.finish();
                            }
                        });                build.setNegativeButton(取消,
                        新DialogInterface.OnClickListener(){                            公共无效的onClick(DialogInterface对话框,
                                                其中INT){
                                dialog.cancel();
                                mode.finish();
                            }
                        });
                AlertDialog警报= build.create();
                alert.show();
                打破;
            案例R.id.doneBTN:
                //!?更改列表视图的背景颜色
                打破;
            }
            返回true;
        }        @覆盖
        公共无效onDestroyActionMode(ActionMode模式){        }        @覆盖
        公共无效onItemCheckedStateChanged(ActionMode模式,
                INT位置,长的ID,布尔检查){
        }
    };    ListView控件=(ListView控件)findViewById(R.id.ListView);
    listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
    listView.setMultiChoiceModeListener(回调);    classDB =新DataBaseClass(本);
}// *****************添加VOW菜单按钮
公共布尔onCreateOptionsMenu(菜单菜单){
    。getMenuInflater()膨胀(R.menu.add,菜单);
    返回true;
}@覆盖
公共布尔onOptionsItemSelected(菜单项项){
    super.onOptionsItemSelected(项目);
    开关(item.getItemId()){
    案例R.id.add_menu:
        意向意图=新意图(getApplicationContext()
                AddActivity.class);
        intent.putExtra(更新,FALSE);
        startActivity(意向);
        返回true;
    默认:
        返回super.onOptionsItemSelected(项目);
    }
}@覆盖
保护无效onResume(){
    displayData();
    super.onResume();
}私人无效displayData(){//显示来自SQLite的数据
    SQLDB = classDB.getWritableDatabase();
    光标mCursor = sqlDB.rawQuery(SELECT * FROM
            + DataBaseClass.TABLE_NAME,NULL);    Id.clear();
    number.clear();
    如果(mCursor.moveToFirst()){
        做{
            Id.add(mCursor.getString(mCursor
                    .getColumnIndex(DataBaseClass.COLUMN_ID)));
            number.add(mCursor.getString(mCursor
                    .getColumnIndex(DataBaseClass.COLUMN_NUMBER)));        }而(mCursor.moveToNext());
    }
    MyAdapter适配器=新MyAdapter(本,身份证,号码);
    listView.setAdapter(适配器);
    mCursor.close();
}

DataBaseClass.java:

 公共类DataBaseClass扩展SQLiteOpenHelper {
静态字符串DATABASE_NAME =用户信息;
公共静态最后弦乐TABLE_NAME =誓言;
公共静态最后弦乐COLUMN_ID =ID;
公共静态最后弦乐COLUMN_NUMBER =数字;公共DataBaseClass(上下文的背景下){
    超级(上下文,DATABASE_NAME,空,1);
}@覆盖
公共无效的onCreate(SQLiteDatabase DB){
    字符串CREATE_TABLE =CREATE TABLE+ TABLE_NAME +(+ COLUMN_ID +INTEGER PRIMARY KEY,+ COLUMN_NUMBER +TEXT);
    db.execSQL(CREATE_TABLE);
}@覆盖
公共无效onUpgrade(SQLiteDatabase分贝,INT oldVersion,诠释静态网页){
    db.execSQL(DROP TABLE IF EXISTS+ TABLE_NAME);
    的onCreate(DB);}

MyAdapter.java类:

 公共类MyAdapter延伸BaseAdapter {
私人上下文的背景下;
私人的ArrayList<串GT;中;
私人的ArrayList<串GT; Mnumber;公众的ArrayList<整数GT; selectedViewsPositions =新的ArrayList<整数GT;();
公共光标dbCursor;公共MyAdapter(上下文C,ArrayList的<弦乐> ID,ArrayList的<串GT;号码){
    上下文= C;
    MID = ID;
    Mnumber =号;
}@覆盖
公众诠释的getCount(){
    返回MId.size();
}@覆盖
公共对象的getItem(int i)以{
    返回null;
}@覆盖
众长getItemId(int i)以{
    返回0;
}@覆盖
公共查看getView(INT I,观景,ViewGroup中的ViewGroup){
    持有人mHolder;
    LayoutInflater layoutInflater;
    如果(查看== NULL){
        layoutInflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        鉴于= layoutInflater.inflate(R.layout.list_item,NULL);
        mHolder =新持有人();
        mHolder.txt_id =(TextView中)view.findViewById(R.id.id);
        mHolder.txt_Number =(TextView中)view.findViewById(R.id.number);
        view.setTag(mHolder);
    }其他{
        mHolder =(座)view.getTag();
    }
    mHolder.txt_id.setText(MId.get(I));
    mHolder.txt_Number.setText(Mnumber.get(I));    返回视图。
}公共类持有人{
    TextView的txt_id;
    TextView的txt_Number;
}公共字符串getPropertiesByPosition(INT位置,字符串类型){    dbCursor.moveToPosition(位置);    如果(type.equals(ID)){
        返回dbCursor.getString(dbCursor.getColumnIndex(DataBaseClass.COLUMN_ID));
    }    否则如果(type.equals(numbert)){
        返回dbCursor.getString(dbCursor.getColumnIndex(DataBaseClass.COLUMN_NUMBER));
    }    其他{返回null; }
}

AddActivity.java类:

 公共类AddActivity延伸活动{
私人的EditText addNUM;
私人的DatePicker ADDDATE;私人按钮insertBTN;
私人按钮deleteBTN;私人DataBaseClass classDB;
私人SQLiteDatabase SQLDB;私人字符串ID;
私人串号;
私人布尔isUpdate;公共无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.add_activity);    classDB =新DataBaseClass(本);    addNUM =(EditText上)findViewById(R.id.addNum);    insertBTN =(按钮)findViewById(R.id.insert);
    deleteBTN =(按钮)findViewById(R.id.deleteBTN);    insertBTN.setOnClickListener(新View.OnClickListener(){
        @覆盖
        公共无效的onClick(查看视图){
            数= addNUM.getText()的toString()修剪()。            如果(number.length()大于0&放大器;&放大器; number.length()大于0){
                保存数据();
            }其他{
                AlertDialog.Builder alertBuilder =新AlertDialog.Builder(AddActivity.this);
                alertBuilder.setTitle(无效数据);
                alertBuilder.setMessage(请输入有效数据);
                alertBuilder.setPositiveButton(OK,新DialogInterface.OnClickListener(){                    公共无效的onClick(DialogInterface对话,诠释它){
                        dialog.cancel();
                    }
                });
                alertBuilder.create()显示()。
            }
        }
    });    isUpdate = getIntent()getExtras()getBoolean(更新)。
    如果(isUpdate){
        。ID = getIntent()getExtras()的getString(ID);
        。数= getIntent()getExtras()的getString(编号);
        addNUM.setText(数);
    }}私人无效SAVEDATA(){//将数据存入SQLite的
    classDB =新DataBaseClass(本);
    SQLDB = classDB.getWritableDatabase();
    ContentValues​​值=新ContentValues​​();    values​​.put(DataBaseClass.COLUMN_NUMBER,数);    的System.out.println();
    如果(isUpdate)
    {
        //用新的数据更新数据库
        sqlDB.update(DataBaseClass.TABLE_NAME,价值观,DataBaseClass.COLUMN_ID +=+ ID,NULL);
    }其他{
        //将数据插入到数据库
        sqlDB.insert(DataBaseClass.TABLE_NAME,空,价值);
    }
    //关闭数据库
    sqlDB.close();
    完();
}

我有3个问题:
1,如何编辑整排与ActionMode按钮编辑按钮?
2-如何删除他整排与ActionMode按钮,删除按钮?
3如何改变ListView的行上ActionMode按钮完成按钮?

点击颜色

这是LogCat中:

  9月6日至4日:36:28.847 1884年至1884年/? V / AudioPolicyManagerBase:setOutputDevice()输出2设备0002部队0 delayMs 0
9月6日至4日:36:28.847 1884年至2151年/? D / AudioHardwareTinyALSA:OutALSA :: setDevice:模式= 0,newDevice = 0X2,currentDevice = 0X2,力= 0
9月6日至4日:36:29.077 1884年至1884年/? V / AudioPolicyManagerBase:setOutputDevice()输出2设备0000部队0 delayMs 184
9月6日至4日:36:39.592 1884年至2154年/? V / AudioPolicyManagerBase:setOutputDevice()输出2设备0002部队0 delayMs 0
9月6日至4日:36:39.607 1884年至2151年/? D / AudioHardwareTinyALSA:OutALSA :: setDevice:模式= 0,newDevice = 0X2,currentDevice = 0X2,力= 0
9月6日至4日:36:40.192 1884-25939 /? V / AudioPolicyManagerBase:setOutputDevice()输出2设备0000部队0 delayMs 184
9月6日至4日:38:36.412 1884年至1884年/? V / AudioPolicyManagerBase:setOutputDevice()输出2设备0002部队0 delayMs 0
9月6日至4日:38:36.417 1884年至2151年/? D / AudioHardwareTinyALSA:OutALSA :: setDevice:模式= 0,newDevice = 0X2,currentDevice = 0X2,力= 0
9月6日至4日:38:36.647 1884年至1884年/? V / AudioPolicyManagerBase:setOutputDevice()输出2设备0000部队0 delayMs 184
9月6日至4日:38:38.317 1884年至2181年/? V / AudioPolicyManagerBase:setOutputDevice()输出2设备0002部队0 delayMs 0
9月6日至4日:38:38.572 1884年至2181年/? V / AudioPolicyManagerBase:setOutputDevice()输出2设备0000部队0 delayMs 184
9月6日至4日:38:52.677 1884年至2181年/? V / AudioPolicyManagerBase:setOutputDevice()输出2设备0002部队0 delayMs 0
9月6日至4日:38:52.687 1884年至2151年/? D / AudioHardwareTinyALSA:OutALSA :: setDevice:模式= 0,newDevice = 0X2,currentDevice = 0X2,力= 0
9月6日至4日:38:52.917 1884年至1884年/? V / AudioPolicyManagerBase:setOutputDevice()输出2设备0000部队0 delayMs 184
9月6日至4日:38:54.287 1884年至2154年/? V / AudioPolicyManagerBase:setOutputDevice()输出2设备0002部队0 delayMs 0
9月6日至4日:38:54.542 1884年至2154年/? V / AudioPolicyManagerBase:setOutputDevice()输出2设备0000部队0 delayMs 184
9月6日至4日:38:54.767 1884年至1884年/? V / AudioPolicyManagerBase:setOutputDevice()输出2设备0002部队0 delayMs 0
9月6日至4日:38:55.032 1884年至1884年/? V / AudioPolicyManagerBase:setOutputDevice()输出2设备0000部队0 delayMs 184
9月6日至4日:38:56.827 1884-28672 /? V / AudioPolicyManagerBase:setOutputDevice()输出2设备0002部队0 delayMs 0
9月6日至4日:38:59.892 1884年至1884年/? V / AudioPolicyManagerBase:setOutputDevice()输出2设备0002部队0 delayMs 0
9月6日至4日:39:00.052 1884年至2176年/? V / AudioPolicyManagerBase:setOutputDevice()输出2设备0002部队0 delayMs 184
9月6日至4日:39:00.162 1884年至2176年/? V / AudioPolicyManagerBase:setOutputDevice()输出2设备0000部队0 delayMs 184
9月6日至4日:39:01.672 1884年至1884年/? V / AudioPolicyManagerBase:setOutputDevice()输出2设备0002部队0 delayMs 0
9月6日至4日:39:01.927 1884年至1884年/? V / AudioPolicyManagerBase:setOutputDevice()输出2设备0000部队0 delayMs 184
9月6日至4日:39:13.257 1884年至2176年/? V / AudioPolicyManagerBase:setOutputDevice()输出2设备0002部队0 delayMs 0
9月6日至4日:39:13.267 1884年至2151年/? D / AudioHardwareTinyALSA:OutALSA :: setDevice:模式= 0,newDevice = 0X2,currentDevice = 0X2,力= 0
9月6日至4日:39:13.497 1884年至2176年/? V / AudioPolicyManagerBase:setOutputDevice()输出2设备0000部队0 delayMs 184
9月6日至4日:39:14.782 1884年至2154年/? V / AudioPolicyManagerBase:setOutputDevice()输出2设备0002部队0 delayMs 0
9月6日至4日:39:15.052 1884年至2154年/? V / AudioPolicyManagerBase:setOutputDevice()输出2设备0000部队0 delayMs 184
9月6日至4日:45:21.852 1884年至2176年/? V / AudioPolicyManagerBase:setOutputDevice()输出2设备0002部队0 delayMs 0
9月6日至4日:45:21.867 1884年至2151年/? D / AudioHardwareTinyALSA:OutALSA :: setDevice:模式= 0,newDevice = 0X2,currentDevice = 0X2,力= 0
9月6日至4日:45:23.502 1884-18891 /? V / AudioPolicyManagerBase:setOutputDevice()输出2设备0000部队0 delayMs 184
9月6日至4日:47:09.712 2233年至2347年/? I / ActivityManager:杀PROC 18535:com.example.draft_vow / u0a211:强行停止


解决方案

新的编辑
抱歉耽搁XD

数据库AgendaSqlite.java

 进口android.content.Context;
进口android.database.sqlite.SQLiteDatabase;
进口android.database.sqlite.SQLiteDatabase.CursorFactory;
进口android.database.sqlite.SQLiteOpenHelper;公共类AgendaSqlite扩展SQLiteOpenHelper {    // Sentencia SQL对CREAR拉塔布拉德USUARIOS
    字符串sqlCreate =CREATE TABLE誓要(_id INTEGER PRIMARY KEY,数字INTEGER);    公共AgendaSqlite(上下文的背景下,字符串名称,CursorFactory工厂,诠释的版本){
        超(背景下,名称,厂家,版本);
    }    @覆盖
    公共无效的onCreate(SQLiteDatabase DB){
        db.execSQL(sqlCreate);
    }    @覆盖
    公共无效的OnOpen(SQLiteDatabase DB){
        super.onOpen(DB);
        如果(!db.isReadOnly()){
            //启用外键约束
            db.execSQL(PRAGMA foreign_keys = ON;);
        }
    }    @覆盖
    公共无效onUpgrade(SQLiteDatabase分贝,INT oldVersion,诠释静态网页){
        // eliminamos LA版前德拉塔布拉
        db.execSQL(DROP TABLE是否存在誓要);        //褐creamos拉新世界译本德拉塔布拉
        db.execSQL(sqlCreate);
    }
}

编辑/删除,在这里,你需要一个EDITTEXT什么让你要删除/编辑次数

 公共类MyActivity延伸活动{
私人的ListView ListView的;
私人DataBaseClass classDB;
私人SQLiteDatabase SQLDB;
私人的ArrayList<串GT; ID =新的ArrayList<串GT;(); //誓言ID
私人的ArrayList<串GT;数=新的ArrayList<串GT;(); //誓言文本
串C1 =,C2 =,C3 =,C4 =,C5 =,C6 =;
字符串翅=;
SQLiteDatabase分贝;
光标光标;
最后弦乐TABLA_PRINCIPAL =誓言; //表
最后弦乐NOMBRE_BASE_DATOS =userInformation.db; //数据库
AgendaSqlite usdbh;
INT数= 0,numberCorrect = 0;
INT ID = 0,idCorrect = 0;
ListView.MultiChoiceModeListener回调;@覆盖
公共无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.main);
    串ArchivoDB = Environment.getExternalStorageDirectory()getAbsolutePath()+/+ NOMBRE_BASE_DATOS。
    usdbh =新AgendaSqlite(这一点,ArchivoDB,NULL,1); //
    DB = usdbh.getWritableDatabase();    回调=新ListView.MultiChoiceModeListener(){
        @覆盖
        公共布尔onCreateActionMode(ActionMode模式,菜单菜单){
            mode.setTitle(演示);
            。getMenuInflater()膨胀(R.menu.action_mode_menu,菜单);
            返回true;
        }        @覆盖
        在prepareActionMode公共布尔(ActionMode模式,菜单菜单){
            返回true;
        }        @覆盖
        公共布尔onActionItemClicked(ActionMode模式,菜单项项){
            开关(item.getItemId()){
            案例R.id.editBTN:
                editBTN(); //编辑方法
                mode.finish();
                打破;
            案例R.id.deleteBTN:
                deleteBTN(); //删除!?方法
                mode.finish();
                打破;
            案例R.id.doneBTN:
                //!?更改列表视图的背景颜色
                打破;
            }
            返回true;
        }        @覆盖
        公共无效onDestroyActionMode(ActionMode模式){        }        @覆盖
        公共无效onItemCheckedStateChanged(ActionMode模式,
                INT位置,长的ID,布尔检查){
        }
    };    ListView控件=(ListView控件)findViewById(R.id.ListView);
    listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
    listView.setMultiChoiceModeListener(回调);    classDB =新DataBaseClass(本);
}// *****************添加VOW菜单按钮
公共布尔onCreateOptionsMenu(菜单菜单){
    。getMenuInflater()膨胀(R.menu.add,菜单);
    返回true;
}@覆盖
公共布尔onOptionsItemSelected(菜单项项){
    super.onOptionsItemSelected(项目);
    开关(item.getItemId()){
    案例R.id.add_menu:
        意向意图=新意图(getApplicationContext()
                AddActivity.class);
        intent.putExtra(更新,FALSE);
        startActivity(意向);
        返回true;
    默认:
        返回super.onOptionsItemSelected(项目);
    }
}@覆盖
保护无效onResume(){
    displayData();
    super.onResume();
}
/ *
私人无效displayData(){//显示来自SQLite的数据
    SQLDB = classDB.getWritableDatabase();
    光标mCursor = sqlDB.rawQuery(SELECT * FROM
            + DataBaseClass.TABLE_NAME,NULL);    Id.clear();
    number.clear();
    如果(mCursor.moveToFirst()){
        做{
            Id.add(mCursor.getString(mCursor
                    .getColumnIndex(DataBaseClass.COLUMN_ID)));
            number.add(mCursor.getString(mCursor
                    .getColumnIndex(DataBaseClass.COLUMN_NUMBER)));        }而(mCursor.moveToNext());
    }
    MyAdapter适配器=新MyAdapter(本,身份证,号码);
    listView.setAdapter(适配器);
    mCursor.close();
} * /
editBTN(){
            //获取数从编辑文本或东西删除
            更新();
            字串[] args =新的String [] {} C1;
            db.execSQL(UPDATE+ TABLA_PRINCIPAL +SET编号='+数字+'WHERE _id =?,参数);
            Toast.makeText(getApplicationContext(),更新!,Toast.LENGTH_LONG).show();}    无效更新()/////// contarenacion德洛斯DATOS
    {
        C1 =; C2 =; C3 =; C4 =; C5 =; C6 =;
        鳍片=;
        光标= db.rawQuery(选择*+ TABLA_PRINCIPAL,NULL);        如果(cursor.getCount()!= 0){
            如果(cursor.moveToFirst()){
                做{
                    C1 = cursor.getString(光标
                            .getColumnIndex(_ ID)); //获取_id
                    如果(ID == C1){
                        idCorrect = C1;
                    }                    C2 = cursor.getString(光标
                            .getColumnInteger(数字)); //获取数
                    如果(数字== C2){
                        numberCorrect = C2;
                    }
                }而(cursor.moveToNext());
            }
        }
        cursor.close();
    }    deleteBTN(){
        //获取numberto从编辑文本或东西删除
        更新();
        字串[] args =新的String [] {} C2;
        db.execSQL(DELETE FROM+ TABLA_PRINCIPAL +WHERE数=?,参数);
        Toast.makeText(getApplicationContext(),删除!,Toast.LENGTH_LONG).show();
    }
}


如果你想删除使用database.exeSQL做到这一点,在这里你去:

  delete.setOnClickListener(新Button.OnClickListener(){
        公共无效的onClick(视图v){
            。名称= paciente.getText()的toString(); //获取您要删除什么nameof
            如果(name.matches()){//检查它是否是空的
                Toast.makeText(getBaseContext(),无论你想/ ALERT,Toast.LENGTH_LONG).show();
            }其他{
                字串[] args =新的String [] {名};
                db.execSQL(DELETE FROM+ YOUR_TABLE +WHERE的ColumnName =?,参数);
                Toast.makeText(getApplicationContext(),无论你想要什么,Toast.LENGTH_LONG).show();
                espacioHistorial.setText();
            }
        }
    });

更新是一个按钮相似的:

 字串[] args =新的String [] {农布雷}; //名称或ID任何你想要的
                    db.execSQL(UPDATE+ TABLA_PRINCIPAL +SET sintomas ='+ sintomas +',diagnostico ='+ diagnostico1 +'WHERE nombre_paciente =?,参数); //使用SET你说该列将更新一个新的字符串
                    Toast.makeText(getApplicationContext(),告警,Toast.LENGTH_LONG).show();

希望这有助于,再见

I'm using this tutorial for writing an Android program that shows the database's field in a ListView. Now I want to edit them (edit/delete) with ActionMode's buttons.

Would you please help me write editing and deleting code? This is my project code:

MyActivity.java class:

public class MyActivity extends Activity {
private ListView listView;
private DataBaseClass classDB;
private SQLiteDatabase sqlDB;
private ArrayList<String> Id = new ArrayList<String>(); // vows id
private ArrayList<String> number = new ArrayList<String>(); // vows text

ListView.MultiChoiceModeListener callback;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    callback = new ListView.MultiChoiceModeListener() {
        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            mode.setTitle("Demo");
            getMenuInflater().inflate(R.menu.action_mode_menu, menu);
            return true;
        }

        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            return true;
        }

        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            switch (item.getItemId()) {
            case R.id.editBTN:
                editBTN();//edit method
                mode.finish(); 
                break;
            case R.id.deleteBTN:
                 AlertDialog.Builder build = new AlertDialog.Builder(MyActivity.this);
                build.setMessage("Do you want to delete ?\r\n" + adapter.getPropertiesByPosition(adapter.selectedViewsPositions.get(0), "title"));

                if (adapter.selectedViewsPositions.size() == 1) {
                    //build.setTitle("Do you want to delete ?");

                    build.setMessage("Do you want to delete ?\r\n" + adapter.getPropertiesByPosition(adapter.selectedViewsPositions.get(0), "title"));
                } else {
                    //build.setTitle("Delete ?");
                    build.setMessage("Delete these " + adapter.selectedViewsPositions.size() + " saved pages ?");
                }

                build.setPositiveButton("Delete",
                        new DialogInterface.OnClickListener() {

                            public void onClick(DialogInterface dialog, int which) {
                                ProgressDialog pd = new ProgressDialog(MyActivity.this);
                                pd.setMessage("Deleting items...");
                                pd.setIndeterminate(false);
                                pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                                pd.setMax(adapter.selectedViewsPositions.size());
                                pd.setCancelable(false);
                                pd.setCanceledOnTouchOutside(false);

                                pd.show();

                                classDB = new DataBaseClass(MyActivity.this);
                                sqlDB = classDB.getWritableDatabase();

                                for (Integer position: adapter.selectedViewsPositions) {
                                    sqlDB.delete(DataBaseClass.TABLE_NAME, DataBaseClass.COLUMN_ID + "=" + adapter.getPropertiesByPosition(position, "id"), null);
                                    pd.setProgress(adapter.selectedViewsPositions.indexOf(position));

                                }
                                sqlDB.close();


                                pd.hide();
                                pd.cancel();

                                //Toast.makeText(MyActivity.this,"Deleted " + gridAdapter.selectedViewsPositions.size() + " saved pages", Toast.LENGTH_LONG).show();


                                mode.finish();
                            }
                        });

                build.setNegativeButton("Cancel",
                        new DialogInterface.OnClickListener() {

                            public void onClick(DialogInterface dialog,
                                                int which) {
                                dialog.cancel();
                                mode.finish();
                            }
                        });
                AlertDialog alert = build.create();
                alert.show();                   
                break;
            case R.id.doneBTN:
                //!?change background color of list view
                break;
            }
            return true;
        }

        @Override
        public void onDestroyActionMode(ActionMode mode) {

        }

        @Override
        public void onItemCheckedStateChanged(ActionMode mode,
                int position, long id, boolean checked) {
        }
    };

    listView = (ListView) findViewById(R.id.ListView);
    listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
    listView.setMultiChoiceModeListener(callback);

    classDB = new DataBaseClass(this);
}

// ***************** Menu Button for adding VOW
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.add, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    super.onOptionsItemSelected(item);
    switch (item.getItemId()) {
    case R.id.add_menu:
        Intent intent = new Intent(getApplicationContext(),
                AddActivity.class);
        intent.putExtra("update", false);
        startActivity(intent);
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

@Override
protected void onResume() {
    displayData();
    super.onResume();
}

private void displayData() { // displays data from SQLite
    sqlDB = classDB.getWritableDatabase();
    Cursor mCursor = sqlDB.rawQuery("SELECT * FROM "
            + DataBaseClass.TABLE_NAME, null);

    Id.clear();
    number.clear();
    if (mCursor.moveToFirst()) {
        do {
            Id.add(mCursor.getString(mCursor
                    .getColumnIndex(DataBaseClass.COLUMN_ID)));
            number.add(mCursor.getString(mCursor
                    .getColumnIndex(DataBaseClass.COLUMN_NUMBER)));

        } while (mCursor.moveToNext());
    }
    MyAdapter adapter = new MyAdapter(this, Id, number);
    listView.setAdapter(adapter);
    mCursor.close();
}

DataBaseClass.java:

public class DataBaseClass extends SQLiteOpenHelper {
static String DATABASE_NAME = "user's information";
public static final String TABLE_NAME = "vowing";
public static final String COLUMN_ID = "id";
public static final String COLUMN_NUMBER = "number";

public DataBaseClass(Context context) {
    super(context, DATABASE_NAME, null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+" ("+COLUMN_ID+" INTEGER PRIMARY KEY, "+COLUMN_NUMBER+" TEXT)";
    db.execSQL(CREATE_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
    onCreate(db);

}

MyAdapter.java class:

public class MyAdapter extends BaseAdapter {
private Context context;
private ArrayList<String> MId;
private ArrayList<String> Mnumber;

public ArrayList<Integer> selectedViewsPositions = new ArrayList<Integer>();
public Cursor dbCursor;

public MyAdapter(Context c , ArrayList<String> id, ArrayList<String> number){
    context=c;
    MId=id;
    Mnumber=number;
}

@Override
public int getCount() {
    return MId.size();
}

@Override
public Object getItem(int i) {
    return null;
}

@Override
public long getItemId(int i) {
    return 0;
}

@Override
public View getView(int i, View view, ViewGroup viewGroup) {
    Holder mHolder;
    LayoutInflater layoutInflater;
    if (view == null) {
        layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = layoutInflater.inflate(R.layout.list_item, null);
        mHolder = new Holder();
        mHolder.txt_id = (TextView) view.findViewById(R.id.id);
        mHolder.txt_Number = (TextView) view.findViewById(R.id.number);
        view.setTag(mHolder);
    } else {
        mHolder = (Holder) view.getTag();
    }
    mHolder.txt_id.setText(MId.get(i));
    mHolder.txt_Number.setText(Mnumber.get(i));

    return view;
}

public class Holder {
    TextView txt_id;
    TextView txt_Number;
}

public String getPropertiesByPosition(int position, String type) {

    dbCursor.moveToPosition(position);

    if (type.equals("id")) {
        return dbCursor.getString(dbCursor.getColumnIndex(DataBaseClass.COLUMN_ID));
    }

    else if (type.equals("numbert")) {
        return dbCursor.getString(dbCursor.getColumnIndex(DataBaseClass.COLUMN_NUMBER));
    }

    else { return null; }
}

AddActivity.java class:

public class AddActivity extends Activity {
private EditText addNUM;
private DatePicker addDATE;

private Button insertBTN;
private Button deleteBTN;

private DataBaseClass classDB;
private SQLiteDatabase sqlDB;

private String id;
private String number;
private boolean isUpdate;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.add_activity);

    classDB = new DataBaseClass(this);

    addNUM = (EditText) findViewById(R.id.addNum);

    insertBTN = (Button) findViewById(R.id.insert);
    deleteBTN = (Button) findViewById(R.id.deleteBTN);

    insertBTN.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            number=addNUM.getText().toString().trim();

            if(number.length()>0 && number.length()>0){
                saveData();
            }else {
                AlertDialog.Builder alertBuilder=new AlertDialog.Builder(AddActivity.this);
                alertBuilder.setTitle("Invalid Data");
                alertBuilder.setMessage("Please, Enter valid data");
                alertBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
                alertBuilder.create().show();
            }
        }
    });

    isUpdate=getIntent().getExtras().getBoolean("update");
    if(isUpdate){
        id=getIntent().getExtras().getString("ID");
        number=getIntent().getExtras().getString("Number");
        addNUM.setText(number);
    }

}

private void saveData(){  //save data into SQLite
    classDB = new DataBaseClass(this);
    sqlDB=classDB.getWritableDatabase();
    ContentValues values=new ContentValues();

    values.put(DataBaseClass.COLUMN_NUMBER,number);

    System.out.println("");
    if(isUpdate)
    {
        //update database with new data
        sqlDB.update(DataBaseClass.TABLE_NAME, values, DataBaseClass.COLUMN_ID+"="+id, null);
    }else {
        //insert data into database
        sqlDB.insert(DataBaseClass.TABLE_NAME, null, values);
    }
    //close database
    sqlDB.close();
    finish();
}

i have 3 questions: 1-how to edit the whole row with EDIT button of ActionMode button? 2- how to delete he whole row with DELETE button of ActionMode button? 3- how to change the color of listView's row that clicked on DONE button of ActionMode button?

This is LogCat:

06-04 09:36:28.847    1884-1884/? V/AudioPolicyManagerBase﹕ setOutputDevice() output 2 device 0002 force 0 delayMs 0
06-04 09:36:28.847    1884-2151/? D/AudioHardwareTinyALSA﹕ OutALSA::setDevice: mode = 0, newDevice=0x2, currentDevice=0x2 ,force= 0
06-04 09:36:29.077    1884-1884/? V/AudioPolicyManagerBase﹕ setOutputDevice() output 2 device 0000 force 0 delayMs 184
06-04 09:36:39.592    1884-2154/? V/AudioPolicyManagerBase﹕ setOutputDevice() output 2 device 0002 force 0 delayMs 0
06-04 09:36:39.607    1884-2151/? D/AudioHardwareTinyALSA﹕ OutALSA::setDevice: mode = 0, newDevice=0x2, currentDevice=0x2 ,force= 0
06-04 09:36:40.192   1884-25939/? V/AudioPolicyManagerBase﹕ setOutputDevice() output 2 device 0000 force 0 delayMs 184
06-04 09:38:36.412    1884-1884/? V/AudioPolicyManagerBase﹕ setOutputDevice() output 2 device 0002 force 0 delayMs 0
06-04 09:38:36.417    1884-2151/? D/AudioHardwareTinyALSA﹕ OutALSA::setDevice: mode = 0, newDevice=0x2, currentDevice=0x2 ,force= 0
06-04 09:38:36.647    1884-1884/? V/AudioPolicyManagerBase﹕ setOutputDevice() output 2 device 0000 force 0 delayMs 184
06-04 09:38:38.317    1884-2181/? V/AudioPolicyManagerBase﹕ setOutputDevice() output 2 device 0002 force 0 delayMs 0
06-04 09:38:38.572    1884-2181/? V/AudioPolicyManagerBase﹕ setOutputDevice() output 2 device 0000 force 0 delayMs 184
06-04 09:38:52.677    1884-2181/? V/AudioPolicyManagerBase﹕ setOutputDevice() output 2 device 0002 force 0 delayMs 0
06-04 09:38:52.687    1884-2151/? D/AudioHardwareTinyALSA﹕ OutALSA::setDevice: mode = 0, newDevice=0x2, currentDevice=0x2 ,force= 0
06-04 09:38:52.917    1884-1884/? V/AudioPolicyManagerBase﹕ setOutputDevice() output 2 device 0000 force 0 delayMs 184
06-04 09:38:54.287    1884-2154/? V/AudioPolicyManagerBase﹕ setOutputDevice() output 2 device 0002 force 0 delayMs 0
06-04 09:38:54.542    1884-2154/? V/AudioPolicyManagerBase﹕ setOutputDevice() output 2 device 0000 force 0 delayMs 184
06-04 09:38:54.767    1884-1884/? V/AudioPolicyManagerBase﹕ setOutputDevice() output 2 device 0002 force 0 delayMs 0
06-04 09:38:55.032    1884-1884/? V/AudioPolicyManagerBase﹕ setOutputDevice() output 2 device 0000 force 0 delayMs 184
06-04 09:38:56.827   1884-28672/? V/AudioPolicyManagerBase﹕ setOutputDevice() output 2 device 0002 force 0 delayMs 0
06-04 09:38:59.892    1884-1884/? V/AudioPolicyManagerBase﹕ setOutputDevice() output 2 device 0002 force 0 delayMs 0
06-04 09:39:00.052    1884-2176/? V/AudioPolicyManagerBase﹕ setOutputDevice() output 2 device 0002 force 0 delayMs 184
06-04 09:39:00.162    1884-2176/? V/AudioPolicyManagerBase﹕ setOutputDevice() output 2 device 0000 force 0 delayMs 184
06-04 09:39:01.672    1884-1884/? V/AudioPolicyManagerBase﹕ setOutputDevice() output 2 device 0002 force 0 delayMs 0
06-04 09:39:01.927    1884-1884/? V/AudioPolicyManagerBase﹕ setOutputDevice() output 2 device 0000 force 0 delayMs 184
06-04 09:39:13.257    1884-2176/? V/AudioPolicyManagerBase﹕ setOutputDevice() output 2 device 0002 force 0 delayMs 0
06-04 09:39:13.267    1884-2151/? D/AudioHardwareTinyALSA﹕ OutALSA::setDevice: mode = 0, newDevice=0x2, currentDevice=0x2 ,force= 0
06-04 09:39:13.497    1884-2176/? V/AudioPolicyManagerBase﹕ setOutputDevice() output 2 device 0000 force 0 delayMs 184
06-04 09:39:14.782    1884-2154/? V/AudioPolicyManagerBase﹕ setOutputDevice() output 2 device 0002 force 0 delayMs 0
06-04 09:39:15.052    1884-2154/? V/AudioPolicyManagerBase﹕ setOutputDevice() output 2 device 0000 force 0 delayMs 184
06-04 09:45:21.852    1884-2176/? V/AudioPolicyManagerBase﹕ setOutputDevice() output 2 device 0002 force 0 delayMs 0
06-04 09:45:21.867    1884-2151/? D/AudioHardwareTinyALSA﹕ OutALSA::setDevice: mode = 0, newDevice=0x2, currentDevice=0x2 ,force= 0
06-04 09:45:23.502   1884-18891/? V/AudioPolicyManagerBase﹕ setOutputDevice() output 2 device 0000 force 0 delayMs 184
06-04 09:47:09.712    2233-2347/? I/ActivityManager﹕ Killing proc 18535:com.example.draft_vow/u0a211: force stop

解决方案

NEW EDIT sorry for the delay XD

data base AgendaSqlite.java

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class AgendaSqlite extends SQLiteOpenHelper {

    //Sentencia SQL para crear la tabla de Usuarios
    String sqlCreate = "CREATE TABLE vowing (_id INTEGER PRIMARY KEY, number INTEGER)";

    public AgendaSqlite(Context context, String name, CursorFactory factory,int version) {
        super(context, name, factory, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(sqlCreate);
    }

    @Override
    public void onOpen(SQLiteDatabase db) {
        super.onOpen(db);
        if (!db.isReadOnly()) {
            // Enable foreign key constraints
            db.execSQL("PRAGMA foreign_keys=ON;");
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        //eliminamos la version anterior de la tabla
        db.execSQL("DROP TABLE IF EXISTS vowing");

        //aqui creamos la nueva version de la tabla
        db.execSQL(sqlCreate);
    }
}

to edit/delete, here, you need a editText or something to get the number you are going to delete/edit

public class MyActivity extends Activity {
private ListView listView;
private DataBaseClass classDB;
private SQLiteDatabase sqlDB;
private ArrayList<String> Id = new ArrayList<String>(); // vows id
private ArrayList<String> number = new ArrayList<String>(); // vows text


String C1="", C2="", C3="", C4="", C5="", C6="";
String Fin="";
SQLiteDatabase db;
Cursor cursor;
final String TABLA_PRINCIPAL = "vowing"; //table
final String NOMBRE_BASE_DATOS = "userInformation.db"; //data base
AgendaSqlite usdbh;
Int number=0, numberCorrect=0;
Int id=0, idCorrect=0;


ListView.MultiChoiceModeListener callback;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);


    String ArchivoDB = Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+NOMBRE_BASE_DATOS;
    usdbh = new AgendaSqlite(this, ArchivoDB, null, 1);//
    db = usdbh.getWritableDatabase();

    callback = new ListView.MultiChoiceModeListener() {
        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            mode.setTitle("Demo");
            getMenuInflater().inflate(R.menu.action_mode_menu, menu);
            return true;
        }

        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            return true;
        }

        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            switch (item.getItemId()) {
            case R.id.editBTN:
                editBTN();//edit method
                mode.finish(); 
                break;
            case R.id.deleteBTN:
                deleteBTN(); //!?delete method
                mode.finish();                     
                break;
            case R.id.doneBTN:
                //!?change background color of list view
                break;
            }
            return true;
        }

        @Override
        public void onDestroyActionMode(ActionMode mode) {

        }

        @Override
        public void onItemCheckedStateChanged(ActionMode mode,
                int position, long id, boolean checked) {
        }
    };

    listView = (ListView) findViewById(R.id.ListView);
    listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
    listView.setMultiChoiceModeListener(callback);

    classDB = new DataBaseClass(this);
}

// ***************** Menu Button for adding VOW
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.add, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    super.onOptionsItemSelected(item);
    switch (item.getItemId()) {
    case R.id.add_menu:
        Intent intent = new Intent(getApplicationContext(),
                AddActivity.class);
        intent.putExtra("update", false);
        startActivity(intent);
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

@Override
protected void onResume() {
    displayData();
    super.onResume();
}
/*
private void displayData() { // displays data from SQLite
    sqlDB = classDB.getWritableDatabase();
    Cursor mCursor = sqlDB.rawQuery("SELECT * FROM "
            + DataBaseClass.TABLE_NAME, null);

    Id.clear();
    number.clear();
    if (mCursor.moveToFirst()) {
        do {
            Id.add(mCursor.getString(mCursor
                    .getColumnIndex(DataBaseClass.COLUMN_ID)));
            number.add(mCursor.getString(mCursor
                    .getColumnIndex(DataBaseClass.COLUMN_NUMBER)));

        } while (mCursor.moveToNext());
    }
    MyAdapter adapter = new MyAdapter(this, Id, number);
    listView.setAdapter(adapter);
    mCursor.close();
}*/
editBTN(){
            //get the number to delete from a edit text or something
            Update();
            String[] args = new String[]{C1};
            db.execSQL("UPDATE " + TABLA_PRINCIPAL + " SET number='" + number + "' WHERE _id=?", args);
            Toast.makeText(getApplicationContext(), "Updating!", Toast.LENGTH_LONG).show();

}

    void Update() /////// contarenacion de los datos
    {
        C1=""; C2=""; C3=""; C4=""; C5=""; C6="";
        Fin="";
        cursor = db.rawQuery("select * from "+TABLA_PRINCIPAL, null);

        if (cursor.getCount() != 0) {
            if (cursor.moveToFirst()) {
                do {
                    C1 = cursor.getString(cursor
                            .getColumnIndex("_id"));//get _id
                    if(id==C1){
                        idCorrect=C1;
                    }

                    C2 = cursor.getString(cursor
                            .getColumnInteger("number"));//get number
                    if(number==C2){
                        numberCorrect=C2;
                    }
                } while (cursor.moveToNext());
            }
        }
        cursor.close();
    }

    deleteBTN(){
        //get the numberto a delete from a edit text or something
        Update();
        String[] args = new String[]{C2};
        db.execSQL("DELETE FROM "+ TABLA_PRINCIPAL+" WHERE number=?", args);
        Toast.makeText(getApplicationContext(), "delete!", Toast.LENGTH_LONG).show();
    }
}


if you are trying to delete use the database.exeSQL to do it, here you go:

delete.setOnClickListener(new Button.OnClickListener(){
        public void onClick(View v){
            name = paciente.getText().toString();//get the nameof what you are trying to delete
            if (name.matches("")) { //check if it's empty
                Toast.makeText(getBaseContext(), "Whatever you want/ALERT", Toast.LENGTH_LONG).show();
            }else{
                String[] args = new String[]{name};
                db.execSQL("DELETE FROM "+ YOUR_TABLE+" WHERE ColumnName=?", args);
                Toast.makeText(getApplicationContext(), "Whatever you want", Toast.LENGTH_LONG).show();
                espacioHistorial.setText("");
            }
        }
    });

to update is similar in a button:

String[] args = new String[]{nombre};//name or id whatever you want
                    db.execSQL("UPDATE " + TABLA_PRINCIPAL + " SET sintomas='" + sintomas + "', diagnostico='"+diagnostico1+"' WHERE nombre_paciente=?", args); //using SET you say that the column will be update with a new string
                    Toast.makeText(getApplicationContext(), "ALERT", Toast.LENGTH_LONG).show();

hope this help, see ya

这篇关于编辑/删除Android的SQLite的数据基行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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