Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/226.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_Sql_Database_Sqlite_Listview - Fatal编程技术网

Android 将现有SQLite数据库中的数据显示到Listview

Android 将现有SQLite数据库中的数据显示到Listview,android,sql,database,sqlite,listview,Android,Sql,Database,Sqlite,Listview,我是新的android编程,所以请帮助我… 我已经使用sqlite数据库浏览器创建了mydatabase.sqlite数据库文件,并将其复制到android应用程序中的assets文件夹中,以便从数据库文件中检索数据 我想在单击按钮时显示数据库表中的所有记录,并在列表视图中显示结果 这是密码 这是我的databasehelper类 public class DataBaseHelper extends SQLiteOpenHelper { private static String TAG

我是新的android编程,所以请帮助我… 我已经使用sqlite数据库浏览器创建了mydatabase.sqlite数据库文件,并将其复制到android应用程序中的assets文件夹中,以便从数据库文件中检索数据

我想在单击按钮时显示数据库表中的所有记录,并在列表视图中显示结果

这是密码

这是我的databasehelper类

public class DataBaseHelper extends SQLiteOpenHelper 
{ 
private static String TAG = "DataBaseHelper"; // Tag just for the LogCat window 
//destination path (location) of our database on device 
private static String DB_PATH = "";  
private static String DB_NAME ="datacoba";// Database name 
private SQLiteDatabase mDataBase;  
private final Context mContext; 

public DataBaseHelper(Context context)  
{ 
    super(context, DB_NAME, null, 1);// 1? its Database Version 
    DB_PATH = "/data/data/" + context.getPackageName() + "/databases/"; 
    this.mContext = context; 
}    

public void createDataBase() throws IOException 
{ 
    //If database not exists copy it from the assets 

    boolean mDataBaseExist = checkDataBase(); 
    if(!mDataBaseExist) 
    { 
        this.getReadableDatabase(); 
        this.close(); 
        try  
        { 
            //Copy the database from assests 
            copyDataBase(); 
            Log.e(TAG, "createDatabase database created"); 
        }  
        catch (IOException mIOException)  
        { 
            throw new Error("ErrorCopyingDataBase"); 
        } 
    } 
} 
    //Check that the database exists here: /data/data/your package/databases/Da Name 
    private boolean checkDataBase() 
    { 
        File dbFile = new File(DB_PATH + DB_NAME); 
        //Log.v("dbFile", dbFile + "   "+ dbFile.exists()); 
        return dbFile.exists(); 
    } 

    //Copy the database from assets 
    private void copyDataBase() throws IOException 
    { 
        InputStream mInput = mContext.getAssets().open(DB_NAME); 
        String outFileName = DB_PATH + DB_NAME; 
        OutputStream mOutput = new FileOutputStream(outFileName); 
        byte[] mBuffer = new byte[1024]; 
        int mLength; 
        while ((mLength = mInput.read(mBuffer))>0) 
        { 
            mOutput.write(mBuffer, 0, mLength); 
        } 
        mOutput.flush(); 
        mOutput.close(); 
        mInput.close(); 
    } 

    //Open the database, so we can query it 
    public boolean openDataBase() throws SQLException 
    { 
        String mPath = DB_PATH + DB_NAME; 
        //Log.v("mPath", mPath); 
        mDataBase = SQLiteDatabase.openDatabase(mPath, null, SQLiteDatabase.CREATE_IF_NECESSARY); 
        //mDataBase = SQLiteDatabase.openDatabase(mPath, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS); 
        return mDataBase != null; 
    } 

    @Override 
    public synchronized void close()  
    { 
        if(mDataBase != null) 
            mDataBase.close(); 
        super.close(); 
    }

    @Override
    public void onCreate(SQLiteDatabase arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub

    } 

} 
这个实用程序类

public class Utility {

    public static String GetColumnValue(Cursor cur, String ColumnName) {
        try {
            return cur.getString(cur.getColumnIndex(ColumnName));
        } catch (Exception ex) {
            return "";
        }
    }


    public static void ShowMessageBox(Context cont, String msg) {
        Toast toast = Toast.makeText(cont, msg, Toast.LENGTH_SHORT);
        // toast.setGravity(Gravity.CENTER, 0, 0);
        toast.setGravity(Gravity.CENTER | Gravity.CENTER, 0, 0);
        toast.show();
    }
}
这个适配器类

public class TestAdapter  
{ 
protected static final String TAG = "DataAdapter"; 

private final Context mContext; 
private SQLiteDatabase mDb; 
private DataBaseHelper mDbHelper; 

public TestAdapter(Context context)  
{ 
    this.mContext = context; 
    mDbHelper = new DataBaseHelper(mContext); 
} 

public TestAdapter createDatabase() throws SQLException  
{ 
    try  
    { 
        mDbHelper.createDataBase(); 
    }  
    catch (IOException mIOException)  
    { 
        Log.e(TAG, mIOException.toString() + "  UnableToCreateDatabase"); 
        throw new Error("UnableToCreateDatabase"); 
    } 
    return this; 
} 

public TestAdapter open() throws SQLException  
{ 
    try  
    { 
        mDbHelper.openDataBase(); 
        mDbHelper.close(); 
        mDb = mDbHelper.getReadableDatabase(); 
    }  
    catch (SQLException mSQLException)  
    { 
        Log.e(TAG, "open >>"+ mSQLException.toString()); 
        throw mSQLException; 
    } 
    return this; 
} 

public void close()  
{ 
    mDbHelper.close(); 
} 

 public Cursor getTestData() 
 { 
     try 
     { 
         String sql ="SELECT Nama_student From Nama"; 

         Cursor mCur = mDb.rawQuery(sql, null); 
         if (mCur!=null) 
         { 
            mCur.moveToNext(); 
         } 
         return mCur; 
     } 
     catch (SQLException mSQLException)  
     { 
         Log.e(TAG, "getTestData >>"+ mSQLException.toString()); 
         throw mSQLException; 
     } 
 }
}

这是我的主要活动课

public class MainActivity extends Activity {

@Override
 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}



public void LoadEmployee(View v)
{
    TestAdapter mDbHelper = new TestAdapter(this);         
    mDbHelper.createDatabase();       
    mDbHelper.open(); 

    Cursor testdata = mDbHelper.getTestData(); 

    String name = Utility.GetColumnValue(testdata, "Nama_student");


    Utility.ShowMessageBox(this, "Name: "+ name);
    mDbHelper.close();

}

}
这些代码生成toast显示的输出,如 只显示了表格的第一行。 如何显示表中的所有行并在listview中显示结果? 编辑:这是我的xml布局

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >


    <Button
        android:id="@+id/btnSearch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="14dp"
        android:layout_marginTop="19dp"
        android:onClick="LoadEmployee"
        android:text="Load Employee"
       />
    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/btnSearch"
        android:layout_below="@+id/btnSearch"
        android:layout_marginLeft="21dp"
        android:layout_marginTop="166dp" >
    </ListView>


