I have application working with SQLite DB(table with two rows) I need to recieve _ID row of the selected listview Item, but don't know how to do it. So, main activity
public class Main extends ListActivity {
private RecipesData recipes;
private static int[] TO={0,R.id.row_text_id};
private static String[] FROM={ _ID, CATEGORY_NAME, };
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
recipes=new RecipesData(this);
try{
Cursor cursor=getCategories();
showCategories(cursor);
}finally{
recipes.close();
}
final ListView lv=getListView();
lv.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> a, View v, int position, long id){
AlertDialog.Builder adb=new AlertDialog.Builder(Main.this);
adb.setTitle("LVSelectedItemExample");
adb.setMessage("Selected Item is = "+((TextView)v).getText());
adb.setPositiveButton("Ok", null);
adb.show();
}
});
}
#Override
protected void onPause(){
recipes.close();
super.onPause();
}
#Override
protected void onStop(){
recipes.close();
super.onStop();
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
super.onCreateOptionsMenu(menu);
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case R.id.add_category_item:
return true;
}
return false;
}
private void showCategories(Cursor cursor){
SimpleCursorAdapter adapter=new SimpleCursorAdapter(this,R.layout.item,cursor,FROM,TO);
setListAdapter(adapter);
}
private Cursor getCategories(){
SQLiteDatabase db=recipes.getReadableDatabase();
Cursor cursor=db.query(CATEGORY_TABLE, FROM, null, null, null, null, null);
startManagingCursor(cursor);
return cursor;
}}
in your onItemClick
Cursor cursor = ((CursorAdapter) a.getAdapter()).getCursor();
String currentId = cursor.getString(0);
Related
Im doing a basic android app to learn about sqlite. The app just have a listfragment that list some products and the price like:
Pencil 1
Pen 1.20
...
And its possible to click in a item of the list to delete it. Im using cursorloader so the db operations are done in background. But Im getting a issue:
When the user clicks in a item the item is not removed from the list, but if I close and open again the app all items of the list have been removed.
Do you know where is the issue? Why the fragmentlist is not updated by removing the clicked item after click in the item and why all items are being removed?
// to list the products and the respective price
public class ProductsFragment extends ListFragment implements OnClickListener, LoaderManager.LoaderCallbacks<Cursor> {
private static final String[] PROJECTION=new String[] {
Provider.Products._ID, Provider.Products.TITLE,
Provider.Products.PRICE };
private CursorAdapter cursorAdapter;
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Cursor cursor = getActivity().getContentResolver().query(Provider.Products.CONTENT_URI, DBHelper.ALL_COLUMNS,
null,null,null,null);
String[] from = {DBHelper.TITLE, DBHelper.PRICE};
int[] to = {R.id.title, R.id.price};
cursorAdapter = new SimpleCursorAdapter(getActivity(), R.layout.item, null, from, to, 0);
setListAdapter(cursorAdapter);
getLoaderManager().initLoader(0, null, this);
}
// to delete a product
#Override
public void onListItemClick(ListView l, View v, int pos, long id) {
super.onListItemClick(l, v, pos, id);
getActivity().getContentResolver().delete(Provider.Products.CONTENT_URI,String.valueOf(id), null);
Toast.makeText(getActivity(), "Item " + id + " clicked", Toast.LENGTH_SHORT).show();
}
// cursorloader methods
#Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
return new CursorLoader(getActivity().getApplicationContext(), Provider.Products.CONTENT_URI, null, null, null, null);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
cursorAdapter.swapCursor(cursor);
}
public void onLoaderReset(Loader<Cursor> loader) {
cursorAdapter.swapCursor(null);
}
// Provider class delete method:
#Override
public int delete(Uri url, String where, String[] whereArgs) {
return database.delete(DBHelper.TABLE_PRODUCTS, where, whereArgs);
}
same issue with:
#Override
public int delete(Uri url, String where, String[] whereArgs) {
int count=db.getWritableDatabase().delete(TABLE, where, whereArgs);
getContext().getContentResolver().notifyChange(url, null);
return(count);
}
item.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
/>
<TextView
android:id="#+id/price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
/>
</RelativeLayout>
Full ProductsFragment:
public class ConstantsFragment extends ListFragment implements OnClickListener, LoaderManager.LoaderCallbacks<Cursor> {
private CursorAdapter cursorAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Cursor cursor = getActivity().getContentResolver().query(Provider.Constants.CONTENT_URI, DatabaseHelper.ALL_COLUMNS,
null,null,null,null);
String[] from = {DatabaseHelper.TITLE, DatabaseHelper.VALUE};
int[] to = {R.id.title, R.id.value};
cursorAdapter = new SimpleCursorAdapter(getActivity(), R.layout.row, null, from, to, 0);
setListAdapter(cursorAdapter);
getLoaderManager().initLoader(0, null, this);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.actions, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId()==R.id.add) {
add();
return(true);
}
return(super.onOptionsItemSelected(item));
}
#Override
public void onClick(DialogInterface dialog, int which) {
ContentValues values=new ContentValues();
AlertDialog dlg=(AlertDialog)dialog;
EditText title=(EditText)dlg.findViewById(R.id.title);
EditText value=(EditText)dlg.findViewById(R.id.value);
values.put(DatabaseHelper.TITLE, title.getText().toString());
values.put(DatabaseHelper.VALUE, value.getText().toString());
getActivity().getContentResolver().insert(Provider.Constants.CONTENT_URI, values);
getLoaderManager().restartLoader(0, null, this);
}
#Override
public void onListItemClick(ListView l, View v, int pos, long id) {
super.onListItemClick(l, v, pos, id);
getLoaderManager().restartLoader(0, null, this);
getActivity().getContentResolver().delete(Provider.Constants.CONTENT_URI,String.valueOf(id), null);
Toast.makeText(getActivity(), "Item id " + id + "clicked", Toast.LENGTH_SHORT).show();
}
private void add() {
LayoutInflater inflater=getActivity().getLayoutInflater();
View addView=inflater.inflate(R.layout.add_edit, null);
AlertDialog.Builder builder=new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.add_title).setView(addView)
.setPositiveButton(R.string.ok, this)
.setNegativeButton(R.string.cancel, null).show();
}
#Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
return new CursorLoader(getActivity().getApplicationContext(), Provider.Constants.CONTENT_URI, null, null, null, null);
}
public void insertNote(String title, Double value){
ContentValues values = new ContentValues();
values.put(DatabaseHelper.TITLE, title);
values.put(DatabaseHelper.VALUE, value);
Uri noteUri = getActivity().getContentResolver().insert(Provider.Constants.CONTENT_URI, values);
Log.d("MainActivity", "Inserted" + noteUri.getLastPathSegment());
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
cursorAdapter.swapCursor(cursor);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
cursorAdapter.swapCursor(null);
}
}
in on click after item deleted call to notifyDatasetChanged()
I have a android list layout. Basically it will list user's info on the screen. Please help me explain how the listView set the data. How the SimpleCursorAdapter links with Loader
Here's code :
public class ChatList extends ListActivity implements LoaderManager.LoaderCallbacks<Cursor>{
private SimpleCursorAdapter adapter;
private final int Adapter_AccountName = 1;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chatlist);
adapter = new SimpleCursorAdapter(this,
R.layout.main_list_item,
null,
new String[]{DataProvider.COL_NAME, DataProvider.COL_COUNT,DataProvider.PROFILE_COL_LASTMSGAT,DataProvider.PROFILE_COL_IMAGE},
new int[]{R.id.text1, R.id.text2,R.id.text3,R.id.avatar},
0);
adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
#Override
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
switch(view.getId()) {
// here can add one more line in the main page for each account
case R.id.text2:
int count = cursor.getInt(columnIndex);
if (count > 0) {
((TextView)view).setText(String.format("%d new message%s", count, count==1 ? "" : "s"));
}
return true;
case R.id.text3:
String lastUpdate = cursor.getString(columnIndex);
Date d = DbDatetimeUtility.getDate(cursor.getString(columnIndex));
Date t = DbDatetimeUtility.getCurrentDate();
((TextView)view).setText(DbDatetimeUtility.returnDifferentTime(d,t));
return true;
case R.id.avatar:
byte[] imageByte = cursor.getBlob(columnIndex);
((ImageView)view).setImageBitmap(DbBitmapUtility.getResizedBitmap(DbBitmapUtility.getImage(imageByte),125,125));
return true;
}
return false;
}
});
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(false);
//final ListView listView = getListView();
final ListView listView = getListView();
listView.setAdapter(adapter);
getLoaderManager().initLoader(0, null, this);
}
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Intent intent = new Intent(this, ChatActivity.class);
intent.putExtra(Common.PROFILE_ID, String.valueOf(id));
startActivity(intent);
}
//----------------------------------------------------------------------------
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
CursorLoader loader = new CursorLoader(this,
DataProvider.CONTENT_URI_PROFILE,
new String[]{DataProvider.COL_ID, DataProvider.COL_NAME, DataProvider.COL_COUNT,DataProvider.PROFILE_COL_LASTMSGAT,DataProvider.PROFILE_COL_IMAGE},
null,
null,//new String[]{DataProvider.PROFILE_COL_LASTMSGAT},
DataProvider.PROFILE_COL_LASTMSGAT + " DESC");
return loader;
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
adapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
adapter.swapCursor(null);
}
}
Thanks in advance!
Briefly for now, the main points are:
onCreateLoader gets the data from the SQLite database.
This code adapter = new SimpleCursorAdapter, populates the adapter.
This code listView.setAdapter(adapter); populates the ListView.
There is a nice Stackoverflow answer at Using SimpleCursorAdapter to get Data from Database to ListView
I have List fragment with Context menu on long press of list item. The list item clicked and the list item removed from my Database. But the list not refresh even after calling restart loader?
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setEmptyText("Loading...");
myAdapter = new MySimpleCursorAdapter(getActivity().getApplicationContext(), R.layout.my_list_item, null, new String[] {DBConstants.NAME,DBConstants.ITEM1,DBConstants.SYMBOL}, new int[] {R.id.my_companyname,R.id.my_item1,R.id.my_symbol},0);
setListAdapter(myAdapter);
registerForContextMenu(getListView());
MyLoader = getActivity().getSupportLoaderManager().initLoader(1, null, this);
}
#Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
DBHelper dbHelper=new DBHelper(getActivity());
return new MyLoader(getActivity(),dbHelper);
}
#Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor c) {
if(c!=null && c.getCount()>0){
myAdapter.swapCursor(c);
if (isResumed()) {
setListShown(true);
} else {
setListShownNoAnimation(true);
}
}
else
{
setEmptyText("Not selected");
}
}
#Override
public void onLoaderReset(Loader<Cursor> arg0) {
myAdapter.swapCursor(null);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
String selectedItem = item.getTitle().toString();
Log.i("context", "selected context menu item->"+selectedItem);
if(selectedItem.equalsIgnoreCase("Remove"))
{
AdapterView.AdapterContextMenuInfo menuInfo=(AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
String[] args={String.valueOf(menuInfo.id)};
Log.i("context", String.valueOf(menuInfo.id));
new DBHelper(getActivity()).getWritableDatabase().delete(DBConstants.MYSTOCKS_TABLE, "_ID=?", args);
getActivity().getSupportLoaderManager().restartLoader(1, null, this);
/*
Cursor cursor = myAdapter.getCursor();
myAdapter.swapCursor(cursor);
*/
//getLoaderManager().initLoader(0, null, this);
}
return super.onContextItemSelected(item);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
//super.onCreateContextMenu(menu, v, menuInfo);
getActivity().getMenuInflater().inflate(R.menu.mystocks_context, menu);
}
Do you add the fragment in activity's onCreate or onResume? If the latter, you might want to move the fragment setup (transaction creation, addition of the fragment, committing) to onCreate. After doing that restartLoader() will work properly.
public class NewFriendsListFragment extends SherlockListFragment implements
LoaderManager.LoaderCallbacks<Cursor> {
int monthchange, daychange;
Dialog dialog;
int pos;
CheckedTextView ctv_name;
private SimpleCursorAdapter mAdapter=null;
private SQLiteCursorLoader loader=null;
String mCurFilter;
private static Handler responseHandler;
boolean loaded=false;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//some more stuff...
setHasOptionsMenu(true);
mAdapter = new FriendListSCA(getSherlockActivity().getApplicationContext(),
R.layout.friend_item, null,null, null, null, null, NAME),
new String[]{NAME,MONTH,UID}, new int[]{R.id.name,R.id.info,R.id.profile_pic});
setListAdapter(mAdapter);
setListShown(false);
registerForContextMenu(getListView());
getLoaderManager().initLoader(0, null, this);
responseHandler = new Handler()
{
//handler code
};
}
public Loader<Cursor> onCreateLoader(int loaderId, Bundle args) {
//loader code
return(loader);
}
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
mAdapter.changeCursor(cursor);
// Showin List
if (isResumed()) {
setListShown(true);
} else {
setListShownNoAnimation(true);
}
}
public void onLoaderReset(Loader<Cursor> loader) {
mAdapter.changeCursor(null);
}
#Override
public boolean onContextItemSelected(android.view.MenuItem item) {
AdapterContextMenuInfo info;
try {
info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
} catch (ClassCastException e) {
return false;
}
pos=info.position;
switch (item.getItemId()) {
case R.id.edit_item:
show_dialog();
return true;
}
return(super.onOptionsItemSelected(item));
}
#Override
public void onListItemClick(ListView l, View v, final int position, long id) {
Log.e("onListItemClick","Inside onListItemClick");
ContentValues cv= new ContentValues();
//MORE CODE
loader.update(TABLE_NAME_INCLUDE, cv, _ID+" = ?", new String[]{Integer.toString(position)});
}
private class FriendListSCA extends SimpleCursorAdapter
{
public FriendListSCA(Context context, int layout, Cursor c,
String[] from, int[] to) {
super(context, layout, c, from, to,0);
setViewBinder(new FriendsListDataViewBinder());
}
}
public class FriendsListDataViewBinder implements SimpleCursorAdapter.ViewBinder
{
//_ID + "," + UID+","+NAME+","+MONTH+","+DAY+","+WISH
#Override
public boolean setViewValue(View view, Cursor c, int columnIndex)
{
switch (view.getId())
{
case R.id.name:
CheckedTextView ctv= (CheckedTextView)view;
ctv.setText(c.getString(2));
if(c.getInt(5)==0 || c.getInt(4)==-1)
{
ctv.setPaintFlags(ctv.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
ctv.setChecked(false);
}
else
{
ctv.setPaintFlags(ctv.getPaintFlags() & (~ Paint.STRIKE_THRU_TEXT_FLAG));
ctv.setChecked(true);
}
return true;
case R.id.info:
if(c.getInt(4)!=-1)
{
((TextView)view).setText(Utility.MONTH_NAME[c.getInt(3)-1] + " " + Integer.toString(c.getInt(4)));
}
else
{
((TextView)view).setText("Tap and hold to manually enter");
}
return true;
case R.id.profile_pic:
if(!loaded)
return true;
((ImageView)view).setImageBitmap(Utility.model.getImage(
Long.toString( c.getLong(1) ), getURL(c.getLong(1)) ));
return true;
}
return false;
}
}
private void show_dialog()
{
//DATE PICKER CODE
okay.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v)
{
ContentValues cv=new ContentValues();
cv.put(MONTH, monthchange);
cv.put(DAY, daychange);
loader.update(TABLE_NAME_INCLUDE, cv, _ID+" = ?" , new String[]{Integer.toString(pos)});
//getLoaderManager().restartLoader(0, null, NewFriendsListFragment.this);
//I tried calling restart loader, but nothing, when I checked
//it turned out the sqlite database wasn't being updated
responseHandler.sendEmptyMessage(1); //just dismisses dialog
}
});
dialog.show();
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Place an action bar item for searching.
MenuItem item = menu.add("Search");
item.setIcon(android.R.drawable.ic_menu_search);
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
View searchView = SearchViewCompat.newSearchView(getActivity());
if (searchView != null) {
SearchViewCompat.setOnQueryTextListener(searchView,
new OnQueryTextListenerCompat() {
#Override
public boolean onQueryTextChange(String filtext) {
mCurFilter = !TextUtils.isEmpty(filtext) ? filtext : null;
getLoaderManager().restartLoader(0, null, NewFriendsListFragment.this);
return true;
}
});
item.setActionView(searchView);
}
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
}
}
I'm using a SherlockListFragment from the ActionBarSherlock library to display a list using a CommonsWare Loaderex sqlite cursor loader, and evrything seems to work fine, the names and birthdays and profile pics are all displayed fine, but I can't seem to be able to update any of the data in the table using loader.update(...), nothing happens when I call it.
What's wrong?
You have:
loader.update(TABLE_NAME_INCLUDE, cv, _ID+" = ?", new String[]{Integer.toString(position)});
In all likelihood, that should be:
loader.update(TABLE_NAME_INCLUDE, cv, _ID+" = ?", new String[]{Integer.toString(id)});
(replacing position with id)
i want to refresh/update afeter i select the "delete" ContextItem, it deletes but dont "refresh" the listview
see on code ListActivity:
public class ProjetoProTelefoneActivity extends ListActivity {
public final static String ID_EXTRA = "br.com.DaniloDeLuca.ProjetoProTelefone._ID";
Cursor modelo = null;
RestaurantAdapter adapter = null;
RestauranteHelper helper=null;
SharedPreferences prefs=null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
helper = new RestauranteHelper(this);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
initList();
prefs.registerOnSharedPreferenceChangeListener(prefListener);
registerForContextMenu(getListView());
}
public void onDestroy(){
super.onDestroy();
helper.close();
}
//*********************************************************************************************************************************
// Long Press menu
//*********************************************************************************************************************************
public void onCreateContextMenu(ContextMenu menu,View v,ContextMenuInfo menuInfo){
super.onCreateContextMenu(menu, v, menuInfo);
AdapterView.AdapterContextMenuInfo info;
try {
info = (AdapterView.AdapterContextMenuInfo) menuInfo;
} catch (ClassCastException e) {
return;
}
Cursor cursor = (Cursor) getListAdapter().getItem(info.position);
if (cursor == null) {
return;
}
new MenuInflater(this).inflate(R.menu.option_item,menu);
super.onCreateContextMenu(menu,v,menuInfo);
}
public boolean onContextItemSelected(MenuItem item)
{
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
int index = info.position;
View view = info.targetView;
long id = info.id;
if(item.getItemId()==R.id.edit){
Intent i=new Intent(ProjetoProTelefoneActivity.this, DetailForm.class);
i.putExtra(ID_EXTRA, String.valueOf(id));
startActivity(i);
return(true);
}
else if(item.getItemId()==R.id.remove){
Intent i=new Intent(ProjetoProTelefoneActivity.this, DeleteItemList.class);
i.putExtra(ID_EXTRA, String.valueOf(id));
startActivity(i);
return(true);
}
return super.onContextItemSelected(item);
}
//*********************************************************************************************************************************
// Fim Long Press menu
//*********************************************************************************************************************************
public void onListItemClick(ListView list, View view,
int position,long id){
Intent i=new Intent(ProjetoProTelefoneActivity.this, DetailForm.class);
i.putExtra(ID_EXTRA, String.valueOf(id));
startActivity(i);
}
//hook into menu button for activity
public boolean onCreateOptionsMenu(Menu menu){
new MenuInflater(this).inflate(R.menu.option,menu);
return(super.onCreateOptionsMenu(menu));
}
/// when menu button option selected
public boolean onOptionsItemSelected(MenuItem item){
if(item.getItemId()==R.id.add){
startActivity(new Intent(ProjetoProTelefoneActivity.this, DetailForm.class));
return(true);
}
else if(item.getItemId()==R.id.prefs){
startActivity(new Intent(this, EditPreferences.class));
return(true);
}
return(super.onOptionsItemSelected(item));
}
private SharedPreferences.OnSharedPreferenceChangeListener prefListener=
new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
if(key.equals("sort_order")){
initList();
}
}
};
private void initList(){
if(modelo!=null){
stopManagingCursor(modelo);
modelo.close();
}
modelo =helper.getAll(prefs.getString("sort_order","nome DESC"));
startManagingCursor(modelo);
adapter = new RestaurantAdapter(modelo);
setListAdapter(adapter);
}
class RestaurantAdapter extends CursorAdapter {
RestaurantAdapter(Cursor c) {
super(ProjetoProTelefoneActivity.this, c);
}
public void bindView(View row, Context ctxt,
Cursor c) {
RestaurantHolder holder=(RestaurantHolder)row.getTag();
holder.populateFrom(c, helper);
}
public View newView(Context ctxt, Cursor c,
ViewGroup parent) {
LayoutInflater inflater=getLayoutInflater();
View row=inflater.inflate(R.layout.row, parent, false);
RestaurantHolder holder=new RestaurantHolder(row);
row.setTag(holder);
return(row);
}
}
static class RestaurantHolder {
private TextView name=null;
private TextView address=null;
private ImageView icon=null;
RestaurantHolder(View row) {
name=(TextView)row.findViewById(R.id.title);
address=(TextView)row.findViewById(R.id.address);
icon=(ImageView)row.findViewById(R.id.icon);
}
void populateFrom(Cursor r,RestauranteHelper helper) {
name.setText(helper.getNome(r));
address.setText(helper.getEnd(r));
if (helper.getTipo(r).equals("casa")) {
icon.setImageResource(R.drawable.casa_icon);
}
else if (helper.getTipo(r).equals("apartamento")) {
icon.setImageResource(R.drawable.apartamento_icon);
}
else {
icon.setImageResource(R.drawable.comercio_ico);
}
}
}
}
Now my DeleteItemList:
public class DeleteItemList extends Activity{
RestauranteHelper helper = null;
String restauranteId= null;
public void onCreate(Bundle savedInstaceState){
super.onCreate(savedInstaceState);
helper= new RestauranteHelper(this);
restauranteId=getIntent().getStringExtra(ProjetoProTelefoneActivity.ID_EXTRA);
helper.delete(restauranteId);
finish();
}
public void onDestroy(){
super.onDestroy();
helper.close();
}
}
RestauranteHelper.delete:
public void delete(String id){
String[] args = {id};
getWritableDatabase().delete("restaurantes", "_ID =?", args);
}
idk if its clear what i want to do... i want to refresh the list, afeter selecting "Remove" option.
=D
After changing the items in the list call the notifyDatasetChanged on your list adapter. That will do it.
Here is how the ListView will work.
After you initialize the list, set the items in the list adapter.
Now call listview.setAdapter method to set the adapter.
Now when ever you make any changes in the items, change them on the list that you have passed to the adapter.
Then call the notofyDatasetChanged on your adapter.
That should work. If that is not working, then something else is wrong and try to debug each step of your code.
** In your case you are calling the delete on the database helper, but your cursor or adapter does not update when you change your stuff on the database. You need to remove that item from the cursor or query the database again and then pass it to the adapter.