1

我一直在尝试以不同的方式填充我的列表视图。我的数据库类已经定义了一个返回游标的函数。我想知道我的方式是否可行?截至目前,当我尝试访问 ListView 时,我的应用程序崩溃了。这是代码:

public class ProjectExplorer extends ListActivity {

private projectdatabase database;
protected Cursor cursor;
protected ListAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //setContentView(R.layout.activity_project_explorer);

    openDatabase();
}

private void openDatabase() {

    database.open();
    cursor = database.getDataforDisplay();
    adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cursor, null, null, 0);
    setListAdapter(adapter);

}

@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_project_explorer, menu);
    return true;
}     }

返回游标的方法的代码:

public Cursor getDataforDisplay () {        

    String[] columns = new String[] {KEY_ROWID, PROJECT_NAME, PROJECT_FINISH_DATE, PROJECT_DIFFICULTY, PROJECT_STATUS};
    Cursor c = projectDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);


    return c;

}

根据要求,完成数据库类代码:

public class projectdatabase {

public static final String KEY_ROWID = "_id";
public static final String PROJECT_NAME = "project_name";
public static final String PROJECT_ID = "project_id";
public static final String PROJECT_DIFFICULTY = "project_difficulty";
public static final String PROJECT_STATUS = "project_status";
public static final String PROJECT_START_DATE = "project_start_date";
public static final String PROJECT_FINISH_DATE = "project_finsish_date";

private static final String DATABASE_NAME = "project_db";
static final String DATABASE_TABLE = "project_details";
private static final int DATABASE_VERSION = 1;

private DbHelper ourHelper;
private final Context projectdbContext;
private SQLiteDatabase projectDatabase;

private static class DbHelper extends SQLiteOpenHelper {
    public DbHelper(Context context) {

        super(context, DATABASE_NAME, null, DATABASE_VERSION);

    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub

        db.execSQL("CREATE TABLE "+ DATABASE_TABLE + " (" +
                KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                PROJECT_NAME + " TEXT NOT NULL, " +
                PROJECT_ID + " INTEGER, " +
                PROJECT_START_DATE + " TEXT, " +
                PROJECT_FINISH_DATE + " TEXT, " +
                PROJECT_DIFFICULTY + " TEXT, " +
                PROJECT_STATUS + " TEXT);"
               ); 

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub

        db.execSQL("DROP TABLE IF EXIST " + DATABASE_NAME);
        onCreate(db);

    }
}

public projectdatabase (Context c) {                            
     projectdbContext = c;
}

public projectdatabase open() {                                                 //Open database
    ourHelper = new DbHelper(projectdbContext);
    projectDatabase = ourHelper.getWritableDatabase();
    return this;
}

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

public long createEntry(String name, String pid, String startdate, String finishdate, String difficulty) {          //Enter project data into database

    ContentValues cv = new ContentValues();
    cv.put(PROJECT_NAME, name);
    cv.put(PROJECT_ID, pid);
    cv.put(PROJECT_START_DATE, startdate);
    cv.put(PROJECT_FINISH_DATE, finishdate);
    cv.put(PROJECT_DIFFICULTY, difficulty);

    return projectDatabase.insert(DATABASE_TABLE, null, cv);
}

public String getData() {                                                       //Retrieve all project data

    String[] columns = new String[] {KEY_ROWID, PROJECT_NAME, PROJECT_ID, PROJECT_START_DATE, PROJECT_FINISH_DATE, PROJECT_DIFFICULTY, PROJECT_STATUS};
    Cursor c = projectDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
    String result = "";

    int iRow = c.getColumnIndex(KEY_ROWID);
    int iName = c.getColumnIndex(PROJECT_NAME);
    int iID = c.getColumnIndex(PROJECT_ID);
    int iStartDate = c.getColumnIndex(PROJECT_START_DATE);
    int iFinishDate = c.getColumnIndex(PROJECT_FINISH_DATE);
    int iDifficulty = c.getColumnIndex(PROJECT_DIFFICULTY);
    int iStatus = c.getColumnIndex(PROJECT_STATUS);

    for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {

        result = result + c.getString(iRow) + "|" + c.getString(iName) + "|" + c.getString(iID) + "|" + c.getString(iStartDate) + "|" + c.getString(iFinishDate) + "|" + c.getString(iDifficulty) + "|" + c.getString(iStatus) + "\n";

    }

    return result;
}

public Cursor getDataforDisplay () {        //Display selected data for 'User profile' *Incomplete*

    String[] columns = new String[] {KEY_ROWID, PROJECT_NAME, PROJECT_FINISH_DATE, PROJECT_DIFFICULTY, PROJECT_STATUS};
    Cursor c = projectDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);

