0

I am a beginner and I am studying the android at University.

Currently, I am using DBAdapter at the moment, and I am trying to show the data on layout from database by using ListView(if there are better way instead, advice me).

When I run application at the moment, makeText function will be called, and it will be shown data information.

Instead of showing the notification, I want to show some of values on ListView such as name, and quantity.

How can I get it? which ListView do I have to use it with database? I want to know the handling database with ListView. Please advice.

Code attached below:

FridgeDbAdapter.java

public class FridgeDbAdapter
{
public static final String KEY_ROWID = "_id";
public static final String KEY_CATEGORY = "category";
public static final String KEY_NAME = "name";
public static final String KEY_EXPIRED_DATE = "expired_date";
private static final String DATABASE_TABLE = "fridge_table";
private Context ctxt;
private SQLiteDatabase db;
private FridgeDatabaseHelper dbhelper;


public FridgeDbAdapter(Context ctxt)
{
    this.ctxt = ctxt;
}

//DB databaseHelper
public class FridgeDatabaseHelper extends SQLiteOpenHelper
{
    private static final String DATABASE_NAME = "fridge_db";
    private static final int DATABASE_VERSION = 1;
    private static final String DATBASE_CREATE = 
            "create table fridge_table (_id integer primary key autoincrement, "
 + "category text not null, name text not null, expired_date text not null);";

    public FridgeDatabaseHelper(Context ctxt)
    {
        super(ctxt, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db)
    {
        db.execSQL(DATBASE_CREATE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVer, int newVer)
    {
        Log.w(FridgeDatabaseHelper.class.getName(), 
                    "Upgrading database from version " + oldVer + " to "
        + newVer + ", which will delete the old data.");
        db.execSQL("DROP TABLE IF EXISTS fridge_table");
        //Method is called during creation of new database
        onCreate(db);
    }
}

//Open database
public FridgeDbAdapter open() throws SQLException
{
    dbhelper = new FridgeDatabaseHelper(ctxt);
    db = dbhelper.getWritableDatabase();
    return this;
}

//Close database
public void close(){
    dbhelper.close();
}

//Create a new item
public long insertItem(String category, String name, String expired_date)
{
    ContentValues initialValues = new ContentValues();
    initialValues.put(KEY_CATEGORY, category);
    initialValues.put(KEY_NAME, name);
    initialValues.put(KEY_EXPIRED_DATE, expired_date);
    return db.insert(DATABASE_TABLE, null, initialValues);
}

//update a item
public boolean updateItem(long rowId, String category, 
    String name, String expired_date)
{
    ContentValues updateValues = new ContentValues();
    updateValues.put(KEY_CATEGORY, category);
    updateValues.put(KEY_NAME, name);
    updateValues.put(KEY_EXPIRED_DATE, expired_date);
    return db.update(DATABASE_TABLE, updateValues, KEY_ROWID + "=" + rowId,
            null) > 0;      
}

//delete a item
public boolean deleteItem(long rowId){
    return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}

//return cursor over the list of all items in the database
public Cursor fetchAllItems(){
    return db.query(DATABASE_TABLE, new String[]{KEY_ROWID, KEY_CATEGORY, 
                            KEY_NAME, KEY_EXPIRED_DATE}, 
                   null, null, null, null, null);
}

//return a cursor positioned at the defined item
public Cursor fetchItem(long rowId) throws SQLException{
    Cursor mCursor = db.query(true, DATABASE_TABLE, 
            new String[]{KEY_ROWID, KEY_CATEGORY, KEY_NAME,
    KEY_EXPIRED_DATE}, KEY_ROWID + "=" + rowId, null, null, null, null, null);
    if(mCursor != null){
        mCursor.moveToFirst();
    }
    return mCursor;
}
}

Fridge.java

public class Fridge extends Activity{
//Button goBack;
Button button1;
TextView text;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fridge);

    FridgeDbAdapter db = new FridgeDbAdapter(this);

