0

我正在尝试ListMenu从 SQLite 数据库创建一个使用数据来定义每个MenuItem. 所以在一个名为menu.java我的类中定义了数组

String classes [] = {};

它应该包含每个菜单项名称。

在 DBAdapter 类中,我创建了一个函数,以便用户可以将信息插入表中(顺便说一句,这一切都很好)。

public long insertContact(String name, String code, String location, String comments, int days, int start, int end, String type) 
    {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_NAME, name);
        initialValues.put(KEY_CODE, code);
        initialValues.put(KEY_LOCATION, location);
        initialValues.put(KEY_COMMENTS, comments);
        initialValues.put(KEY_DAYS, days);
        initialValues.put(KEY_START, start);
        initialValues.put(KEY_END, end);
        initialValues.put(KEY_TYPE, type);
        return db.insert(DATABASE_TABLE, null, initialValues);
    }

String我需要用插入到 KEY_NAME 中的s 来填充该String数组。有谁知道这是否可能?

非常感谢你们的帮助。

如果我通过 Sam/Mango 实现该功能,程序会崩溃,是我使用不正确还是由于数组大小未知而导致的错误?

DBAdapter db = new DBAdapter(this);
String classes [] = db.getClasses();

编辑:我应该提到,如果我手动定义数组:

String classes [] = {"test1", "test2", "test3", etc};

它工作正常。错误是 NullPointerException

这是 logcat(对格式感到抱歉)。我没有用 db = helper.getReadableDatabase(); 初始化 在 getClasses() 函数中,但不幸的是它没有解决问题。