    c.moveToFirst();
    return c;

}

}

日志猫:

当我在 AVD 中运行项目时出现此错误:

12-29 00:35:14.333: E/dalvikvm(4804): Unable to open stack trace file '/data/anr/traces.txt': Permission denied

然后,当我打开应该显示 ListView 但应用程序崩溃的活动时:

12-29 00:38:04.245: E/AndroidRuntime(4804): FATAL EXCEPTION: main
12-29 00:38:04.245: E/AndroidRuntime(4804): java.lang.RuntimeException: Unable to start      
activity ComponentInfo{com.kk.project/com.kk.project.ProjectExplorer}:     
java.lang.IllegalArgumentException: column 'name' does not exist
12-29 00:38:04.245: E/AndroidRuntime(4804):     at     
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
12-29 00:38:04.245: E/AndroidRuntime(4804):     at  
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
12-29 00:38:04.245: E/AndroidRuntime(4804):     at  
android.app.ActivityThread.access$600(ActivityThread.java:123)
12-29 00:38:04.245: E/AndroidRuntime(4804):     at 
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
12-29 00:38:04.245: E/AndroidRuntime(4804):     at 
android.os.Handler.dispatchMessage(Handler.java:99)
12-29 00:38:04.245: E/AndroidRuntime(4804):     at 
android.os.Looper.loop(Looper.java:137)
12-29 00:38:04.245: E/AndroidRuntime(4804):     at   
android.app.ActivityThread.main(ActivityThread.java:4424)
12-29 00:38:04.245: E/AndroidRuntime(4804):     at  
java.lang.reflect.Method.invokeNative(Native Method)
12-29 00:38:04.245: E/AndroidRuntime(4804):     at  
java.lang.reflect.Method.invoke(Method.java:511)
12-29 00:38:04.245: E/AndroidRuntime(4804):     at  
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
12-29 00:38:04.245: E/AndroidRuntime(4804):     at  
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
12-29 00:38:04.245: E/AndroidRuntime(4804):     at  
dalvik.system.NativeStart.main(Native Method)
12-29 00:38:04.245: E/AndroidRuntime(4804): Caused by: 
java.lang.IllegalArgumentException: column 'name' does not exist
12-29 00:38:04.245: E/AndroidRuntime(4804):     at  
android.database.AbstractCursor.getColumnIndexOrThrow(AbstractCursor.java:267)
12-29 00:38:04.245: E/AndroidRuntime(4804):     at 
android.support.v4.widget.SimpleCursorAdapter.findColumns(SimpleCursorAdapter.java:317)
12-29 00:38:04.245: E/AndroidRuntime(4804):     at 
android.support.v4.widget.SimpleCursorAdapter.<init>(SimpleCursorAdapter.java:92)
12-29 00:38:04.245: E/AndroidRuntime(4804):     at   
com.kk.project.ProjectExplorer.openDatabase(ProjectExplorer.java:29)
12-29 00:38:04.245: E/AndroidRuntime(4804):     at   
com.kk.project.ProjectExplorer.onCreate(ProjectExplorer.java:21)
12-29 00:38:04.245: E/AndroidRuntime(4804):     at  
android.app.Activity.performCreate(Activity.java:4465)
12-29 00:38:04.245: E/AndroidRuntime(4804):     at  
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
12-29 00:38:04.245: E/AndroidRuntime(4804):     at  
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
12-29 00:38:04.245: E/AndroidRuntime(4804):     ... 11 more
4

3 回答 3

1

您需要在尝试使用数据库之前对其进行初始化。

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //setContentView(R.layout.activity_project_explorer);
    database=new projectdatabase(ProjectExplorer.this);
    openDatabase();
} 

编辑 :

adapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, cursor, new String[] { "project_name" }, new int[] { android.R.id.text1 }, 0);
于 2012-12-28T18:56:53.843 回答
1

是的,它是正确的方式,但你错过了一件事。您需要将列从光标映射到正确的 UI 字段,如下所示:

SimpleCursorAdapter scaCity = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, cursor, new String[] { "name" }, new int[] { android.R.id.text1 }, 0);

同样在返回光标之前的函数 getDataForDisplay() 中,调用:

c.moveToFirst();
于 2012-12-28T18:57:54.977 回答
1

您是否考虑过使用装载机?它们专门设计用于显示数据库中的数据并填充列表。做了很多很棒的事情,比如显示第一个结果,而其余的仍然从 DB 中返回,等等。

http://developer.android.com/guide/components/loaders.html

可能不是您问题的直接答案,但非常值得考虑。祝你好运。

于 2012-12-28T19:18:40.503 回答