I know that data is inserted in the database , and it is listed correctly but the notifydatasetchanges doesn't works , the list view doesn't get refreshed, so I have to restart my activity....
Cursor c = db.selectAll();
final ListView lv = (ListView) findViewById(R.id.listView1);
adapter=new MyContactsAdapter(this, c);
lv.setAdapter(adapter);
db.insertInTable("asd","asd");
//insertion in table works, I am sure, cause when I start the activity the new values are listed
//this the part that doesn't works
((MyContactsAdapter)lll.getAdapter()).notifyDataSetChanged();
adapter.notifyDataSetChanged();
lll.refreshDrawableState();
private class MyContactsAdapter extends CursorAdapter{
private Cursor mCursor;
private Context mContext;
private final LayoutInflater mInflater;
public MyContactsAdapter(Context context, Cursor cursor) {
super(context, cursor, true);
mInflater = LayoutInflater.from(context);
mContext = context;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView t = (TextView) view.findViewById(R.id.textView2);
t.setText(cursor.getString( 0 ));
t = (TextView) view.findViewById(R.id.TextView01);
t.setText(cursor.getString(1));
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
final View view = mInflater.inflate(R.layout.item, parent, false);
return view;
}
}//adapter
Ok, something like, From your code,
Cursor c;
#Override
onCreate(.... {
setContentView(...);
final ListView lv = (ListView) findViewById(R.id.listView1);
db.insertInTable("asd","asd");
c = db.selectAll();
adapter=new MyContactsAdapter(this, c);
lv.setAdapter(adapter);
// some button click...
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
db.insertInTable("xyz","xyz");
c = db.selectAll();
adapter.notifyDataSetChanged();
}
});
Try this, Let see what happen...
Related
I wanna delete items in my listview by clicking a button in my list view item. This works but i dont know how to refresh the listview after i clicked the button. can anyone help me?
here is some of my code
public class ActionsListView extends AppCompatActivity {
private Button deleteBtn, editBtn, addBtn;
private ListView listView;
DBAdapter myDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_actions_list_view);
deleteBtn = (Button) findViewById(R.id.deleteBtn);
editBtn = (Button) findViewById(R.id.editBtn);
addBtn = (Button) findViewById(R.id.alv_AddBtn);
openDB();
populateListView();
}
private void openDB(){
myDb = new DBAdapter(this);
myDb.open();
}
private void populateListView(){
Cursor cursor = myDb.getAllRows();
String [] fromFieldNames = new String[] {DBAdapter.KEY_ACTION_NAME, DBAdapter.KEY_ACTION_DURATION};
int [] toViewIDs = new int[]{R.id.itemActionDisplay, R.id.itemDurationDisplay};
MySimpleCursorAdapter myCursorAdapter;
myCursorAdapter = new MySimpleCursorAdapter(getBaseContext(), R.layout.item_action, cursor, fromFieldNames, toViewIDs, 0);
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(myCursorAdapter);
}
My custom simplecursoradapter
public MySimpleCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags) {
super(context, layout, c, from, to, flags);
}
#Override
public View newView(Context _context, Cursor _cursor, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) _context.getSystemService(_context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.item_action, parent, false);
return view;
}
#Override
public void bindView(View view, final Context context, Cursor cursor) {
String actionName = cursor.getString(cursor.getColumnIndex(DBAdapter.KEY_ACTION_NAME));
String actionDuration = cursor.getString(cursor.getColumnIndex(DBAdapter.KEY_ACTION_DURATION));
TextView actionNameTxtField = (TextView) view.findViewById(R.id.itemActionDisplay);
TextView actionDurationTxtField = (TextView) view.findViewById(R.id.itemDurationDisplay);
actionNameTxtField.setText(actionName);
actionDurationTxtField.setText(actionDuration);
Button yourButton = (Button) view.findViewById(R.id.deleteBtn);
yourButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (view != null) {
DBAdapter myDb = new DBAdapter(context);
myDb.open();
myDb.deleteAll();
notifyDataSetChanged();
}
}
});
}
Here is the code I am using to show a custom ListView using simple CursorAdapter
I am using this code to show cart items, and I want to add button in ListView
As I am new to android development I'm not able to figure out what the problem is
myDbHelper.openDataBase();
final Cursor ictemp = myDbHelper.getOrdredItems(myDbHelper);
if (ictemp != null) {
ictemp.moveToFirst();
count = ictemp.getCount();
Log.d("count", "count===" + count);
String[] from = new String[] { "item_name", "item_rate", "qty",
"unit" };
int[] to = new int[] { R.id.tv_Name, R.id.tv_Rate, R.id.et_qty,
R.id.tv_unit };
final SimpleCursorAdapter sc = new SimpleCursorAdapter(this,
R.layout.list_row2, ictemp, from, to, 0);
final Cursor crs = myDbHelper.getTotal(myDbHelper);
if (crs != null) {
crs.moveToFirst();
String total = crs.getString(0);
Gtotal.setText("Rs." + total);
tvcount.setText("" + count);
}
lv.setAdapter(sc);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view,
final int pos, long arg3) {
remove = (Button) arg0.findViewById(R.id.btn_remove);
switch (arg0.getId()) {
case R.id.btn_remove:
Toast.makeText(ctx, "Clicked on " + pos,
Toast.LENGTH_SHORT).show();
break;}
}
});
One solution is to create a CustomAdapter that extends SimpleCursorAdapter.
Then override bindView method
In bindView, find the Button then handle onClickEvent
public class CustomAdapter extends SimpleCursorAdapter {
private Context mContext;
private Context appContext;
private int layout;
private Cursor cr;
private final LayoutInflater inflater;
public CustomAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
super(context, layout, c, from, to);
this.layout = layout;
this.mContext = context;
this.inflater = LayoutInflater.from(context);
this.cr = c;
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return inflater.inflate(layout, null);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
super.bindView(view, context, cursor);
...
TextView tv_Name = (TextView) view.findViewById(R.id.tv_Name);
tv_Name.setText(...);
...
Button btnRemove = (Button) view.findViewById(R.id.btn_remove);
btnRemove.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// button click
// Remove your item here
}
});
}
}
Use it in Activity by
final CustomAdapter sc = new CustomAdapter(this,R.layout.list_row2,ictemp, from, to, 0);
lv.setAdapter(sc)
Hope this helps
I checked a lot of stack overflow question, and none of them helped.
How to refresh my listView after deleting item with onLongClickListener?
As you'll see nor adapter.notifyDataSetChanged(), nor listView.invalidateViews() don't work.
This is implementation with just necessary methods to figure out idea.
public class MainActivity extends AppCompatActivity {
public FloatingActionButton fabAddWord;
public Toolbar toolbar;
public ListView listView;
private RjecnikCursorAdapter adapter;
private RjecnikDB dbRjecnik;
private SQLiteDatabase db;
private Cursor cursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
fabAddWord = (FloatingActionButton) findViewById(R.id.fabAddWord);
listView = (ListView) findViewById(R.id.listView);
dbRjecnik = new RjecnikDB(this);
db = dbRjecnik.getWritableDatabase();
String query = "SELECT * FROM " + RjecnikDB.TABLE;
cursor = db.rawQuery(query, null);
adapter = new RjecnikCursorAdapter(this, cursor);
listView.setAdapter(adapter);
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
deleteOnLongClick(cursor.getString(cursor.getColumnIndex(RjecnikDB.COLUMN_RIJEC)));
adapter.notifyDataSetChanged();
listView.invalidateViews();
return true;
}
});
}
public void deleteOnLongClick(String rijec) {
SQLiteDatabase db = dbRjecnik.getWritableDatabase();
db.delete(RjecnikDB.TABLE, RjecnikDB.COLUMN_RIJEC + " = ?", new String[] {rijec} );
this.adapter.notifyDataSetChanged();
this.listView.invalidateViews();
db.close();
}
CustomAdapter
public class RjecnikCursorAdapter extends CursorAdapter {
public RjecnikCursorAdapter (Context context, Cursor cursor) {
super(context, cursor, 0);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.item_word, parent, false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView tvSingleLineWord = (TextView) view.findViewById(R.id.tvSingleLineWord);
// Extract properties from cursor
String rijec = cursor.getString(cursor.getColumnIndex(RjecnikDB.COLUMN_RIJEC));
// Populate fields with extracted properties
tvSingleLineWord.setText(rijec);
}
}
The Adapter have a data cache, so data in ListView will not change when data in database changed. You should change the cursor.
#Override
public void changeCursor(Cursor cursor) {
mIndexer.setCursor(cursor);
super.changeCursor(cursor);
}
put code below to your OnItemLongClickListener
cursor = db.rawQuery(query, null);
adapter.changeCurosr(cursor);
You have to use just notifyDataSetChanged() to refresh your listView data, invalidateViews() will only redraw the visible items yet nothing on them has changed (changing font for example).
Note that is recommanded to run your notifyDataSetChanged() on UI thread.
EDIT 2 : you can use BaseAdapter instead of CursorAdapter like below
public class RjecnikCursorAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<String> rjecnikList;
public RjecnikCursorAdapter(Activity activity, List<String> rjecnikList) {
this.activity = activity;
this.rjecnikList = rjecnikList;
}
#Override
public int getCount() {
return rjecnikList.size();
}
#Override
public Object getItem(int location) {
return rjecnikList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.item_word, null);
TextView tvSingleLineWord = (TextView) view.findViewById(R.id.tvSingleLineWord);
tvSingleLineWord.setText(String.valueOf(rjecnikList.get(position)));
return convertView;
}
}
And in your activity :
public class MainActivity extends AppCompatActivity {
public FloatingActionButton fabAddWord;
public Toolbar toolbar;
public ListView listView;
public List<String> mylist;
private RjecnikCursorAdapter adapter;
private RjecnikDB dbRjecnik;
private SQLiteDatabase db;
private Cursor cursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
fabAddWord = (FloatingActionButton) findViewById(R.id.fabAddWord);
listView = (ListView) findViewById(R.id.listView);
dbRjecnik = new RjecnikDB(this);
db = dbRjecnik.getWritableDatabase();
String query = "SELECT * FROM " + RjecnikDB.TABLE;
cursor = db.rawQuery(query, null);
mylist = new ArrayList<>();
if (cursor.moveToFirst()){
do{
//change this with your column data
String data = cursor.getString(cursor.getColumnIndex("data");
mylist.add(data);
}while(cursor.moveToNext());
}
cursor.close();
adapter = new RjecnikCursorAdapter(this, mylist);
listView.setAdapter(adapter);
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
deleteOnLongClick(cursor.getString(cursor.getColumnIndex(RjecnikDB.COLUMN_RIJEC)));
mylist.remove(position);
adapter.notifyDataSetChanged();
listView.invalidateViews();
return true;
}
});
}
public void deleteOnLongClick(String rijec) {
SQLiteDatabase db = dbRjecnik.getWritableDatabase();
db.delete(RjecnikDB.TABLE, RjecnikDB.COLUMN_RIJEC + " = ?", new String[] {rijec} );
this.adapter.notifyDataSetChanged();
this.listView.invalidateViews();
db.close();
}
I am trying to get the selected checkboxes deleted. I have no clue what to do after this code below:
I am using a simple cursor adapter. I also want to know how I could select and deselect all the checkboxes. I had researched everything but can't find any answer. I've been stuck for 3 days. ALso, Im not sure if the code below is even the correct path i need.
public class SecondCheckedListView extends ListActivity {
private Cursor mCursor;
private Long mRowId;
DBAdapter db = new DBAdapter(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondcheckedlistview);
db.open();
fillData();
}
private void fillData() {
mCursor = db.getAllContacts();
startManagingCursor(mCursor);
String[] from = new String[]{DBAdapter.KEY_FIRSTNAME, DBAdapter.KEY_LASTNAME};
int[] to = new int[]{R.id.textView1, R.id.textView2};
SimpleCursorAdapter d =
new SimpleCursorAdapter(this, R.layout.rowcheckedlistview, mCursor, from, to);
setListAdapter(d);
}
public class MyAdapter extends SimpleCursorAdapter {
private final Context mContext;
private final int mLayout;
private final Cursor mCursor;
private final int mNameIndex;
private final int mIdIndex;
private final LayoutInflater mLayoutInflater;
private final class ViewHolder {
public TextView firstname;
public TextView lastname;
public CheckBox cBox;
}
public MyAdapter(Context context, int layout, Cursor c,
String[] from, int[] to) {
super(context, layout, c, from, to);
this.mContext = context;
this.mLayout = layout;
this.mCursor = c;
this.mNameIndex = mCursor.getColumnIndex(DBAdapter.KEY_FIRSTNAME);
this.mIdIndex = mCursor.getColumnIndex(DBAdapter.ROW_ID);
this.mLayoutInflater = LayoutInflater.from(mContext);
}
#Override
public View getView(final int pos, View convertView, ViewGroup parent) {
if (mCursor.moveToPosition(pos)) {
ViewHolder viewHolder;
if(convertView == null) {
convertView = mLayoutInflater.inflate(mLayout, null);
viewHolder = new ViewHolder();
viewHolder.firstname = (TextView) convertView.findViewById(R.id.textView1);
viewHolder.lastname = (TextView) convertView.findViewById(R.id.textView2);
viewHolder.cBox = (CheckBox) convertView.findViewById(R.id.bcheck);
convertView.setTag(viewHolder);
}else{
viewHolder = (ViewHolder) convertView.getTag();
}
String firstname = mCursor.getString(mNameIndex);
String rowId = mCursor.getString(mIdIndex);
}
return convertView;
}
}
}
what do you mean "delete"? You want to remove the checkbox from the listview? You might need
to do something like
viewHolder.RemoveView(cBox);
If you want to select/delsect all checkboxes, you'll probably want that based upon some other botton or checkbox. I do that with another checkbox like so:
private OnClickListener setSelectAllListener = new OnClickListener() {
#Override
public void onClick(View v) {
selectAllTouched = true;
if (!selectAllCheck.isChecked()) {
selectAll = false;
studs.notifyDataSetChanged();
}
else {
selectAll = true;
studs.notifyDataSetChanged();
}
}
};
And then in my custom adapter that does stuff with each checkbox in a listview, I use this:
if (selectAllTouched) {
if(selectAll){
holder.here.setChecked(true);
itemCheckedHere.set(pos, true);
int who= new Integer(holder.text2.getText().toString());
mDbHelper.updateAttend(who, classnum, ATTEND, 1, attendDate );
}
else{
holder.here.setChecked(false);
itemCheckedHere.set(pos, false);
int who = new Integer(holder.text2.getText().toString());
mDbHelper.updateAttend(who, classnum, ATTEND, 0, attendDate );
}
}
I used a sparse array, itemCheckedHere, to hold the values of all the check boxes so scrolling doesn't change the values on resued views.
I have the following code returning a list from a database. I want to use a checkbox list so people can do a search on beaches with certain facilities, but I can’t get it to show the check boxes, it just displays a normal list!
public class FacilitySearch extends ListActivity {
private DatabaseHelper dbBookHelper = null;
private Cursor ourCursor = null;
private BookAdapter adapter = null;
public final static String ID_EXTRA="com.fnesse.beachguide._ID";
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
ListView myListView = getListView();
myListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
myListView.setOnItemClickListener(onListClick);
dbBookHelper = new DatabaseHelper(this);
dbBookHelper.createDatabase();
ourCursor = dbBookHelper.getFacilities();
startManagingCursor(ourCursor);
adapter=new BookAdapter(ourCursor);
myListView.setAdapter(adapter);
myListView.setItemsCanFocus(false);
}
private AdapterView.OnItemClickListener onListClick = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Intent i = new Intent(FacilitySearch.this, Administration.class);
i.putExtra(ID_EXTRA, String.valueOf(id));
startActivity(i);
}
};
class BookAdapter extends CursorAdapter {
BookAdapter(Cursor c) {
super(FacilitySearch.this, c);
}
#Override
public void bindView(View row, Context ctxt, Cursor c) {
BookHolder holder = (BookHolder)row.getTag();
holder.populateFrom(c, dbBookHelper);
}
#Override
public View newView(Context ctxt, Cursor c, ViewGroup parent) {
LayoutInflater inflater=getLayoutInflater();
View row=inflater.inflate(R.layout.row2, parent, false);
BookHolder holder=new BookHolder(row);
row.setTag(holder);
return(row);
}
}
static class BookHolder {
private TextView name = null;
BookHolder(View row) {
name=(TextView)row.findViewById(R.id.beachListText);
}
void populateFrom(Cursor c, DatabaseHelper r) {
name.setText(r.getName(c));
}
}
Any ideas?
Cheers,
Mike.
I think you need to include in your list item a CheckedTextView with
android:id="#android:id/text1"
as shown in the android.R.layout.simple_list_item_multiple_choice resource.
It's the same when you extend ListActivity and you define your own main layout you need to have a ListView with id
android:id="#id/android:list"