Reputation: 107
I am new to Android development, I have a Listview in may app, Listview is populated with data from Sqlite database. I want to use check boxes on this listview & delete selected item. I want to clear selected data rows form Sqlite Db indeed. Any useful help will be appreciated.
First i have retrieved SMS in my app as follows:` if (bundle != null) {
//—retrieve the SMS message received—
Object messages[] = (Object[]) bundle.get("pdus");
SmsMessage smsMessage[] = new SmsMessage[messages.length];
for (int n = 0; n < messages.length; n++) {
smsMessage[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
timestamp = smsMessage[n].getTimestampMillis();
number = smsMessage[n].getOriginatingAddress();
body += smsMessage[n].getDisplayMessageBody();
abortBroadcast();
blockMessage(context);
} // end for loop
} // bundle is null
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" +e);
}
}
private void blockMessage(Context context) {
// instantiate DbMNager object to insert sms in database
//formating receiving time:
//SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-hh.mm.ss");
SimpleDateFormat formatter = new SimpleDateFormat("EEEE, MMMM d HH:mm:ss a");
String formatedTime = formatter.format(timestamp);
DBmanager= new DbManager(context);
DBmanager.open();
DBmanager.Insert_sms_data(formatedTime ,number,body);
DBmanager.close();`
Then stored in SQlite DB as follows :
public void Insert_sms_data(String formatedTime, String number, String body){
try{
SQLiteDatabase DB = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(SMS_Time, formatedTime);
cv.put(PHONE_NUMBER, number);
cv.put(MESSAGE_BODY, body);
DB.insert(TABLE_SMS, null, cv);
DB.close();
}
catch(Exception ex)
{
Log.e("ERROR in insertion", ex.toString());
}
}
public Cursor Return_All(){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cur = db.rawQuery("SELECT * FROM "+"SMS_TABLE", null);
return cur;
}
// Clear all messaged
public void ClearAll(){
SQLiteDatabase db = this .getWritableDatabase();
db.delete(TABLE_SMS, null, null);
db.close();
}
After that retrieved in my listview Activity successfully.
public class MainActivity extends Activity {
ListView listViewSMS;
Context context;
DbManager manager;
Button btn_clearall;
Cursor cursor;
SimpleCursorAdapter adapter;
//array from is the column name in your cursor where you're getting the data
String[] from = new String[]{"Phone_number","Message_body","Time"};
//array toIDs contains the id of textViews
int[] toIDs = new int[]{R.id.textViewSMSSender,R.id.textViewMessageBody,R.id.textViewMSMStime};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview_activity_main);
context=this;
//get the ListView Reference
try{
listViewSMS=(ListView)findViewById(R.id.listViewSMS);
listViewSMS.setChoiceMode(listViewSMS.CHOICE_MODE_MULTIPLE);
manager = new DbManager(context);
cursor = manager.Return_All();
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.listview_each_item, cursor, from, toIDs);
listViewSMS.setAdapter(adapter);
adapter.notifyDataSetChanged();
//refreshCursor();
listViewSMS.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> arg0, View v, int position,
long arg3) {
int itemId = Integer.valueOf(String.valueOf(position));
cursor.moveToPosition(itemId);
int messageId = cursor.getInt(0);
deleteMessage(messageId);
Toast.makeText(getApplicationContext(), "current position"+itemId, Toast.LENGTH_LONG).show();
TextView tv_SMSSenderNumber=(TextView)v.findViewById(R.id.textViewSMSSender);
TextView tv_SMSBody=(TextView)v.findViewById(R.id.textViewMessageBody);
TextView tv_SMSTime=(TextView)v.findViewById(R.id.textViewMSMStime);
String smsSender=tv_SMSSenderNumber.getText().toString();
String smsBody= tv_SMSBody.getText().toString();
String smsTime= tv_SMSTime.getText().toString();
}
});
}
catch(Exception ex){
Log.e("ERROR!!", ex.toString());
}
btn_clearall = (Button)findViewById(R.id.btn_Delall);
btn_clearall.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
clearMessages();
//refreshCursor();
// adapter.notifyDataSetChanged();
}
});
CheckBox cb_sms_lv = (CheckBox)findViewById(R.id.cb_smslist);
}
protected void clearMessages() {
new AlertDialog.Builder(MainActivity.this).setIcon(
android.R.drawable.ic_dialog_alert).setTitle(R.string.delete)
.setMessage(getString(R.string.clear_message_confirm))
.setPositiveButton(R.string.delete,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface di, int i) {
manager = new DbManager(
context);
manager.open();
manager.ClearAll();
manager.close();
refreshCursor();
}
}).setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface di, int i) {
}
}).show();
}
private void deleteMessage(final int messageId){
new AlertDialog.Builder(MainActivity.this).setIcon(
android.R.drawable.ic_dialog_alert).setTitle(R.string.delete)
.setMessage(getString(R.string.delete_message_confirm))
.setPositiveButton(R.string.delete,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface di, int i) {
manager = new DbManager(
context);
manager.open();
manager.deleteMessage(messageId);
manager.close();
refreshCursor();
}
}).setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface di, int i) {
}
}).show();
}
public void refreshCursor() {
manager = new DbManager(context);
manager.open();
cursor = manager.Return_All();
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.listview_each_item, cursor, from, toIDs);
listViewSMS.setAdapter(adapter);
manager.close();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
I can delete the whole thread successfully but now i wantt to delete few sms from listview using checkbox Any helpful tutorial please?
Upvotes: 1
Views: 2489
Reputation: 100
Try this
Code to delete item from listview
int index = Integer.parseInt(position+"");
ArrayList.remove(index);
notifyDataSetChanged();
Then use the Query to delete data from Sqite database
Upvotes: 3
Reputation: 1967
For Custom Adapter use the list item row xml as:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:id="@+id/data"
android:padding="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
/>
<CheckBox
android:id="@+id/checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/data"
android:checked="false" />
</RelativeLayout>
and in the custom adapter java class
public class CustomAdapter extends BaseAdapter{
ArrayList<String> mlistdata;
private LayoutInflater layoutinflater;
private Context mContext;
public CustomAdapter(Context context,ArrayList<String> elements)
{
mlistdata = elements;
layoutinflater=LayoutInflater.from(context);
mContext=context;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return mlistdata.size();
}
@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(final int arg0, View convertview, ViewGroup arg2) {
// TODO Auto-generated method stub
final ViewHolder holder;
if(convertview==null)
{
holder = new ViewHolder();
convertview = layoutinflater.inflate(R.layout.gallery_items, null);
holder.txt=(TextView)convertview.findViewById(R.id.data);
holder.cb=(CheckBox)convertview.findViewById(R.id.checkbox);
convertview.setTag(holder);
}
else{
holder=(ViewHolder)convertview.getTag();
}
holder.txt.setText((mlistdata.get(arg0)).toString());
holder.cb.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(holder.cb.isChecked())
{
//database related operation
}
else
{
//database related operation
}
}
});
return convertview;
}
static class ViewHolder
{
TextView txt;
CheckBox cb;
}
Upvotes: 1
Reputation: 3332
Try this solution here
in EmployeeAdapter.java you will have checked and unchecked dataList and to get that write a methode getDataList();
in this file.
Example :
public List<employeemodel> getDataList(){
return employeeData;
}
use this method in your activity using yourAdapter.getDataList();
after getting datalist perform the delete operation and set new dataList to your adapter and call yourListView.notifyDatasetChange();
.
Upvotes: 0
Reputation: 1432
if you succesfully remove data from databse as you say in your question than use notifydatasetchanged method of listview to reload listview with new data.
Upvotes: 1
Reputation: 7259
A little tip could help. Since you have the data with you, keep track of the items tick marked. Store their ids. Once the user clicks on done or whatever button you have, run an sql query that deletes the records with the ids. And then call notifyDataSetChanged
of the list view. Since its a cursor there are changes that notifyDataSetChanged
might not function well then refill the cursor once again.
Refer to Refresh ListView and also this
Upvotes: 1
Reputation: 5260
com/nhaarman/ListViewAnimations. very useful..you can see demo at https://play.google.com/store/apps/details?id=com.haarman.listviewanimations
Upvotes: 0