  //Open database
    db.open();
   //Get all items
   Cursor c = db.fetchAllItems();
    if(c.moveToFirst())
    {
        do
        {
            //Call displayItem method in below
            DisplayItem(c);
        } while (c.moveToNext());
    }
    else
    {
        Toast.makeText(this, "No item found", Toast.LENGTH_SHORT).show();
    }
    db.close();
 }  

public void DisplayItem(Cursor c){
    Toast.makeText(this, "id: " + c.getString(0) + "\n" + 
                    "category: " + c.getString(1) + "\n" +
                    "name: " + c.getString(2) + "\n" + 
                    "expired date: " + c.getString(3), 
                                            Toast.LENGTH_SHORT).show();
}


}

fridge.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Fridger page" />

 <LinearLayout
    android:id="@+id/fridge_List_View"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >
 </LinearLayout>

 <Button
    android:id="@+id/add_Btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Add item" />


 </LinearLayout>
Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
wholee1
  • 1,491
  • 13
  • 34
  • 51

5 Answers5

3

Formula you might wanna consider using it's the Loader API, it's great because it help you handle your cursor and query efficiently.

Loaders make it easy to asynchronously load data in an activity or fragment.

  • They are available to every Activity and Fragment.
  • They provide asynchronous loading of data.
  • They monitor the source of their data and deliver new results when the content changes.
  • They automatically reconnect to the last loader's cursor when being recreated after a configuration change. Thus, they don't need to
    re-query their data.

Implements LoaderCallbacks in your ListView or ListFragment, then override the methods onCreateLoader, onFinishedLoader, onRestartLoader. Initialize your loader with the LoaderManager, getLoaderManager().initLoader, and enjoy.

The only disadvantage that I've seen it's that is usefull if you have a ContentProvider, but even if you don't you can try some solutions in SO, like Loader without ContentProvider, In general i've learned that ContentProvider makes your life so much easier with the cursors, granted!.

Community
  • 1
  • 1
Necronet
  • 6,704
  • 9
  • 49
  • 89
1

public class ShowNotificationAdapter extends SimpleCursorAdapter{

Cursor dataCursor;
LayoutInflater mInflater;
Context context;
int layoutType;
DatabaseHelper db_helper;

public CustomAdapter(Context context, int layout, Cursor dataCursor, String[] from, int[] to) { super(context, layout, dataCursor, from, to);

        this.context=context;
        this.dataCursor = dataCursor;
        mInflater = LayoutInflater.from(context);

        db_helper=new DatabaseHelper(context);
        db_helper.open();           
}

@Override public View getView(final int position, View convertView, ViewGroup parent) {

        final ViewHolder holder;

        if(convertView==null)
        {
                 convertView = mInflater.inflate(R.layout.custom_listitem, null);
                 holder = new ViewHolder();

                 holder.name=(TextView)convertView.findViewById(R.id.name);
                 holder.quantity=(TextView)convertView.findViewById(R.id.quantity);
                 holder.otherInfo=(TextView)convertView.findViewById(R.id.otherInfo);                    
        }
        else
        {   
            holder=(ViewHolder)convertView.getTag();
        }

        dataCursor.moveToPosition(position);                

        String nameString=Integer.toString(dataCursor.getString(dataCursor.getColumnIndexOrThrow("name")));//column name of "name"
        holder.name.setText(nameString);

        String quantityString=dataCursor.getString(dataCursor.getColumnIndexOrThrow("quantity")); //column name of "quantity" 
        holder.quantity.setText(quantityString);      

        String otherInfoString=dataCursor.getString(dataCursor.getColumnIndexOrThrow("field_name"));  
        holder.otherInfo.setText(quantityString); 

        return convertView;
}    

static class ViewHolder
{
        TextView name;
        TextView quantity;
        TextView otherInfo;
}
@Override
public Object getItem(int position) {

        return position;
}

}

0

You want to use a ListActivity.

