Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/232.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 用SQLite数据库内容填充可扩展的listview子列表_Android_Database_Sqlite_Listview_Expandable - Fatal编程技术网

Android 用SQLite数据库内容填充可扩展的listview子列表

Android 用SQLite数据库内容填充可扩展的listview子列表,android,database,sqlite,listview,expandable,Android,Database,Sqlite,Listview,Expandable,我想用sqlite数据库内容填充可扩展的listview子列表。 对于标题,我通过MainActivity添加了值。 当我试图运行这段代码时,我在类转换异常“java.lang.ClassCastException不能转换为java.util.Collection”中遇到错误。 我被这件事深深打动了。我已经在这里发布了我的代码,任何帮助都将不胜感激 主要活动: ExpandableListAdapter listAdapter; ExpandableListView expListView;

我想用sqlite数据库内容填充可扩展的listview子列表。 对于标题,我通过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");

     }

}
谢谢

编辑:
正如Arash所说,如果这是一个问题,我如何将CursorAdapter的值添加到列表中并将其添加到我的childView(第1章)。

您试图将
CursorAdapter
强制转换到无效的
集合中:

chapter1.addAll((Collection<? extends String>) new DBAdapter(c1Cursor));

第1章addAll((收集)你能解释一下,它是如何实现的吗?
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
chapter1.addAll((Collection<? extends String>) new DBAdapter(c1Cursor));