我在您的代码中没有看到一些
列表视图。您需要
ListView
和一些适配器。然后,用数据库中的记录填充适配器,并将此适配器设置为您的
列表视图

为什么在
getTestData
方法中返回
Cursor
?例如,您可以创建一些包装类,并使用此类的实例返回
List
。通过此
列表
列表视图
创建适配器非常简单

编辑:

好的,首先需要创建一个
ArrayAdapter
。当然,您可以使用其他类型的适配器。也可以创建自定义适配器。这种方法很简单

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, list);

您需要在
LoadEmployee
方法中编写以下代码:

Cursor testdata = mDbHelper.getTestData();     

 /** the desired columns to be bound **/
 String[] columns = new String[] { "Nama_student" };

 /** the XML defined views which the data will be bound to **/
 int[] to = new int[] { R.id.name_entry, R.id.number_entry };

 /** create the adapter using the cursor pointing to the desired data as well as the layout information **/
 SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this,
            R.layout.list_example_entry, cursor, columns, to);

 /** set this adapter as your ListActivity's adapter **/
 listview.setAdapter(mAdapter);
以下链接将帮助您了解其工作原理:


您可以在创建适配器的线上方看到。它很简单
ArrayAdapter
。但是,如果您想在一行
ListView
中显示单行,这就足够了。因此,我需要在databasehelper中使用此代码,并设置返回(context,android.R.layout.simple_list_item_1,设置此字段的返回)?它仍然有一个问题,我已经在databasehelper上有了上下文,现在如何在主活动上初始化?我可以这样初始化吗
Context mycontext;ArrayAdapter=新的ArrayAdapter(mycontext,android.R.layout.simple\u list\u item\u 1,list);如果您正在活动中创建适配器,只需将
这个
关键字放入
ArrayAdapter
构造函数的第一个参数中。也许您应该先询问Google。可能有很多关于这个的教程。
Cursor testdata = mDbHelper.getTestData();     

 /** the desired columns to be bound **/
 String[] columns = new String[] { "Nama_student" };

 /** the XML defined views which the data will be bound to **/
 int[] to = new int[] { R.id.name_entry, R.id.number_entry };

 /** create the adapter using the cursor pointing to the desired data as well as the layout information **/
 SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this,
            R.layout.list_example_entry, cursor, columns, to);

 /** set this adapter as your ListActivity's adapter **/
 listview.setAdapter(mAdapter);