我正在使用 SQLiteHelper 将数据存储在数据库中,数据已正确存储(使用 SQLite 查看器打开),但是当我必须从数据库中获取数据时,我的代码总是返回空值
public class HistorySQLiteHelper extends SQLiteOpenHelper{
String sqlCreate = "CREATE TABLE History (artist TEXT, title TEXT, link TEXT)";
public HistorySQLiteHelper(Context context, String nombre, CursorFactory factory, int version){
super(context, nombre, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db){
db.execSQL(sqlCreate);
}
@Override
public void onUpgrade(SQLiteDatabase db, int versionAnterior, int versioNueva){
db.execSQL("DROP TABLE IF EXISTS History");
db.execSQL(sqlCreate);
}
}
这是我用来检索数据的代码
String[] fields = new String[] {"artist", "title", "link"};
HistorySQLiteHelper hdbh = new HistorySQLiteHelper(HistoryActivity.this, "DBHistory", null, 1);
SQLiteDatabase db = hdbh.getReadableDatabase();
Cursor c = db.query("History", fields, "artist=?", new String[]{String.valueOf(0)}, null, null, null);
int counter = 0;
artist = new String[30];
title = new String[30];
links = new String[30];
if (c.moveToFirst()) {
do {
artist[counter] = c.getString(0);
title[counter] = c.getString(1);
links[counter] = c.getString(2);
counter++;
} while (c.moveToNext());
}
db.close();
if (artist.length < 1){
String[] strings = nee Stting[]{" No results. "};
adaptador = new ArrayAdapter<String>(HistoryActivity.this, android.R.layout.simple_list_item_1, strings);
list.setAdapter(adaptador);
}else{
AdaptadorTitulares adapter = new AdaptadorTitulares(HistoryActivity.this);
list.setAdapter(adapter);
}
list.setClickable(true);
}
}
和 ArrayAdapter 类:
class AdaptadorTitulares extends ArrayAdapter {
Activity context;
@SuppressWarnings("unchecked")
AdaptadorTitulares(Activity context) {
super(context, R.layout.listitem_titular, artist);
this.context = context;
}
public View getView(int position, View convertView, ViewGroup parent)
{
View item = convertView;
ViewHolder holder;
if(item == null)
{
LayoutInflater inflater = context.getLayoutInflater();
item = inflater.inflate(R.layout.listitem_titular, null);
holder = new ViewHolder();
holder.titulo = (TextView)item.findViewById(R.id.LblTitulo);
item.setTag(holder);
}
else
{
holder = (ViewHolder)item.getTag();
}
holder.titulo.setText(artist[position]);
return(item);
}
}
static class ViewHolder {
TextView titulo;
}
为什么我的代码给出空值以及如何解决它?
PD:这里是变量字段和 onCreate 方法
public class HistoryActivity extends Activity{
private ListView list;
private String[] artist;
private String[] title;
private String[] links;
private ArrayAdapter<String> adaptador;
@Override
public void onCreate(Bundle state) {
super.onCreate(state);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_history);
list = (ListView)findViewById(R.id.history_list);
new LoadTask().execute(); //this is where I put the code to retrieve data
} //////////////////////////////// onCreate END