繁体   English   中英

从现有的SQLite数据库显示数据到Listview

[英]Display Data From Existing SQLite Database To Listview

我是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显示的输出,像这样,并且仅显示表的第一行。 如何显示表格中的所有行并在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 您需要ListView和一些适配器。 然后,用数据库中的记录填充适配器,并将此适配器设置为ListView

为什么要在getTestData方法中返回Cursor 例如,您可以创建一些包装器类并返回带有此类实例的List 通过此List非常容易为ListView创建适配器。

编辑:

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

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

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

   listView.setAdapter(adapter);

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM