gpt4 book ai didi

database - 帮助 ListView 数据库

转载 作者:行者123 更新时间:2023-11-30 04:52:52 26 4
gpt4 key购买 nike

我在运行此代码时遇到问题:App Force Closing..

短跑运动员.Java

import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.ListAdapter;
import android.widget.SimpleCursorAdapter;

public class Sprinter extends ListActivity {
/** Called when the activity is first created. */
final static String MY_DB_NAME = "Sprinter";
final static String MY_DB_TABLE = "Stations";

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

SQLiteDatabase myDB = null;
try {
myDB = this.openOrCreateDatabase(MY_DB_NAME, MODE_PRIVATE, null);

myDB.execSQL("CREATE TABLE IF NOT EXISTS " + MY_DB_TABLE + "_id integer primary key autoincrement, name varchar(100);");

myDB.execSQL("INSERT INTO " + MY_DB_TABLE + " (_id, name)" + " VALUES ('', 'Oceanside Transit Center');");

myDB.execSQL("INSERT INTO " + MY_DB_TABLE + " (_id, name)" + " VALUES ('', 'Coast Highway');");

Cursor mCursor = myDB.rawQuery("SELECT name" + " FROM " + MY_DB_TABLE, null);

startManagingCursor(mCursor);

ListAdapter adapter = new SimpleCursorAdapter(this, R.layout.list_item, mCursor, new String[] { "name" }, new int[] { R.id.Name });

this.setListAdapter(adapter);

this.getListView().setTextFilterEnabled(true);
} finally {
if (myDB != null) {
myDB.close();
}
}
}
}

主.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ListView
android:id="@id/android:list"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</ListView>

<TextView
android:id="@id/android:empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="No Data"
/>
</LinearLayout>

list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/LinearLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">

<TextView android:id="@+id/Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
</LinearLayout>

最佳答案

对于 SimpleCursorAdapter,您还需要选择一个名为 _id 的主 ID。你只需要在你的光标中使用它,你不必将它用于任何事情。

Cursor mCursor = myDB.rawQuery("SELECT _id, name" + " FROM " + MY_DB_TABLE, null);

关于database - 帮助 ListView 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2587071/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com