我有一些数据存储在sqlite数据库的不同表中。例如,我从表名main_category获取Tutorial标题,从表教程获得教程描述,我想在expandable listview中显示它们。但我得到nullpointer异常。 这是我从sqlite数据库获取值的代码。
public List<String> getTutNames() {
List<String> list = new ArrayList<>();
Cursor cursor = database.rawQuery("Select cat_name From main_category;", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
list.add(cursor.getString(0));
cursor.moveToNext();
}
cursor.close();
return list;
}
public List<String> getTutDes() {
List<String> list = new ArrayList<>();
Cursor cursor = database.rawQuery("Select tut_detail From tutorials;", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
list.add(cursor.getString(0));
cursor.moveToNext();
}
cursor.close();
return list;
}
这是我将其放入可扩展列表视图中的代码。
public class Main2Activity extends AppCompatActivity {
ExpandableListAdapter listAdapter;
ExpandableListView elv;
List<String> listDataHeader;
List<String> listChild;
HashMap<String, List<String>> listDataChild;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
elv = (ExpandableListView) findViewById(R.id.elv);
DatabaseAccess db = DatabaseAccess.getInstance(this);
db.open();
listDataHeader = db.getTutNames();
listChild = db.getTutDes();
db.close();
for (int i=0; i<listDataHeader.size();i++) {
listDataChild.put(listDataHeader.get(i), listChild);
}
listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);
elv.setAdapter(listAdapter);
}
}
答案 0 :(得分:0)
试试这个!可能有帮助
在检索数据时检查logcat。
public List<String> getTutNames() {
List<String> list = new ArrayList<>();
Cursor cursor = database.rawQuery("Select cat_name From main_category;", null);
if(cursor.getCount() > 0){
while (cursor.moveToNext()){
list.add(cursor.getString(0));
}
}
cursor.moveToFirst();
return list;
}
public List<String> getTutDes() {
List<String> list = new ArrayList<>();
Cursor cursor = database.rawQuery("Select tut_detail From tutorials;", null);
if(cursor.getCount() > 0) {
while (cursor.moveToNext()) {
list.add(cursor.getString(0));
}
}
return list;
}
答案 1 :(得分:0)
也许您的查询数据库需要一些时间。您可以在使用时添加synchronized to method和check list null。