2013-04-23 76 views
-1

我是新來的android的數據庫的東西。我想知道如何從我的數據庫中得到一個例如NAME的行ID。我已經使用了下面的一些研究,現在我堅持在顯示部分。顯示來自mysqllite數據庫的數據android

 public class DestinateurTable { 

       public String TABLE_NAME="destinateur"; 

       public String ROW_ID="rowid"; 
       public String NAME="name"; 
       public String AGENCE="agence"; 
       public String EMAIL="email"; 



      } 


     public class Destinataire { 


      public String rowid,name,agence,email; 


     } 


    **My DBHelper.class** 


    public class DBHelper { 

    private final String DATABASE_PATH = "/data/data/.../databases/"; 
    private final String DATABASE_NAME = "...sqlite"; 
    private final static int DATABASE_VERSION = 1; 

    private Context context; 
    private SQLiteDatabase database = null; 
    OpenHelper openHelper=null; 
    StringBuilder query =null; 
    Cursor cursor=null; 

    DestinateurTable destinataireTable = new DestinateurTable(); 

    public static DBHelper dbHelper = null; 

    private DBHelper(Context context) { 

    this.context = context; 
    openHelper = new OpenHelper(this.context); 
    this.database = openHelper.getWritableDatabase(); 

    try { 

     createDataBase(); 
     openDataBase(); 

    } catch (IOException e) { 

     e.printStackTrace(); 
    } 

    } 
    public static DBHelper getInstance(Context context) 
    { 
    if(dbHelper == null) 
     dbHelper = new DBHelper(context); 
    return dbHelper; 
    } 

    public void openDataBase() throws SQLException{ 

    //Open the database 
    String myPath = DATABASE_PATH + DATABASE_NAME; 
    database = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE); 
    } 

    /** 
    * Creates a empty database on the system and rewrites it with your own database. 
    * */ 
    public void createDataBase() throws IOException 
    { 
    openHelper.getReadableDatabase(); 
    if(getDBAlreadyCopiedToDeviceOnceFlag(context) == false){ 
     try { 
     copyDataBase(); 
     setDBAlreadyCopiedToDeviceOnceFlag(context); 
     } catch (IOException e) { 
     e.printStackTrace(); 
     throw new Error("Error copying database"); 
     } 
    } 
    } 

    /** 
    * Check if the database already exist to avoid re-copying the file each time you open the application. 
    * @return true if it exists, false if it doesn't 
    */ 
    @SuppressWarnings("unused") 
    private boolean checkDataBase(){ 

    SQLiteDatabase checkDB = null; 

    try{ 
     String myPath = DATABASE_PATH + DATABASE_NAME; 
     checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE); 

    }catch(SQLiteException e){ 

     //database does't exist yet. 

    } 

    if(checkDB != null){ 

     checkDB.close(); 

    } 

    return checkDB != null ? true : false; 
    } 

    /** 
    * Copies your database from your local assets-folder to the just created empty database in the 
    * system folder, from where it can be accessed and handled. 
    * This is done by transfering bytestream. 
    * */ 
    private void copyDataBase() throws IOException{ 

    //Open your local db as the input stream 
    InputStream myInput = context.getAssets().open(DATABASE_NAME); 

    // Path to the just created empty db 
    String outFileName = DATABASE_PATH + DATABASE_NAME; 

    //Open the empty db as the output stream 
    OutputStream myOutput = new FileOutputStream(outFileName); 

    //transfer bytes from the inputfile to the outputfile 
    byte[] buffer = new byte[1024]; 
    int length; 
    while ((length = myInput.read(buffer))>0){ 
     myOutput.write(buffer, 0, length); 
    } 

    //Close the streams 
    myOutput.flush(); 
    myOutput.close(); 
    myInput.close(); 

    } 

    private class OpenHelper extends SQLiteOpenHelper 
    { 

     @SuppressWarnings("unused") 
     SQLiteStatement insertStmt; 

     public OpenHelper(Context context) 
     { 
      super(context, DATABASE_NAME, null, DATABASE_VERSION); 
     } 

     @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 setDBAlreadyCopiedToDeviceOnceFlag(Context ctx) 
    { 
     SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx); 
     SharedPreferences.Editor editor = prefs.edit(); 
     editor.putBoolean("isDBAlreadyCopiedToDeviceOnce", true); 
     editor.commit(); 
    } 

    public boolean getDBAlreadyCopiedToDeviceOnceFlag(Context ctx) 
    { 
     SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx); 
     boolean isDBAlreadyCopiedToDeviceOnce = prefs.getBoolean("isDBAlreadyCopiedToDeviceOnce", false); 
     return isDBAlreadyCopiedToDeviceOnce; 
    } 



    //////////////////////////// 
    //// Write your methods here 
    //////////////////////////// 

    public ArrayList<Destinataire> getDestinataireList() 
    { 
     ArrayList<Destinataire> items=new ArrayList<Destinataire>(); 

     try 
     { 
      query = new StringBuilder(); 
      query.append("select * from "+destinataireTable.TABLE_NAME); 

      cursor=this.database.rawQuery(query.toString(),null); 
      if (cursor.moveToFirst()) 
      { 
       do 
       { 
        Destinataire d=new Destinataire(); 

        d.rowid=cursor.getString(cursor.getColumnIndex(destinataireTable.ROW_ID)); 
        d.name=cursor.getString(cursor.getColumnIndex(destinataireTable.NAME)); 
        d.agence=cursor.getString(cursor.getColumnIndex(destinataireTable.AGENCE)); 
        d.email=cursor.getString(cursor.getColumnIndex(destinataireTable.EMAIL)); 

        items.add(d); 

       } 

       while (cursor.moveToNext()); 
      } 
      if (cursor != null && !cursor.isClosed()) 
      { 
      cursor.close(); 

      } 
     } 
     catch(SQLiteException e){ 

      e.printStackTrace(); 
      return null; 
     } 

     return items; 
    } 

    //--here 
    public boolean addDestinataire(Destinataire d){ 
     this.database.beginTransaction(); 

     try{ 

      ContentValues contentValues=new ContentValues(); 

      contentValues.put(destinataireTable.ROW_ID, d.rowid); 
      contentValues.put(destinataireTable.NAME, d.name); 
      contentValues.put(destinataireTable.AGENCE, d.agence); 
      contentValues.put(destinataireTable.EMAIL, d.email); 

      this.database.insert(destinataireTable.TABLE_NAME,null,contentValues); 

      this.database.setTransactionSuccessful(); 

     } catch(Exception e){ 

      e.printStackTrace(); 

      return false; 

     } finally{ 

      this.database.endTransaction(); 

     } 

     return true; 
    } 


    public boolean deleteDestinataire(String id){ 

     try { 

      String query="delete from " + destinataireTable.TABLE_NAME+" where "+destinataireTable.ROW_ID+"='"+id+"'"; 
      this.database.execSQL(query); 
     } 

     catch(SQLiteException e){ 
      e.printStackTrace(); 
      return false; 
     } 
     return true; 
    } 


} 
+0

