在listView中显示来自SQLiteDatabase的数据

时间:2016-10-11 12:44:19

标签: android sqlite listview

我当前可以在普通的TextView中显示数据库中的数据。但我现在想在listview中显示数据库中的行,我试图用光标做这个,我似乎无法弄明白。

public class MyDBHandler extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "ekonomi.db";

    public static final String TABLE_UTGIFTER = "utgifter";
    public static final String COLUMN_ID = "_id";
    public static final String COLUMN_TITEL = "_titel";
    public static final String COLUMN_KATEGORI = "_kategori";
    public static final String COLUMN_PRIS = "_pris";
    public static final String COLUMN_DATUM = "_datum";

    public MyDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, DATABASE_NAME, factory, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String query = "CREATE TABLE " + TABLE_UTGIFTER + "(" +
                COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                COLUMN_TITEL + " TEXT, " +
                COLUMN_KATEGORI + " TEXT, " +
                COLUMN_PRIS + " INTEGER, " +
                COLUMN_DATUM + " TEXT" +
                ");";
        db.execSQL(query);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS");
        onCreate(db);
    }

    public void addUtgifter(Utgift utgift){
        SQLiteDatabase db = getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(COLUMN_TITEL, utgift.get_titel());
        values.put(COLUMN_KATEGORI, utgift.get_kategori());
        values.put(COLUMN_PRIS, utgift.get_pris());
        values.put(COLUMN_DATUM, utgift.get_datum());
        db.insert(TABLE_UTGIFTER, null, values);
        db.close();
    }

    public String databaseToString() {
        String dbString = "";
        SQLiteDatabase db = getWritableDatabase();
        String query = "SELECT * FROM " + TABLE_UTGIFTER + " WHERE 1";

        Cursor c = db.rawQuery(query, null);
        c.moveToFirst();

        while (!c.isAfterLast()) {
            if (c.getString(c.getColumnIndex("_titel")) != null) {
                dbString += c.getString(c.getColumnIndex("_titel"));
                dbString += ", ";
//                dbString += "\n";
            }if(c.getString(c.getColumnIndex("_kategori"))!=null){
                dbString += c.getString(c.getColumnIndex("_kategori"));
                dbString += ", ";
            }
            if(c.getString(c.getColumnIndex("_pris"))!=null){
                dbString += c.getString(c.getColumnIndex("_pris"));
                dbString += ", ";
            }
            if(c.getString(c.getColumnIndex("_datum"))!=null){
                dbString += c.getString(c.getColumnIndex("_datum"));
                dbString += "\n";
            }
            c.moveToNext();
        }

        db.close();
        return dbString;
    }
}


public class VisaUtgiftFragment extends Fragment {
    private MainActivity ui;
    private TextView tvDatabase;
    private MyDBHandler dbHandler;
    private ListView lvUtgift;



    public VisaUtgiftFragment() {
        // Required empty public constructor
    }

    public void setActivity(MainActivity ui){
        this.ui = ui;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_visa_utgift, container, false);
        tvDatabase = (TextView)view.findViewById(R.id.tvDatabaseTest);
        dbHandler = new MyDBHandler(getActivity(), null, null, 1);
        tvDatabase.setText(dbHandler.databaseToString());
        lvUtgift = (ListView)view.findViewById(R.id.lvUtgift);
        lvUtgift.setAdapter(new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1, [the rows in the database]));
        lvUtgift.setOnItemClickListener(new ListViewClicked());

        return view;
    }

    private class ListViewClicked implements android.widget.AdapterView.OnItemClickListener {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        }
    }
}

2 个答案:

答案 0 :(得分:0)

您可以使用类似sample code in this guide here

的内容

该示例使用的CursorLoader可以理想地与ContentProvider一起使用,但您可以仅使用SimpleCursorAdapter在您的查询中传递光标而不使用CursorLoader 。它将自己在ListView中显示光标的内容。

您的代码如下:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_visa_utgift, container, false);

    tvDatabase = (TextView)view.findViewById(R.id.tvDatabaseTest);
    dbHandler = new MyDBHandler(getActivity(), null, null, 1);
    tvDatabase.setText(dbHandler.databaseToString());

    lvUtgift = (ListView)view.findViewById(R.id.lvUtgift);
    lvUtgift.setAdapter(new SimpleCursorAdapter(getActivity(),
            android.R.layout.simple_list_item_1,
            dbHandler().getAllItemsInCursor(),
            new String[]{"_titel"},
            new int[]{android.R.id.text1},
            0));
    lvUtgift.setOnItemClickListener(new ListViewClicked());

    return view;
}

您还需要在MyDBHandler课程中添加以下方法:

public Cursor getAllItemsInCursor() {
    return getWritableDatabase()
            .rawQuery("SELECT * FROM " + TABLE_UTGIFTER, null);
}

android.R.layout.simple_list_item_1是预定义布局的资源ID,其中只有一个TextView,资源ID为android.R.id.text1

您可以将android.R.layout.simple_list_item_1替换为您自己可能包含更多TextView的布局,以便能够显示表格中的所有详细信息。您自己的布局可能如下所示:

res/layout目录中的utgifter_item.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/item_id"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/item_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/item_category"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/item_price"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/item_datum"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

SimpleCursorAdapter的构造函数的调用将更改为:

lvUtgift.setAdapter(new SimpleCursorAdapter(getActivity(),
            R.layout.utgifter_item,
            dbHandler().getAllItemsInCursor(),
            new String[]{"_id", "_titel", "_kategori", "_pris", "_datum"},
            new int[]{R.id.item_id, R.id.item_title, R.id.item_category, R.id.item_price, R.id.item_datum},
            0));

答案 1 :(得分:0)

你到底是什么问题? ArrayAdapter cosntructor将List作为第三个参数,因此您必须获取表示db行的List,而不是通过databaseToString()方法获得的一个String。更改您的方法以返回List并将其作为ArrayAdapter构造函数

传递
new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1, yourListOfStrings);