11-11 22:53:39.117: D/dalvikvm(17856): Late-enabling CheckJNI
11-11 22:53:39.297: D/TextLayoutCache(17856): Using debug level: 0 - Debug Enabled: 0
11-11 22:53:39.337: D/libEGL(17856): loaded /system/lib/egl/libGLES_android.so
11-11 22:53:39.337: D/libEGL(17856): loaded /system/lib/egl/libEGL_adreno200.so
11-11 22:53:39.357: D/libEGL(17856): loaded /system/lib/egl/libGLESv1_CM_adreno200.so
11-11 22:53:39.357: D/libEGL(17856): loaded /system/lib/egl/libGLESv2_adreno200.so
11-11 22:53:39.387: I/Adreno200-EGLSUB(17856): <ConfigWindowMatch:2078>: Format RGBA_8888.
11-11 22:53:39.407: D/memalloc(17856): /dev/pmem: Mapped buffer base:0x5c66d000 size:36593664 offset:32825344 fd:65
11-11 22:53:39.417: E/(17856): Can't open file for reading
11-11 22:53:39.417: E/(17856): Can't open file for reading
11-11 22:53:39.417: D/OpenGLRenderer(17856): Enabling debug mode 0
11-11 22:53:39.477: D/memalloc(17856): /dev/pmem: Mapped buffer base:0x5ecd3000 size:40361984 offset:36593664 fd:68
11-11 22:53:40.507: D/memalloc(17856): /dev/pmem: Mapped buffer base:0x61451000 size:7254016 offset:3485696 fd:71
11-11 22:53:41.077: I/Adreno200-EGLSUB(17856): <ConfigWindowMatch:2078>: Format RGBA_8888.
11-11 22:53:41.077: D/memalloc(17856): /dev/pmem: Mapped buffer base:0x61c4c000 size:7725056 offset:7254016 fd:74
11-11 22:53:41.097: D/memalloc(17856): /dev/pmem: Mapped buffer base:0x623aa000 size:8196096 offset:7725056 fd:80
11-11 22:53:41.937: D/memalloc(17856): /dev/pmem: Mapped buffer base:0x62b7b000 size:8667136 offset:8196096 fd:83
11-11 22:53:41.977: D/memalloc(17856): /dev/pmem: Unmapping buffer base:0x61c4c000 size:7725056 offset:7254016
11-11 22:53:41.977: D/memalloc(17856): /dev/pmem: Unmapping buffer base:0x623aa000 size:8196096 offset:7725056
11-11 22:53:41.977: D/memalloc(17856): /dev/pmem: Unmapping buffer base:0x62b7b000 size:8667136 offset:8196096
11-11 22:53:42.167: I/Adreno200-EGLSUB(17856): <ConfigWindowMatch:2078>: Format RGBA_8888.
11-11 22:53:42.177: D/memalloc(17856): /dev/pmem: Mapped buffer base:0x61c5d000 size:17084416 offset:13316096 fd:74
11-11 22:53:42.317: D/memalloc(17856): /dev/pmem: Mapped buffer base:0x63853000 size:20852736 offset:17084416 fd:80
11-11 22:53:42.357: D/OpenGLRenderer(17856): Flushing caches (mode 0)
11-11 22:53:42.357: D/memalloc(17856): /dev/pmem: Unmapping buffer base:0x5c66d000 size:36593664 offset:32825344
11-11 22:53:42.357: D/memalloc(17856): /dev/pmem: Unmapping buffer base:0x5ecd3000 size:40361984 offset:36593664
11-11 22:53:42.367: D/memalloc(17856): /dev/pmem: Unmapping buffer base:0x61451000 size:7254016 offset:3485696
11-11 22:53:42.757: D/memalloc(17856): /dev/pmem: Mapped buffer base:0x5c56d000 size:24621056 offset:20852736 fd:65
11-11 22:53:44.247: D/AndroidRuntime(17856): Shutting down VM
11-11 22:53:44.247: W/dalvikvm(17856): threadid=1: thread exiting with uncaught exception (group=0x40ac3210)
11-11 22:53:44.257: E/AndroidRuntime(17856): FATAL EXCEPTION: main
11-11 22:53:44.257: E/AndroidRuntime(17856): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{x.x.timetable/x.x.timetable.menu}: java.lang.NullPointerException
11-11 22:53:44.257: E/AndroidRuntime(17856):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1891)
11-11 22:53:44.257: E/AndroidRuntime(17856):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1992)
11-11 22:53:44.257: E/AndroidRuntime(17856):    at android.app.ActivityThread.access$600(ActivityThread.java:127)
11-11 22:53:44.257: E/AndroidRuntime(17856):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1158)
11-11 22:53:44.257: E/AndroidRuntime(17856):    at android.os.Handler.dispatchMessage(Handler.java:99)
11-11 22:53:44.257: E/AndroidRuntime(17856):    at android.os.Looper.loop(Looper.java:137)
11-11 22:53:44.257: E/AndroidRuntime(17856):    at android.app.ActivityThread.main(ActivityThread.java:4441)
11-11 22:53:44.257: E/AndroidRuntime(17856):    at java.lang.reflect.Method.invokeNative(Native Method)
11-11 22:53:44.257: E/AndroidRuntime(17856):    at java.lang.reflect.Method.invoke(Method.java:511)
11-11 22:53:44.257: E/AndroidRuntime(17856):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:823)
11-11 22:53:44.257: E/AndroidRuntime(17856):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:590)
11-11 22:53:44.257: E/AndroidRuntime(17856):    at dalvik.system.NativeStart.main(Native Method)
11-11 22:53:44.257: E/AndroidRuntime(17856): Caused by: java.lang.NullPointerException
11-11 22:53:44.257: E/AndroidRuntime(17856):    at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:221)
11-11 22:53:44.257: E/AndroidRuntime(17856):    at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:157)
11-11 22:53:44.257: E/AndroidRuntime(17856):    at x.x.timetable.DBAdapter.getClasses(DBAdapter.java:151)
11-11 22:53:44.257: E/AndroidRuntime(17856):    at x.x.timetable.menu.<init>(menu.java:15)
11-11 22:53:44.257: E/AndroidRuntime(17856):    at java.lang.Class.newInstanceImpl(Native Method)
11-11 22:53:44.257: E/AndroidRuntime(17856):    at java.lang.Class.newInstance(Class.java:1319)
11-11 22:53:44.257: E/AndroidRuntime(17856):    at android.app.Instrumentation.newActivity(Instrumentation.java:1023)
11-11 22:53:44.257: E/AndroidRuntime(17856):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1882)
11-11 22:53:44.257: E/AndroidRuntime(17856):    ... 11 more
11-11 22:53:46.527: I/Process(17856): Sending signal. PID: 17856 SIG: 9



package x.x.timetable;

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

public class DBAdapter {
    static final String KEY_ROWID = "_id";
    static final String KEY_NAME = "name";
    static final String KEY_CODE = "code";
    static final String KEY_LOCATION = "location";
    static final String KEY_COMMENTS = "comments";
    static final String KEY_DAYS = "days";
    static final String KEY_START = "start";
    static final String KEY_END = "end";
    static final String KEY_TYPE = "type";


    static final String TAG = "DBAdapter";

    static final String DATABASE_NAME = "MyDB";
    static final String DATABASE_TABLE = "timetable";
    static final int DATABASE_VERSION = 2;

    static final String DATABASE_CREATE =
        "create table timetable (_id integer primary key autoincrement, "
        + "name text not null, code text not null, location text not null, comments text not null, days INTEGER not null, start INTEGER not null, end INTEGER not null, type text not null);";

    final Context context;

    DatabaseHelper DBHelper;
    SQLiteDatabase db;

