【问题标题】:Display Data From Existing SQLite Database To Listview将现有 SQLite 数据库中的数据显示到 Listview
【发布时间】:2014-03-27 23:52:09
【问题描述】:

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

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

这里是代码

这是我的数据库助手类

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; 
     } 
 }

}

这是我的 MainActivity 类

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 显示的输出,例如 this 并且只显示了表格的第一行。 如何显示表中的所有行并在列表视图中显示结果? 编辑:这是我的 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>

【问题讨论】:

  • 也许你应该先问问谷歌。可能有很多教程。

标签: android sql database sqlite listview


【解决方案1】:

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

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

编辑:

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

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

List 是某个列表的实例,其中包含您要在ListView 中显示的数据。接下来,您只需初始化ListView 并设置适配器。

   listView.setAdapter(adapter);

【讨论】:

  • 您可以在创建适配器的行上方看到。很简单ArrayAdapter。但是如果你想在一个ListView 行中显示单行,就足够了。
  • 所以我需要在我的数据库助手link 中使用此代码并将返回设置为(上下文,android.R.layout.simple_list_item_1,在此字段上设置返回); ?
  • 它仍然有 1 个问题,我已经在 databasehelper 上有了上下文,现在我该如何初始化主要活动?我可以像这样初始化吗
    Context mycontext; ArrayAdapter 适配器 = new ArrayAdapter(mycontext, android.R.layout.simple_list_item_1, list);
  • 如果你在activity中创建适配器,只需将this关键字放入ArrayAdapter的构造函数的第一个参数中即可。
【解决方案2】:

您需要在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);

以下链接将帮助您了解其工作原理:

http://developer.android.com/guide/topics/ui/layout/listview.html

http://www.vogella.com/tutorials/AndroidSQLite/article.html

http://www.tuicool.com/articles/rUFr2m

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-19
    • 2017-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多