我想用sqlite数据库内容填充expandable listview,子列表。 对于Headers,我通过MainActivity添加了值。 当我尝试运行此代码时,我在类转换异常中遇到错误" java.lang.ClassCastException无法转换为java.util.Collection"。 我对此很感兴趣。我在这里发布了我的代码,任何帮助都将不胜感激。
主要活动:
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listChapter;
HashMap<String, List<String>> listSections;
//ArrayList<HashMap<String, String>> listSections;
public DatabaseHelper dbHelper = null;
public DBAdapter adapter = null;
public Cursor c1Cursor = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chapter);
expListView = (ExpandableListView)findViewById(R.id.lvExp);
prepareListData();
listAdapter = new ExpandableListAdapter(this, listChapter, listSections);
expListView.setAdapter(listAdapter);
expListView.setOnGroupClickListener(new OnGroupClickListener(){
@Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
return false;
}
});
expListView.setOnGroupExpandListener(new OnGroupExpandListener(){
@Override
public void onGroupExpand(int groupPosition) {
// TODO Auto-generated method stub
}
});
expListView.setOnGroupCollapseListener(new OnGroupCollapseListener(){
@Override
public void onGroupCollapse(int groupPosition) {
// TODO Auto-generated method stub
}
});
expListView.setOnChildClickListener(new OnChildClickListener(){
@Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), " id "+id, Toast.LENGTH_LONG).show();
return false;
}
});
}
private void prepareListData() {
// TODO Auto-generated method stub
listChapter = new ArrayList<String>();
listSections = new HashMap<String, List<String>>();
//listSections = new ArrayList<HashMap<String, String>>();
listChapter.add("Chapter I");
listChapter.add("Chapter II");
dbHelper = new DatabaseHelper(this);
dbHelper.createDatabase();
dbHelper.openDatabase();
c1Cursor = dbHelper.c1Cursor();
startManagingCursor(c1Cursor);
adapter = new DBAdapter(c1Cursor);
c2Cursor = dbHelper.c2Cursor();
startManagingCursor(c2Cursor);
adapter = new DBAdapter(c2Cursor);
List<String> chapter1 = new ArrayList<String>();
chapter1.addAll((Collection<? extends String>) new DBAdapter(c1Cursor));
//chapter1.addAll((Collection<? extends String>) adapter);
//chapter1.add(object);
//chapter1.addAll((Collection<? extends String>) adapter);
List<String> chapter2 = new ArrayList<String>();
listSections.put(listChapter.get(0), chapter1);
listSections.put(listChapter.get(1), chapter2);
}
class DBAdapter extends CursorAdapter{
DBAdapter(Cursor c){
super(Chapter.this,c);
}
@Override
public void bindView(View row, Context ctxt, Cursor c) {
// TODO Auto-generated method stub
DatabaseHolder holder = (DatabaseHolder)row.getTag();
holder.populateFrom(c, dbHelper);
}
@Override
public View newView(Context ctxt, Cursor c, ViewGroup parent) {
LayoutInflater layoutInflater = getLayoutInflater();
View row = layoutInflater.inflate(R.layout.list_item_chapter, parent, false);
DatabaseHolder holder = new DatabaseHolder(row);
row.setTag(holder);
return(row);
}
}
class DatabaseHolder {
private TextView section_title = null;
DatabaseHolder(View row){
section_title = (TextView)row.findViewById(R.id.lblListItem);
Log.d("check ", "In DB HOLDER ");}
void populateFrom(Cursor c, DatabaseHelper r){
//Log.d("DBHolder ", "Populate from "+r.getName(c));
section_title.setText(r.getName(c));
Log.d("Check ", "In populate from");
}
}
MyAdapter
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context _context;
private List<String> _listChapter;
private HashMap<String, List<String>> _listSections;
public ExpandableListAdapter(Context context, List<String> listChapters,
HashMap<String, List<String>> listSections) {
this._context = context;
this._listChapter = listChapters;
this._listSections = listSections;
}
@Override
public int getGroupCount() {
// TODO Auto-generated method stub
return this._listChapter.size();
}
@Override
public int getChildrenCount(int groupPosition) {
// TODO Auto-generated method stub
return this._listSections.get(this._listChapter.get(groupPosition)).size();
}
@Override
public Object getGroup(int groupPosition) {
// TODO Auto-generated method stub
return this._listChapter.get(groupPosition);
}
@Override
public Object getChild(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return this._listSections.get(this._listChapter.get(groupPosition)).get(childPosition);
}
@Override
public long getGroupId(int groupPosition) {
// TODO Auto-generated method stub
return groupPosition;
}
@Override
public long getChildId(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return childPosition;
}
@Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return false;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
String chapterList = (String)getGroup(groupPosition);
if(convertView == null){
LayoutInflater inflater = (LayoutInflater)this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_group, null);
}
TextView listChapter = (TextView)convertView.findViewById(R.id.lblListHeader);
listChapter.setTypeface(null, Typeface.BOLD);
listChapter.setText(chapterList);
return convertView;
}
@Override
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final String childText = (String)getChild(groupPosition, childPosition);
if(convertView == null){
LayoutInflater inflater = (LayoutInflater)this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item_chapter, null);
}
TextView listChild = (TextView) convertView.findViewById(R.id.lblListItem);
listChild.setText(childText);
return convertView;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return true;
}}
我的DatabaseHelper:
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DB_PATH ="/data/data/com.example.contenttest/databases/";
private static final String DB_NAME = "company.db";
private static final int SCHEMA_VERSION = 1;
public static final String TABLE_NAME = "content";
public static final String COL_ID = "id";
//public static final String rId = "_id";
public static final String COL_SEC_TITLE = "section_topic";
public static final String COL_CONTENT = "content";
public static final String COL_SEC_NO = "section_no";
public SQLiteDatabase dbSqlite;
private final Context myContext;
public DatabaseHelper(Context context){
super(context, DB_NAME, null, SCHEMA_VERSION);
this.myContext = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
public void createDatabase(){
boolean dbExist = DBExists();
if(!dbExist){
this.getReadableDatabase();
copyDBFromResource();
}
}
@SuppressWarnings("deprecation")
private boolean DBExists(){
SQLiteDatabase db = null;
try{
String databasePath = DB_PATH + DB_NAME;
db = SQLiteDatabase.openDatabase(databasePath, null, SQLiteDatabase.OPEN_READWRITE);
db.setLocale(Locale.getDefault());
db.setLockingEnabled(true);
db.setVersion(1);
}catch(SQLiteException e){
Log.e("SQLHelper", "database not found");
}
if(db!=null){
db.close();
}
return db != null ?true:false;
}
private void copyDBFromResource(){
InputStream inputStream = null;
OutputStream outStream = null;
String dbFilePath = DB_PATH + DB_NAME;
try{
inputStream = myContext.getAssets().open(DB_NAME);
outStream = new FileOutputStream(dbFilePath);
byte[] buffer = new byte[1024];
int length;
while((length = inputStream.read(buffer))>0){
outStream.write(buffer, 0 ,length);
}
Log.d("Response", "Copied Successfully");
outStream.flush();
outStream.close();
inputStream.close();
}catch(IOException e){
throw new Error("Problem copying database from resource file.");
}
}
public void openDatabase() throws SQLException{
String myPath = DB_PATH + DB_NAME;
dbSqlite = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}
public synchronized void close(){
if(dbSqlite != null){
dbSqlite.close();
}
super.close();
}
public Cursor getCursor(){
//SELECT id AS _id, section_topic FROM content
Cursor mCursor = dbSqlite.rawQuery("SELECT "+COL_ID+" AS _id "+","+COL_SEC_TITLE+","+COL_CONTENT+" FROM "+TABLE_NAME, null);
if(mCursor!=null){
if(mCursor.moveToFirst()){
do{
Log.d("Sectio Topic ", mCursor.getString(mCursor.getColumnIndex("section_topic")));
}while(mCursor.moveToNext());
}
}
Log.d("Response from database is", "follows "+mCursor);
return mCursor;
}
public String getName(Cursor c){
//Log.d("String values is ", c.getString(3));
String secTitle = c.getString(c.getColumnIndex(COL_SEC_TITLE));
//return (c.getString(3));
return secTitle;
}
public String getContent(Cursor c){
String secContent = c.getString(c.getColumnIndex(COL_CONTENT));
return secContent;
}
public Integer getId(Cursor c){
Integer secId = c.getInt(c.getColumnIndex("_id"));
return secId;
}
public Cursor c1Cursor(){
//select section_topic from content where id<=2
Cursor c1Cursor = dbSqlite.rawQuery("SELECT "+COL_ID+" AS _id "+","+COL_SEC_TITLE+","+COL_CONTENT+" FROM "+TABLE_NAME+" WHERE"+" id <= 2", null);
if(c1Cursor !=null ){
if(c1Cursor.moveToFirst()){
do{
Log.d("Sectio Topic ", c1Cursor.getString(c1Cursor.getColumnIndex("section_topic")));
}while(c1Cursor.moveToNext());
}
}
return c1Cursor;
}
public Cursor c2Cursor(){
Cursor c2Cursor = dbSqlite.rawQuery("SELECT "+COL_ID+" AS _id "+","+COL_SEC_TITLE+","+COL_CONTENT+" FROM "+TABLE_NAME+" WHERE"+" id>2 AND id<10", null);
if(c2Cursor != null){
if(c2Cursor.moveToFirst()){
do{
Log.d("Section Topic ", c2Cursor.getString(c2Cursor.getColumnIndex(COL_SEC_TITLE)));
}while(c2Cursor.moveToNext());
}
}
return c2Cursor;
}}
我的堆栈跟踪:
09-06 07:04:18.761: W/dalvikvm(1495): threadid=1: thread exiting with uncaught exception (group=0xb4aaaba8)
09-06 07:04:18.911: E/AndroidRuntime(1495): FATAL EXCEPTION: main
09-06 07:04:18.911: E/AndroidRuntime(1495): Process: com.example.contenttest, PID: 1495
09-06 07:04:18.911: E/AndroidRuntime(1495): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.contenttest/com.example.contenttest.Chapter}: java.lang.ClassCastException: com.example.contenttest.Chapter$DBAdapter cannot be cast to java.util.Collection
09-06 07:04:18.911: E/AndroidRuntime(1495): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
09-06 07:04:18.911: E/AndroidRuntime(1495): at android.app.ActivityThread.startActivityNow(ActivityThread.java:2035)
09-06 07:04:18.911: E/AndroidRuntime(1495): at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:135)
09-06 07:04:18.911: E/AndroidRuntime(1495): at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:347)
09-06 07:04:18.911: E/AndroidRuntime(1495): at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:749)
09-06 07:04:18.911: E/AndroidRuntime(1495): at android.widget.TabHost.setCurrentTab(TabHost.java:413)
09-06 07:04:18.911: E/AndroidRuntime(1495): at android.widget.TabHost$2.onTabSelectionChanged(TabHost.java:154)
09-06 07:04:18.911: E/AndroidRuntime(1495): at android.widget.TabWidget$TabClickListener.onClick(TabWidget.java:546)
09-06 07:04:18.911: E/AndroidRuntime(1495): at android.view.View.performClick(View.java:4438)
09-06 07:04:18.911: E/AndroidRuntime(1495): at android.view.View$PerformClick.run(View.java:18422)
09-06 07:04:18.911: E/AndroidRuntime(1495): at android.os.Handler.handleCallback(Handler.java:733)
09-06 07:04:18.911: E/AndroidRuntime(1495): at android.os.Handler.dispatchMessage(Handler.java:95)
09-06 07:04:18.911: E/AndroidRuntime(1495): at android.os.Looper.loop(Looper.java:136)
09-06 07:04:18.911: E/AndroidRuntime(1495): at android.app.ActivityThread.main(ActivityThread.java:5017)
09-06 07:04:18.911: E/AndroidRuntime(1495): at java.lang.reflect.Method.invokeNative(Native Method)
09-06 07:04:18.911: E/AndroidRuntime(1495): at java.lang.reflect.Method.invoke(Method.java:515)
09-06 07:04:18.911: E/AndroidRuntime(1495): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
09-06 07:04:18.911: E/AndroidRuntime(1495): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
09-06 07:04:18.911: E/AndroidRuntime(1495): at dalvik.system.NativeStart.main(Native Method)
09-06 07:04:18.911: E/AndroidRuntime(1495): Caused by: java.lang.ClassCastException: com.example.contenttest.Chapter$DBAdapter cannot be cast to java.util.Collection
09-06 07:04:18.911: E/AndroidRuntime(1495): at com.example.contenttest.Chapter.prepareListData(Chapter.java:142)
09-06 07:04:18.911: E/AndroidRuntime(1495): at com.example.contenttest.Chapter.onCreate(Chapter.java:52)
09-06 07:04:18.911: E/AndroidRuntime(1495): at android.app.Activity.performCreate(Activity.java:5231)
09-06 07:04:18.911: E/AndroidRuntime(1495): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
09-06 07:04:18.911: E/AndroidRuntime(1495): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
09-06 07:04:18.911: E/AndroidRuntime(1495): ... 18 more
09-06 07:04:23.461: I/Process(1495): Sending signal. PID: 1495 SIG: 9
谢谢!
修改 正如Arash所说,如果这是问题,我如何将CursorAdapter的值添加到列表并将其添加到我的childView(第1章)。
答案 0 :(得分:0)
您正在尝试将CursorAdapter
投射到无效的Collection
:
chapter1.addAll((Collection<? extends String>) new DBAdapter(c1Cursor));
你必须从你的CursorAdapter获取一个列表,然后将它添加到你的chapter1