Salut! Cool de croiser desfrançaispar ici =)Je te conseil de lire ce tuto du site duzérosur la base dedonénesSQLite en Android:http://www.siteduzero.com/informatique/tutoriels/creez-des-applications-pour -android/les-bases-de-donnees – ZarkDev 2013-04-23 08:18:21

+0

j'ai beinin d'une solution au plus vite – Christina 2013-04-23 08:28:48

+0

Faut poster plus de code si tu veux de l'aide。 Ta提問est floue。 – 2013-04-23 08:30:17

回答

0

您的整個數據庫操作似乎很好。你提到現在你想顯示數據。 做它使用的是ListView,其連接到Adapter的最常見的方式,你可以直接用光標使用適配器,但你已經得到了它作爲一個清單,這樣你就可以使用ArrayAdapter

要使用它作爲一個簡單的測試,並開始瞭解它是如何工作的。創建extends ListActivity,然後你寫下面的代碼就可以了新的活動:

public class MyListActivity extends ListActivity{ 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     ArrayList<Destinataire> items = getDestinataireList(); 
     ArrayAdapter<Destinataire> adapter = new ArrayAdapter<Destinataire>(this, android.R.layout.simple_list_item_1 , android.R.id.text1, items) 
     setListAdapter(adapter); 
    } 
} 

還包括該行的Destinataire類中:

@Override 
public String toString() { 
    return name + " " + agence + " " + email; 
} 

這是一個非常簡單的例子,它不是最優化(對例如,您應該使用後臺線程從數據庫加載數據),但它應該顯示一個列表,其中每個項目顯示name agence email

快樂編碼!

編輯:

這一行:

new ArrayAdapter<Destinataire>(this, android.R.layout.simple_list_item_1 , android.R.id.text1, items) 

...有一些重要的部分,所以讓我解釋一下:

  • ArrayAdapter:它是標準的行爲是調用toString( )對於Array中的對象,在完成第一部分之後,您可以開始學習CustomAdapter,以製作更復雜(有趣)的內容。
  • this:這是引用ListActivity。每個活動都擴展了一個ContextWrapper,這意味着它們持有對設備資源的引用。適配器創建佈局非常重要。
  • android.R.layout.simple_list_item_1:這是一個標準的Android佈局,只是一行文本。非常簡單,但對於快速測試非常有用。它告訴適配器爲每個項目使用此佈局。
  • android.R.id.text1:它是佈局中文本的ID。它告訴適配器在佈局中有一個帶有該ID的TextView。所以它會從數據對象中獲取toString(),並將其設置爲TextView
  • items:這就是你的數據。
+0

是的,但如果我想只檢索名稱,例如意味着數據庫中的一行 – Christina 2013-04-23 09:01:48

+0

ArrayAdapter將在您的Destinataire類上調用toString()。所以你可以把toString改成你需要的任何東西。現在我將編輯我的答案,並對適配器進行更多解釋。請閱讀。 – Budius 2013-04-23 09:04:26

+0

我得到一個空指針exeption ..我相信我的數據庫路徑是錯誤的..是正確的方式採取「/ data/data/package_name/databases /作爲DATABASE_PATH? – Christina 2013-04-23 09:24:38

相關問題