简体   繁体   中英

Retrieve values from sqlite to android listview

     t1=(TextView)findViewById(R.id.s1);
     t2=(TextView)findViewById(R.id.s2);
     t3=(TextView)findViewById(R.id.s3);
     t4=(TextView)findViewById(R.id.s4);

        dbase=openOrCreateDatabase("reg_db", Context.MODE_PRIVATE, null);
        dbase.execSQL("create table if not exists registration(name       varchar(40),age number(5),casestudy varchar(100),gender varchar(10),phonenumber varchar(12),doctorname varchar(50),date DATE,time varchar(5))");


        Cursor c=dbase.query("registration",new String[]{"name","age","casestudy","gender","phonenumber","doctorname","date","time"}, null, null, null, null, null);
        while(c.moveToNext()){
        String  c1=c.getString(0);
        String  c2=c.getString(1);
        String  c3=c.getString(2);
        String  c4=c.getString(3);
        String  c5=c.getString(4);
        String  c6=c.getString(5);
        String  c7=c.getString(6);
        String  c8=c.getString(7);
        t1.setText(c1);
        t2.setText(c5);
        t3.setText(c7);
        t4.setText(c8);

I am able display only one row in my table how to display all rows in a list form... please specify thank you

Use this before while loop

You need to set curser at First position

  if (c!= null) {

        //more to the first row
        c.moveToFirst();



while(c.moveToNext()){
        String  c1=c.getString(0);
        String  c2=c.getString(1);
        String  c3=c.getString(2);
        String  c4=c.getString(3);
        String  c5=c.getString(4);
        String  c6=c.getString(5);
        String  c7=c.getString(6);
        String  c8=c.getString(7);
        t1.setText(c1);
        t2.setText(c5);
        t3.setText(c7);
        t4.setText(c8);
}
}

Use this code :

 if(c!=null)
  {
    if (c.moveToFirst()) {
      do {
        String  c1=c.getString(0);
        String  c2=c.getString(1);
        String  c3=c.getString(2);
        String  c4=c.getString(3);
        String  c5=c.getString(4);
        String  c6=c.getString(5);
        String  c7=c.getString(6);
        String  c8=c.getString(7);
        t1.setText(c1);
        t2.setText(c5);
        t3.setText(c7);
        t4.setText(c8);

       } while (c.moveToNext());
     }
  }
if (c.moveToFirst()){
   do{
      // do what ever you want here
   }while(.moveToNext());
}
c.close();

I think you appear to be trying to populate the ListView, while a Listview will have another layout for each row/entry, this being pointed to by an adapter.

That is, to populate a Listview you will need to have an adapter. The adapter will utilise an XML layout that defines each entry (row), these in addition to the layout containing the ListView and the activity.

Here's an example of a custom cursor adapter :-

package mjt.shopper;

import android.content.Context;
import android.database.Cursor;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.TextView;

/**
 * Created by Mike092015 on 6/02/2016.
 */
class AislesCursorAdapter extends CursorAdapter {
    public AislesCursorAdapter(Context context, Cursor cursor, int flags) {
        super(context, cursor, 0);
    }
    @Override
    public View getView(int position, View convertview, ViewGroup parent) {
        View view = super.getView(position, convertview, parent);
        Context context = view.getContext();
        if (position % 2 == 0) {
            view.setBackgroundColor(ContextCompat.getColor(context, R.color.colorlistviewroweven));
        } else {
            view.setBackgroundColor(ContextCompat.getColor(context, R.color.colorlistviewrowodd));
        }
        return view;
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        TextView textviewaisleid = (TextView) view.findViewById(R.id.aisle_id_entry);
        TextView textviewaislename = (TextView) view.findViewById(R.id.aisle_name_entry);
        TextView textviewaisleorder = (TextView) view.findViewById(R.id.aisle_order_entry);
        TextView textviewaisleshopref = (TextView) view.findViewById(R.id.aisle_shopref_entry);

        textviewaisleid.setText(cursor.getString(ShopperDBHelper.AISLES_COLUMN_ID_INDEX));
        textviewaislename.setText(cursor.getString(ShopperDBHelper.AISLES_COLUMN_NAME_INDEX));
        textviewaisleorder.setText(cursor.getString(ShopperDBHelper.AISLES_COLUMN_ORDER_INDEX));
        textviewaisleshopref.setText(cursor.getString(ShopperDBHelper.AISLES_COLUMN_SHOP_INDEX));
    }
    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        return LayoutInflater.from(context).inflate(R.layout.activity_aisle_list_entry, parent, false);
    }
}

