简体   繁体   中英

Android ListView with SQLite

I'd like to refresh the Listview items. These items are populated from SQLite database. My code is below

public class Weeve extends Activity {
      private String[] lv_arr;
    protected ListView CView;
    private DBAdapter mDbHelper;

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

   mDbHelper = new DBAdapter(this);
    mDbHelper.open();

    Cursor c = mDbHelper.getAll();
    if (c.getCount() > 0)
    {if (c.moveToFirst())
    {
        ArrayList strings = new ArrayList();
       do {                    
          String mC = c.getString(0);
          strings.add(mC);  

       } while (c.moveToNext());
       lv_arr = (String[]) strings.toArray(new String[strings.size()]);
    }
    }  
    else Toast.makeText(this, 
           "No more Records", 
           Toast.LENGTH_SHORT).show();
    c.close();

    ListView CView = new ListView(this);
    CView.setAdapter(new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, lv_arr));      
    setContentView(CView);}}

I'd like to make refreshing this list view after adding, updating or deleting SQLite table. These operations are called by content or option menu. I tried to create these code into a separated function and call it after every operation. But can't. I think setContentView(CView) statement.

I also tried to use SimpleCursorAdapter like notepad sample from Android.com. I got Thread error. Help me.

You can do that using Adapter.notifyDataSetChanged().

However, I find your code slightly off. You're fetching rows from the database using a cursor, just to create a new ArrayAdapter for the row values. Why not use a CursorAdapter to back your list? That's what it's meant for.

确保您的所有活动都在清单中

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM