如何在listview Android中显示数据库结果

时间:2016-04-13 11:28:00

标签: android sqlite listview arraylist

我很难将SQLite db中某个特定表格的列中的项目存储到ArrayList中,然后附加到我的应用中的ListView。< / p>

任何关于如何做到这一点的全面而详细的例子将不胜感激。

感谢。

3 个答案:

答案 0 :(得分:0)

基本上你有4个组件。两个xml布局,一个游标适配器(不需要从游标创建一个数组)和从数据库中检索数据的代码。第一个布局包括ListView,第二个是每个条目/行的布局。

第一个布局,将通过活动的onCreate方法中的setContentView调用。这将包含以下内容: -

<ListView
    android:id="@+id/aslbclv01"
    android:layout_width="match_parent"
    android:layout_height="@dimen/standard_listview_height"
    android:longClickable="true">
</ListView>

请注意,据我所知,高度必须特定于ListView才能滚动。

第二个布局条目/行xml的示例如下(本示例中为 R.layout.activity_shop_list_entry ): -

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="0dp"
    android:background="@color/colorlistviewroweven"
    tools:context=".ShopListEntryActivity">
    <TextView
        android:id="@+id/shop_name_entry"
        android:layout_width="@dimen/standard_dummy_size"
        android:layout_height="match_parent"
        android:layout_weight="0.3"
        android:singleLine="true"
        android:textSize="@dimen/standard_subsubsubheading_text_size"
        android:textStyle="bold" />
    <TextView
        android:id="@+id/shop_city_entry"
        android:layout_width="@dimen/standard_dummy_size"
        android:layout_height="match_parent"
        android:layout_weight="0.3"
        android:singleLine="true"
        android:textSize="@dimen/standard_subsubsubheading_text_size"/>
    <TextView
        android:id="@+id/shop_street_entry"
        android:layout_width="@dimen/standard_dummy_size"
        android:layout_height="match_parent"
        android:layout_weight="0.4"
        android:singleLine="true"
        android:textSize="@dimen/standard_subsubsubheading_text_size"/>
</LinearLayout>

上面的光标适配器(在本例中为自定义,因为我从未使用过简单光标适配器)是: -

package mjt.shopper;

import android.content.Context;
import android.database.Cursor;
import android.graphics.Color;
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 2/02/2016.
 */
class ShopsCursorAdapter extends CursorAdapter {
    public ShopsCursorAdapter(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 View newView(Context context, Cursor cursor, ViewGroup parent) {
        return LayoutInflater.from(context).inflate(R.layout.activity_shop_list_entry, parent, false);
    }
    @Override
    public void bindView(View view,Context context, Cursor cursor) {
        TextView textViewShopName = (TextView) view.findViewById(R.id.shop_name_entry);
        TextView textViewShopStreet = (TextView) view.findViewById(R.id.shop_street_entry);
        TextView textViewShopCity = (TextView) view.findViewById(R.id.shop_city_entry);

        textViewShopName.setText(cursor.getString(ShopperDBHelper.SHOPS_COLUMN_NAME_INDEX));
        textViewShopStreet.setText(cursor.getString(ShopperDBHelper.SHOPS_COLUMN_STREET_INDEX));
        textViewShopCity.setText(cursor.getString(ShopperDBHelper.SHOPS_COLUMN_CITY_INDEX));
    }
}

请注意,SHOPS.COLUMN _ ???? _ INDEX是光标中相应列的偏移量。

另请注意,不需要getView(在上面它将行设置为替代颜色)。

R.layout.activity_shop_list_entry 是第二个设置了TextViews的xml。

在活动中,在onCreate方法中,以下代码填充ListView: -

        final Cursor csr = shopperdb.getShopsAsCursor();
        final ListView listview = (ListView) findViewById(R.id.aslbclv01);
        final ShopsCursorAdapter adapter = new ShopsCursorAdapter(this,csr, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        listview.setAdapter(adapter);

第一行通过getShopsAsCursor方法从数据库中提取数据作为游标。 第二行获取ListView的id。 第三行实例化CursorAdapter(在本例中为ShopsCursorAdapter)。 第四行设置ListView的cursoradapter。

根据评论,这里是 getShopsAsCursor 方法,它在DBHelper中编码: -

public Cursor getShopsAsCursor() {
    SQLiteDatabase db = this.getReadableDatabase();
    String sqlstr = "SELECT * FROM " + SHOPS_TABLE_NAME +
            " ORDER BY " + SHOPS_COLUMN_NAME + ", " + SHOPS_COLUMN_CITY + ";";
    return db.rawQuery(sqlstr,null);
}

答案 1 :(得分:0)

您可以使用Cursor适配器直接将数据从SQLite设置为listview。 这是示例代码。

Tier3CompileThreshold

了解更多信息https://coderwall.com/p/fmavhg/android-cursoradapter-with-custom-layout-and-how-to-use-it

答案 2 :(得分:0)

尝试以下代码

<强> ListViewActivity.java

public class ListViewActivity extends Activity
{
    ListView listCustom;
    private SQLiteDatabase db;
    ProductDatabase customerDB;
    ProductAdapter customAdapter;
    static final String DATABASE_NAME = "login.db";
    public static String DB_PATH; 
    private ArrayList<LevelList> results = new ArrayList<LevelList>();
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.product_list);

        levelLists = new ArrayList<LevelList>();
        customerDB = new ProductDatabase(getApplicationContext());
        customerDB = customerDB.open();
        listCustom = (ListView) findViewById(R.id.listView1);
        mainMenu();
    }

    public void mainMenu()
    {
        results.clear();
        DB_PATH = "/data/data/com.gt.invoicemaker/databases/";
        String myPath = DB_PATH + DATABASE_NAME;
        db = SQLiteDatabase.openDatabase(myPath, null,SQLiteDatabase.OPEN_READONLY);  
          final Cursor c = db.rawQuery("SELECT  ID AS _id, USERID, INAME, IPRICE FROM ITEM, null);
          // Note: Master is the one table in External db. Here we trying to access the records of table from external db. 
         if (c != null ) {
                if  (c.moveToFirst()) {
                    do {
                        LevelList results1 = new LevelList();
                        int _id = c.getInt(c.getColumnIndex("_id"));
                        String userName = c.getString(c.getColumnIndex("INAME"));

                        results1.id = _id;
                        results1.item = userName;
                        results.add(results1);
                    }while (c.moveToNext());
                }
         }
                customAdapter = new ProductAdapter(getApplicationContext(), results);
                listCustom.setAdapter(customAdapter);
    }
  }
}

<强> ProductAdapter.java

public class ProductAdapter extends BaseAdapter {

    private Context mContext;
    private List<LevelList> listItem;

      public ProductAdapter(Context c,List<LevelList> listItem) {
          mContext = c;
          this.listItem = listItem;
      }

      @Override
      public int getCount() {
          // TODO Auto-generated method stub
          return listItem.size();
      }

      @Override
      public Object getItem(int position) {
          // TODO Auto-generated method stub
          return listItem;
      }

      @Override
      public long getItemId(int position) {
          // TODO Auto-generated method stub
          return position;
      }

      @Override
      public View getView(int position, View convertView, ViewGroup parent) {
          // TODO Auto-generated method stub
          LayoutInflater inflater = (LayoutInflater) mContext
              .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

          View rowView=inflater.inflate(R.layout.singleproduct, null,true);

              TextView textView = (TextView) rowView.findViewById(R.id.single_product);
              textView.setText(listItem.get(position).item);
          return rowView;
      }
}

<强> product_list.xml

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

                <ListView
                    android:id="@+id/listView1"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_above="@+id/addnew"
                    android:layout_below="@+id/mainview"
                    android:layout_centerHorizontal="true"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp"
                    android:layout_marginTop="7dp"
                    android:layout_marginBottom="7dp"
                    android:scrollbars="none" >

                </ListView>

    </RelativeLayout>

<强> singleproduct.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/single_product"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:textColor="@android:color/white"
            android:layout_marginLeft="15dp"
            android:text="" />

</LinearLayout>