And you will need to create a cursor and query the data in the fillData method.

Here's a decent tutorial on how to do that:

http://www.vogella.de/articles/AndroidSQLite/article.html

Bryan
  • 3,629
  • 2
  • 28
  • 27
0

Use ListView and SimpleCursor adapter.

Example code can be found at:

wannik
  • 12,212
  • 11
  • 46
  • 58
0

You can use a custom_adapter using SimpleCursorAdapter,for getting your database info. displayed onto the listview.

CustomAdpater.class:

public class CustomAdpater extends SimpleCursorAdapter{

    Cursor dataCursor;
    LayoutInflater mInflater;
    Context context;
    int layoutType;
    DatabaseHelper db_helper;

   public CustomAdapter(Context context, int layout, Cursor dataCursor, String[] from,
                    int[] to) {
            super(context, layout, dataCursor, from, to);

            this.context=context;
            this.dataCursor = dataCursor;
            mInflater = LayoutInflater.from(context);

            db_helper=new DatabaseHelper(context);
            db_helper.open();           
    }

 @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

            final ViewHolder holder;

            if(convertView==null)
            {
                     convertView = mInflater.inflate(R.layout.custom_listitem, null);
                     holder = new ViewHolder();

                     holder.name=(TextView)convertView.findViewById(R.id.name);
                     holder.quantity=(TextView)convertView.findViewById(R.id.quantity);
                     holder.otherInfo=(TextView)convertView.findViewById(R.id.otherInfo);                    
            }
            else
            {   
                holder=(ViewHolder)convertView.getTag();
            }

            dataCursor.moveToPosition(position);                

            String nameString=Integer.toString(dataCursor.getString(dataCursor.getColumnIndexOrThrow("name")));//column name of "name"
            holder.name.setText(nameString);

            String quantityString=dataCursor.getString(dataCursor.getColumnIndexOrThrow("quantity")); //column name of "quantity" 
            holder.quantity.setText(quantityString);      

            String otherInfoString=dataCursor.getString(dataCursor.getColumnIndexOrThrow("field_name"));  
            holder.otherInfo.setText(quantityString); 

            return convertView;
    }    

    static class ViewHolder
    {
            TextView name;
            TextView quantity;
            TextView otherInfo;
    }
    @Override
    public Object getItem(int position) {

            return position;
    }
}

custom_listitem.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="fill_parent"  
    android:orientation="vertical">
        <TextView android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:padding="5dp"
                  android:id="@+id/name"
                  />
        <TextView android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:padding="5dp"
                  android:id="@+id/quantity"
                  />
        <TextView android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:padding="5dp"
                  android:id="@+id/otherInfo"
                  />
</LinearLayout>

MainActivity.class:

...
ListView listview=(ListView)findViewById(R.id.listview);

Cursor cursor=<get data to be passed to custom adapter>;
String[] from={"name","quantity"};//field names of 'name' and 'quantity'
int[] to={R.id.name,R.id.quantity};      

CustomAdapter ca=new CustomAdapter(context,R.layout.custom_listitem,cursor,from,to);
listview.setAdapter(ca);
ca.notifyDataSetChanged();
...
Nathan A
  • 11,059
  • 4
  • 47
  • 63
Hiral Vadodaria
  • 19,158
  • 5
  • 39
  • 56
  • Thanks you for your coding. I am wondering about listitem.xml. Where is R.id.listview? I cannot find it. Is it possible to select the row for passing the edit page? I want to make a list and each row can be clicked for edit. – wholee1 Nov 16 '11 at 11:35
  • How can I write on Cursor cursor=;? – wholee1 Nov 16 '11 at 11:52
  • You cannot edit listitem once it is listed. Secondly,you need to work on basics of android first.here,R.id.listview simply the listview you defined in your layout file with id as "listview". And also work on Cursor basics. It is really easiest code someone can give you! – Hiral Vadodaria Nov 16 '11 at 11:56