问题
below is my code i want to add delete listview message when user click on long press selected message will delete from listview and also database help me how to do that im usign tread in my code so how to delete selected mesage form listview and database any idea?
public class MsgActivity extends BackBaseActivity{
ImageView back;
Button writemsg;
ListView msglist;
List<MessageModel> msgarray;
MessageAdapter msgadapter;
ImageView scroll_down;
ImageView scroll_up;
int x = 1;
public static Activity msgactivity;;
Handler handle = new Handler() {
public void handleMessage(android.os.Message msg) {
super.handleMessage(msg);
CommonObjects.hideProgress();
msgadapter = new MessageAdapter(MsgActivity.this,
msgarray);
msglist.setAdapter(msgadapter);
}catch (Exception e) {
// TODO: handle exception
}
}
if(msg.what == 1){
Toast.makeText(MsgActivity.this, "No Messages",
Toast.LENGTH_SHORT).show();
}
}
};
@Override
protected void onRestart() {
if(CommonObjects.getLogoutreject().equals("1") && CommonObjects.logout){
finish();
}
super.onRestart();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.msgactivity);
back = (ImageView)findViewById(R.id.magback);
msglist = (ListView)findViewById(R.id.msglist);
msgactivity = this;
CommonObjects.showProgress(MsgActivity.this, "Loading messages");
new Thread() {
public void run() {
Looper.prepare();
try{
DatabaseHandler db = new
DatabaseHandler(MsgActivity.this);
msgarray = db.getAllmesages();
android.os.Message alertMessage = new android.os.Message();
alertMessage.what = 2;
handle.sendMessage(alertMessage);
}catch (Exception e) {
e.getStackTrace();
android.os.Message alertMessage = new
android.os.Message();
alertMessage.what = 1;
handle.sendMessage(alertMessage);
}
}
}.start();
}
回答1:
if you want to delete any data from listview and databse just perform this opreation
in your mainactivity class
delete.setOnClickListener(new OnClickListener() {
@Override
public void onClick(final View v) {
// TODO Auto-generated method stub
DatabaseHandler dBHandler = new DatabaseHandler(
activity.getApplicationContext());
dBHandler.Delete_Contact(user_id);
Main_Screen.this.onResume();
}
});
and in your databasehandler class,use this
// Deleting single contact
public void Delete_Contact(int id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(id) });
db.close();
}
回答2:
Try like this.
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
// setting onItemLongClickListener and passing the position to the function
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
String[] delete = names2.get(i);
String idString = delete[0];
long idLong = Long.valueOf(idString);
Log.d("Deleting...", idLong + "");
dataManipulator.delete(idLong);
names2.remove(i);
}
});
Where names2 is your List array.
and in your Datamanipulator class add following
public boolean delete(long rowId) {
/** this method deletes by id, the first column in your database */
return db.delete(TABLE_NAME, KEY_ROWID + "=" + rowId, null) > 0;
}
回答3:
DataBaseManager data = new DataBaseManager(context.getApplicationContext());
String QUERY = "SELECT * FROM Cart Where id= "your id";
Cursor cursor = data.selectQuery(QUERY);
int count = cursor.getCount();
if (count <= 0) {
}
else {
data.Delete("YOUR DATABASE NAME", "YOUR ID");
list.remove(position);
notifyDataSetChanged();
}
DatabaseMangerClass
public class DataBaseManager extends SQLiteOpenHelper {
// The Android's default system path of your application database.
@SuppressLint("SdCardPath")
private static String DB_PATH = "data/data/com.Salsoft.pharmapacks/";
private static String DB_NAME = "Cart.sqlite";
private SQLiteDatabase myDataBase;
private SQLiteDatabase myData;
private Context myContext;
// /data/data/com.salsoft.savingdata/db/SavingData.sqlite
/**
* Constructor Takes and keeps a reference of the passed context in order to
* access to the application assets and resources.
*
* @param context
*/
public DataBaseManager(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
Boolean isSDPresent = android.os.Environment.getExternalStorageState()
.equals(android.os.Environment.MEDIA_MOUNTED);
if (isSDPresent) {
// yes SD-card is present
} else {
// Sorry
}
}
/**
* Creates a empty database on the system and rewrites it with your own
* database.
* */
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
// do nothing - database already exist
} else {
File directory = new File(DB_PATH);
directory.mkdirs();
CopyFiles();
}
}
private void CopyFiles() {
try {
InputStream is = myContext.getAssets().open(DB_NAME);
File outfile = new File(DB_PATH, DB_NAME);
outfile.getParentFile().mkdirs();
outfile.createNewFile();
if (is == null) {
throw new RuntimeException("stream is null");
} else {
FileOutputStream out = new FileOutputStream(outfile);
byte buf[] = new byte[128];
do {
int numread = is.read(buf);
if (numread <= 0)
break;
out.write(buf, 0, numread);
} while (true);
is.close();
out.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Check if the database already exist to avoid re-copying the file each
* time you open the application.
*
* @return true if it exists, false if it doesn't
*/
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
} catch (SQLiteException e) {
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
public void openDataBase() throws SQLException {
// Open the database
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
}
@Override
public synchronized void close() {
if (myDataBase != null)
myDataBase.close();
super.close();
}
public void insert(String table, String num, ContentValues content) {
String myPath = DB_PATH + DB_NAME;
myData = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
myData.insert(table, num, content);
}
public void update(String tablename, ContentValues content, String productid) {
String myPath = DB_PATH + DB_NAME;
myData = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
myData.update(tablename, content, "productid = ?",
new String[] { productid });
}
public void Delete(String tablename, String productid) {
String myPath = DB_PATH + DB_NAME;
myData = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
myData.delete(tablename, "productid = ?", new String[] { productid });
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
// ---retrieve records---
public Cursor selectQuery(String query) throws SQLException {
String myPath = DB_PATH + DB_NAME;
myData = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
Cursor mCursor = myData.rawQuery(query, null);
mCursor.moveToFirst();
myData.close();
return mCursor;
}
// //////// For Insert And Update Data ////////
public void insert_update(String query) throws SQLException {
String myPath = DB_PATH + DB_NAME;
myData = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
myData.execSQL(query);
myData.close();
}
}
来源:https://stackoverflow.com/questions/21932025/how-to-delete-message-from-listview-and-database