我正在使用this tutorial编写一个Android程序,该程序在ListView中显示数据库的字段。现在我想用ActionMode的按钮编辑它们(编辑/删除)。
请你帮我写编辑和删除代码吗? 这是我的项目代码:
MyActivity.java类:
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类:
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类:
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();
}
我有3个问题: 1 - 如何使用ActionMode按钮的EDIT按钮编辑整行? 2-如何使用ActionMode按钮的DELETE按钮删除整行? 3-如何更改单击ActionMode按钮的DONE按钮的listView行的颜色?
这是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
答案 0 :(得分:1)
NEW EDIT 对不起延迟XD
数据库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);
}
}
编辑/删除,在这里,您需要一个editText或其他东西来获取您要删除/编辑的编号
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();
}
}
如果您尝试删除使用database.exeSQL来执行此操作,请转到:
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("");
}
}
});
更新在按钮中类似:
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();
希望得到这个帮助,请参阅
答案 1 :(得分:0)
您不需要使用SQLiteOpenHelper 只需使用ORM SugarOrm简单易用
那就像数组一样,所以有“添加”,“删除”方法, 您也可以通过将set方法编辑为item类,并使用“save”更新表的行
Google it