The getView method isn't important and can be ommitted (in the above it alternates the colours of the rows/entries).

You will need the bindView method, obviously tailored to your needs (first half gets the views that are to be populated, the second half sets the views and you may notice that it looks similar to part of your code).

You will also need the newView method which basically sets the layout that is to be used for each row/entry of the ListView (ie the following XML).

Note! ShopperDBHelper.AISLES_COLUMN_???_INDEX contains the index into the cursor

here's an example XML (the one used by the above adapter) :-

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/standard_listview_row_padding_vertical"
    android:paddingLeft="@dimen/standard_listview_row_padding_horizontal"
    android:paddingRight="@dimen/standard_listview_row_padding_horizontal"
    android:paddingTop="@dimen/standard_listview_row_padding_vertical"
    tools:context=".AisleListEntryActivity">
    <!-- Aisle ID 4 debugging -->
    <TextView
        android:id="@+id/aisle_id_entry"
        android:layout_width="30sp"
        android:layout_height="@dimen/rowheight"
        android:textSize="@dimen/standard_listview_text_size"
        android:visibility="visible"/>
    <!-- Aisle Name -->
    <TextView
        android:id="@+id/aisle_name_entry"
        android:layout_width="@dimen/ailsename_text_size"
        android:layout_height="@dimen/rowheight"
        android:textSize="@dimen/standard_listview_text_size"
        android:textStyle="bold" />
    <!-- Aisle Order-->
    <TextView
        android:id="@+id/aisle_order_entry"
        android:layout_width="@dimen/ailseorder_text_size"
        android:layout_height="@dimen/rowheight"
        android:textSize="@dimen/standard_listview_text_size"/>
    <!-- Aisle Shopref 4 debugging -->
    <TextView
        android:id="@+id/aisle_shopref_entry"
        android:layout_width="50sp"
        android:layout_height="@dimen/rowheight"
        android:textSize="@dimen/standard_listview_text_size"
        android:visibility="gone"/>
</LinearLayout>

Here's an example of the code that gets the cursor and sets the listview to use the adapter (again as used by the above), this would be in your activity:-

    Cursor aislescsr = shopperdb.getAislesPerShopAsCursor(csr.getInt(ShopperDBHelper.SHOPS_COLUMNN_ID_INDEX));
    final ListView lv = (ListView) findViewById(R.id.aalbclv01);
    AislesCursorAdapter aisleadapter = new AislesCursorAdapter(lv.getContext(), aislescsr, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
    currentaca = aisleadapter;
    lv.setAdapter(aisleadapter);

The first line populates the cursor from the database. The second line gets the ListView that will be populated with the data from the database. The third line sets the adapter's cursor. The fourth line is not relevant. The fifth line ties the adapter to the ListView.

There is a SimpleCursorAdapter but I've never used one, so can't really tell you about it/them.

Additionally CursorAdapter expects there to a column named _id, so you may have to use AS _id.

here's an example where I didn't have _id and use AS to set it (see 3rd line) :-

        SQLiteDatabase db = this.getReadableDatabase();
        String sqlstr = " SELECT " + PRODUCTUSAGE_COLUMN_AISLEREF +
                " AS _id, " +
                PRODUCTUSAGE_COLUMN_PRODUCTREF + ", " +
                PRODUCTUSAGE_COLUMN_COST + ", " +
                PRODUCTUSAGE_COLUMN_BUYCOUNT + ", " +
                PRODUCTUSAGE_COLUMN_FIRSTBUYDATE + ", " +
                PRODUCTUSAGE_COLUMN_LATESTBUYDATE + ", " +
                PRODUCTUSAGE_COLUMN_MINCOST +
                " FROM " + PRODUCTUSAGE_TABLE_NAME +
                " ORDER BY _id;";
        return db.rawQuery(sqlstr, null);

make Method Like this in Database Class

    // Getting All User
public List<UserModel> getAllUser() {
    List<UserModel> userList = new ArrayList<UserModel>();
    // Select All Query
    String selectQuery = "SELECT  * FROM " + TABLE_USER;

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            UserModel user = new UserModel();
            user.setId(cursor.getString(0));
            user.setName(cursor.getString(1));
            user.setEmail(cursor.getString(2));
            // Adding user to list
            userList.add(user);
        } while (cursor.moveToNext());
    }

    // return user list
    return userList;
}

So you call this method and you will get List type of model class

after that you just have to pass in adapter and implement it

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