    public DBAdapter(Context ctx)
    {
        this.context = ctx;
        DBHelper = new DatabaseHelper(context);
    }

    private static class DatabaseHelper extends SQLiteOpenHelper
    {
        DatabaseHelper(Context context)
        {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db)
        {
            try {
                db.execSQL(DATABASE_CREATE);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
        {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS timetable");
            db.execSQL("DROP TABLE IF EXISTS contacts");
            onCreate(db);
        }
    }

    //---opens the database---
    public DBAdapter open() throws SQLException 
    {
        db = DBHelper.getWritableDatabase();
        return this;
    }

    //---closes the database---
    public void close() 
    {
        DBHelper.close();
    }

    public int count(){
        db = DBHelper.getWritableDatabase();
        String count = "SELECT count(*) FROM table";
        Cursor mcursor = db.rawQuery(count, null);
        int icount = mcursor.getInt(0);
        return icount;
    }

    //---insert a contact into the database---
    public long insertContact(String name, String code, String location, String comments, int days, int start, int end, String type) 
    {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_NAME, name);
        initialValues.put(KEY_CODE, code);
        initialValues.put(KEY_LOCATION, location);
        initialValues.put(KEY_COMMENTS, comments);
        initialValues.put(KEY_DAYS, days);
        initialValues.put(KEY_START, start);
        initialValues.put(KEY_END, end);
        initialValues.put(KEY_TYPE, type);
        return db.insert(DATABASE_TABLE, null, initialValues);
    }

    //---deletes a particular contact---
    public boolean deleteContact(long rowId) 
    {
        return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
    }

    //---retrieves all the Timetable---
    public Cursor getAllTimetable()
    {
        return db.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NAME,
                KEY_CODE, KEY_LOCATION, KEY_COMMENTS, KEY_DAYS, KEY_START, KEY_END, KEY_TYPE}, null, null, null, null, null);
    }

    //---retrieves a particular contact---
    public Cursor getContact(long rowId) throws SQLException 
    {
        Cursor mCursor =
                db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
                KEY_NAME, KEY_CODE, KEY_LOCATION, KEY_COMMENTS, KEY_DAYS, KEY_START, KEY_END, KEY_TYPE}, KEY_ROWID + "=" + rowId, null,
                null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;
    }

    //---updates a contact---
    public boolean updateContact(long rowId, String name, String code, String location, String comments, int days, int start, int end, String type) 
    {
        ContentValues args = new ContentValues();
        args.put(KEY_NAME, name);
        args.put(KEY_CODE, code);
        args.put(KEY_LOCATION, location);
        args.put(KEY_COMMENTS, comments);
        args.put(KEY_DAYS, days);
        args.put(KEY_START, start);
        args.put(KEY_END, end);
        args.put(KEY_TYPE, type);
        return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
    }

    public String[] getClasses() {

        db = DBHelper.getWritableDatabase();
        String[] columns = {KEY_NAME};
        Cursor c = db.query(DATABASE_TABLE, columns, null, null, null, null, null);
        String[] classes = new String [c.getCount()];
        int i = 0;
        while (c.moveToNext()) {
            classes[i] = c.getString(0);
            i++;
        }
        c.close();
        return classes; 
    }
}
4

3 回答 3

1

你正在寻找

ArrayList<String> list= new ArrayList<String>();
list.add(name);

当您不知道需要在数据结构中添加的长度或多少元素时,在许多情况下(不是全部)不应该使用数组。请改用 ArrayList。从列表中获取名称

list.get(ELEMENT_AT);

如果您必须需要一个数组,请先填充 List,然后用于List.toArray();取回一个数组。

于 2012-11-11T21:04:20.280 回答
1

绝对有可能。你可以在你的数据库类中创建一个方法,在字符串数组中返回你的值。

public String[] getClasses() {
    String[] columns = {KEY_NAME};
    Cursor c = db.query(DATABASE_TABLE, columns, null, null, null, null, null);
    String[] classes = new String [c.getCount()];
    int i = 0;
    while (c.moveToNext()) {
        classes[i] = c.getString(0);
        i++;
    }
    c.close();
    return classes; 
}
于 2012-11-11T21:06:15.253 回答
1

根据我们在评论中的讨论,我假设您想在以下位置执行类似的操作onCreate()

public class menu extends ListActivity{
    DBAdapter db;
    String[] classes; // = {"test", "test11", "test1", "test2", "test3",};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        db = new DBAdapter(this);
        db.open();
        classes = db.getClasses();
        setListAdapter(new ArrayAdapter<String>(menu.this, android.R.layout.simple_list_item_1, classes));
    } 

这显然是使用了我帮助芒果写的方法。

于 2012-11-11T22:44:25.663 回答