如何将ListView项加载并保存到SQLiteDatabase?

时间:2011-01-23 22:31:01

标签: android sqlite listview

我想这样做,以便用户单击按钮打开对话框,用户键入项目名称,然后单击“确定”,项目将添加到ListView。到目前为止,我已经到了将项目添加到ListView的位置,但是没有办法保存数据。我有一个名为DataHelper的帮助器,它创建了SQLiteDatabase,但我无法弄清楚如何将它保存到数据库中。 我需要一个代码示例,因为我没有经验。

这是我的.java:

package com.shoppinglist;

import java.util.ArrayList;

import android.app.Dialog;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

public class ShoppingList extends ListActivity {
    /** Called when the activity is first created. */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        ListView lv = (ListView) findViewById(android.R.id.list);
        final ArrayList<String> items = new ArrayList<String>();
        final ArrayAdapter<String> adapter;
        adapter = new ArrayAdapter<String>(
        this, android.R.layout.simple_list_item_1, items);
        lv.setAdapter(adapter);

        Button button1main = (Button) findViewById(R.id.add);
        button1main.setOnClickListener(new OnClickListener()  {
            @Override
            public void onClick(View v)  {
            final Dialog additem = new Dialog(ShoppingList.this);
            additem.setContentView(R.layout.maindialog);
            final EditText et = (EditText)additem.findViewById(R.id.edittext);
            additem.setTitle("Type your item");
            additem.setCancelable(true);
            et.setHint("Type the name of an item...");

            Button button = (Button) additem.findViewById(R.id.cancel);
            button.setOnClickListener(new OnClickListener()  {
                @Override
                public void onClick(View v)  {
                    additem.dismiss();
                }
            });
            additem.show();

            Button ok = (Button) additem.findViewById(R.id.ok);
            ok.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    items.add(et.getText().toString());
                    adapter.notifyDataSetChanged();
                    additem.dismiss();
                    et.setText("");
                }
            });
       }
        });
    }
}

我的DataHelper类:

package com.shoppinglist;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;

public class DataHelper {

    private static final String DATABASE_NAME = "items.db";
    private static final int DATABASE_VERSION = 1;
    private static final String TABLE_NAME = "table1";

    private Context context;
    private SQLiteDatabase db;

    private SQLiteStatement insertStmt;
    private static final String INSERT = "insert into "
        + TABLE_NAME + "(name) values (?)";

    public DataHelper(Context context) {
        this.context = context;
        OpenHelper openHelper = new OpenHelper(this.context);
        this.db = openHelper.getWritableDatabase();
        this.insertStmt = this.db.compileStatement(INSERT);
        }

        public long insert(String name) {
            this.insertStmt.bindString(1, name);
            return this.insertStmt.executeInsert();
        }

        public void deleteAll() {
            this.db.delete(TABLE_NAME, null, null);
        }

        public List<String> selectAll() {
            List<String> list = new ArrayList<String>();
            Cursor cursor = this.db.query(TABLE_NAME, new String[] { "name" },
                    null, null, null, null, "name desc");
            if (cursor.moveToFirst()) {
                do {
                    list.add(cursor.getString(0));
                } while (cursor.moveToNext());
            }
            if (cursor !=null && !cursor.isClosed()) {
                cursor.close();
            }
            return list;
        }

        private static class OpenHelper extends SQLiteOpenHelper {

            OpenHelper(Context context) {
                super(context, DATABASE_NAME, null, DATABASE_VERSION);
            }

            @Override
              public void onCreate(SQLiteDatabase db) {
                db.execSQL("CREATE TABLE " + TABLE_NAME + " (id INTEGER PRIMARY KEY, name TEXT)");
              }

            @Override
            public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
                Log.w("Example", "Upgrading database, this will drop tables and recreate.");
                db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
                onCreate(db);
            }
        }
}

我的main.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:background="#FF9900"
    android:padding="10dp"
    android:orientation="vertical">
        <Button
            android:id="@+id/add"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Add item..."
            android:layout_gravity="center"/>
        <ListView android:id="@android:id/list"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:background="#FFCC00"/>  
</LinearLayout>

我的maindialog.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:id="@+id/layout_root"
  android:orientation="vertical"
  android:background="#FFFFFF"
  android:minHeight="100dp"
  android:minWidth="300dp">
  <EditText
     android:id="@+id/edittext"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"/>
 <LinearLayout
    android:id="@+id/button_layout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    android:layout_gravity="bottom">
  <Button
    android:id="@+id/ok"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Ok"/>
  <Button
    android:id="@+id/cancel"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Cancel"/>
  </LinearLayout>   
</LinearLayout>

提前致谢!

1 个答案:

答案 0 :(得分:4)

  

如何将ListView项加载并保存到SQLiteDatabase?

这是错误的问题,恕我直言。正确的问题是:

  

如何让ListView反映我的SQLiteDatabase中的内容?

第一步是使用CursorSimpleCursorAdapter,而不是ArrayListArrayAdapter

第二步是在用户添加条目时在insert()上执行SQLiteDatabase,然后requery() Cursor更新ListView

Here is a sample project证明了这一点。 Here is another