自从一周以来我一直在努力从数据库填充android中的listview但是遇到大问题请我很高兴如果有人会帮助这里是ma代码 // databasehelper class
package com.example;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper{
public static final String DBNAME = "company.db";
public static final String ENAME="ename";
public static final String ADD="addr";
public static final String PNO="pno";
public static final String FA="fa";
public static final String tablename="company";
public DatabaseHelper(Context context) {
super(context, DBNAME, null, 1);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE company (_ID INTEGER PRIMARY KEY AUTOINCREMENT,ename TEXT,addr TEXT,pno TEXT,fa TEXT);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP IF TABLE EXISTS company");
onCreate(db);
}
}
//这里是我试图填充listview的类 package com.example;
import java.util.ArrayList;
import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class Text extends ListActivity {
private ArrayList<String> results = new ArrayList<String>();
private String tableName = DatabaseHelper.tablename;
private SQLiteDatabase newDB;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
openAndQueryDatabase();
displayResultList();
}
private void displayResultList() {
// TODO Auto-generated method stub
TextView tView = new TextView(this);
tView.setText("This data is retrieved from the database and only 4 " +
"of the results are displayed");
getListView().addHeaderView(tView);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_2, results));
getListView().setTextFilterEnabled(true);
}
private void openAndQueryDatabase() {
// TODO Auto-generated method stub
try {
DatabaseHelper dbHelper = new DatabaseHelper(this.getApplicationContext());
newDB = dbHelper.getWritableDatabase();
Cursor c = newDB.rawQuery("SELECT ENAME, PNO FROM " +
tableName, null);
if (c != null ) {
if (c.moveToFirst()) {
do {
String ename = c.getString(c.getColumnIndex("ENAME"));
String addr = c.getString(c.getColumnIndex("PNO"));
results.add("Name: " + ename + ",Age: " + addr);
}while (c.moveToNext());
}
}
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
if (newDB != null)
newDB.execSQL("DELETE FROM " + tableName);
newDB.close();
}
}
}
答案 0 :(得分:0)
您不会在数据库中添加任何内容。您没有进行任何insert
调用来填充数据库。因此,当您执行查询时,您将获得一个空光标。因此,results
没有添加任何内容。这就是为什么你的listview是空的。