1

データベースから ListView にデータを取得したいのですが、できません。対応する activity_view_list.xml レイアウトの Java ファイルの名前は ViewList.java です。その場合は親切に助けてください。以下は私のコードです

DBHelper.java

package com.example.shoppinglist;

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

public class DBHelper extends SQLiteOpenHelper
{

    private static final String DATABASE_NAME = "ShoppingDatabase";
    private static final int DATABASE_VERSION = 1;
    private static final String DATBASE_CREATE = "CREATE TABLE ShoppingList(Id integer primary key autoincrement not null," +
            "List_name varchar(255) default null,List_status varchar(255) default 'OPEN'," +
            "date datetime)";
    public DBHelper(Context context, String name, CursorFactory factory,
            int version) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        // TODO Auto-generated constructor stub

    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        db.execSQL(DATBASE_CREATE);

    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        Log.w(DBHelper.class.getName(), 
                "Upgrading database from version " + oldVersion + " to "
    + newVersion + ", which will delete the old data.");
    db.execSQL("DROP TABLE IF EXISTS ShoppingList");
    //Method is called during creation of new database
    onCreate(db);
    } 
}

DBAdpater.java

package com.example.shoppinglist;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class DBAdapter 
{
    private Context ctxt;
    private SQLiteDatabase db;
    private DBHelper dbHelper;
    public static final String KEY_ROWID = "Id";
    public static final String KEY_NAME = "List_name";
    public static final String KEY_STATUS = "List_status";
    public static final String KEY_DATE = "date";
    //public static final String KEY_TOTAL_ITEMS = "Total_items";
    private static final String DATABASE_TABLE = "ShoppingList";

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

    //Open database
    public DBAdapter open() throws SQLException
    {
        dbHelper = new DBHelper(ctxt, null, null, 0);
        db = dbHelper.getWritableDatabase();
        return this;
    }

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

    //Create a new item
    public long insertItem(String list_name , String list_status, String date)
    {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_NAME, list_name );
        initialValues.put(KEY_STATUS, list_status);
        initialValues.put(KEY_DATE, date);
        return db.insert(DATABASE_TABLE, null, initialValues);
    }

    //update a item
    /*public boolean updateItem(long rowId, String list_name, 
        String list_status, String date)
    {
        ContentValues updateValues = new ContentValues();
        updateValues.put(KEY_NAME, list_name);
        updateValues.put(KEY_STATUS, list_status);
        updateValues.put(KEY_DATE, 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_NAME, 
                                KEY_STATUS, KEY_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_NAME, KEY_STATUS,
        KEY_DATE}, KEY_ROWID + "=" + rowId, null, null, null, null, null);
        if(mCursor != null){
            mCursor.moveToFirst();
        }
        return mCursor;
    }   
}

activity_view_list.xml

<RelativeLayout 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"
    tools:context=".ViewList" >

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" >
    </ListView>

</RelativeLayout>

ViewList.java

package com.example.shoppinglist;
import android.os.Build;
import android.os.Bundle;
import android.annotation.TargetApi;
import android.app.ListActivity;
import android.database.Cursor;
import android.view.Menu;
import android.view.TextureView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;


public class ViewList extends ListActivity {

    private DBAdapter dbadpater;
    protected ListAdapter adapter;
    @SuppressWarnings("deprecation")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_list);
        ListView listview = (ListView)findViewById(R.id.listView1);
        dbadpater = new DBAdapter(ViewList.this);
        dbadpater.open();
        Cursor values = dbadpater.fetchAllItems();
        adapter = new SimpleCursorAdapter(this, R.layout.list_example, values, new String[] {"Id","List_name"}, new int [] {R.id.txtid,R.id.txtname});
        setListAdapter(adapter);
        listview.setOnItemClickListener(new OnItemClickListener() {

            @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                    long id) {
                // TODO Auto-generated method stub
                Toast.makeText(getApplicationContext(), ((TextureView)view).getTextAlignment(),Toast.LENGTH_LONG).show();
            }
        });
        dbadpater.close();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_view_list, menu);
        return true;
    }

}
4

3 に答える 3

0

ローダーのチュートリアルを読み、を使用しSimpleCursorAdapterてリストにデータを入力しますLoaders。それは非常に簡単で効率的です。ローダーは、自身の開閉とリフレッシュを処理Cursorします。

于 2013-02-15T05:23:17.823 に答える
0

アダプターをリストビューに設定するのを忘れています。以下のようにしてみてください:

listView.setAdapter(adapter);
于 2013-02-15T05:32:51.163 に答える
0

を使用してカーソルオブジェクトからデータを取得します

if (cursor.moveToFirst()) {
        do {
        // looping through all rows and here we adding to list
        } while (cursor.moveToNext());
    }
于 2013-02-15T10:20:44.360 に答える