2014-03-27 54 views
0

我是新來的android編程,所以請幫助我... 我已經創建了mydatabase.sqlite數據庫文件使用SQLite數據庫瀏覽器,並將其複製到android應用程序中的資產文件夾以從數據庫中檢索數據文件。從現有的SQLite數據庫顯示數據到列表視圖

我想顯示數據庫表中按鈕單擊的所有記錄並在列表視圖中顯示結果。

下面的代碼

這個我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; 
    } 
} 

}

,這是我的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(); 

} 

} 

的代碼產生由烤麪包示出的輸出,象this 而就僅顯示該表的第一行。 如何顯示錶中的所有行並在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> 

+0

也許你應該先問Google。可能有一些這樣的教程。 –

回答

1

我沒有看到一些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); 
+0

你可以給我的listview適配器代碼? – Labalumit

+0

您可以在創建適配器的行的上方看到。這很簡單'ArrayAdapter'。但是如果你想在一個ListView行中顯示單行,這就足夠了。 – PetrS

+0

所以我需要這個代碼在我的databasehelper [鏈接](http://tinypic.com/r/k2ph4/8)並設置返回\t (上下文,android.R.layout.simple_list_item_1,**設置返回這個領域**); ? – Labalumit

0

你需要編寫下面的代碼在你的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

相關問題