2013-04-24 130 views
0

我已成功添加的数据在我ArrayClassDatabase下面访问数据机器人

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; 

    ArticlesTable articlesTable=new ArticlesTable(); 
    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<Article> getArticlesList(){ 
     ArrayList<Article> items=new ArrayList<Article>(); 

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

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

        a.enseigne=cursor.getString(cursor.getColumnIndex(articlesTable.ENSEIGNE)); 
        a.tel=cursor.getString(cursor.getColumnIndex(articlesTable.TEL)); 
        a.fax=cursor.getString(cursor.getColumnIndex(articlesTable.FAX)); 
        a.latitude=cursor.getString(cursor.getColumnIndex(articlesTable.LATITUDE)); 
        a.longitude=cursor.getString(cursor.getColumnIndex(articlesTable.LONGITUDE)); 

        a.adresse1=cursor.getString(cursor.getColumnIndex(articlesTable.ADRESSE1)); 
        a.adresse2=cursor.getString(cursor.getColumnIndex(articlesTable.ADRESSE2)); 
        a.adresse3=cursor.getString(cursor.getColumnIndex(articlesTable.ADRESSE3)); 
        a.adresse4=cursor.getString(cursor.getColumnIndex(articlesTable.ADRESSE4)); 
        a.adresse5=cursor.getString(cursor.getColumnIndex(articlesTable.ADRESSE5)); 
        a.adresse6=cursor.getString(cursor.getColumnIndex(articlesTable.ADRESSE6)); 

        a.horaires1=cursor.getString(cursor.getColumnIndex(articlesTable.HORAIRE1)); 
        a.horaires2=cursor.getString(cursor.getColumnIndex(articlesTable.HORAIRE2)); 
        a.horaires3=cursor.getString(cursor.getColumnIndex(articlesTable.HORAIRE3)); 
        a.horaires4=cursor.getString(cursor.getColumnIndex(articlesTable.HORAIRE4)); 
        a.horaires5=cursor.getString(cursor.getColumnIndex(articlesTable.HORAIRE5)); 
        a.horaires6=cursor.getString(cursor.getColumnIndex(articlesTable.HORAIRE6)); 
        a.horaires7=cursor.getString(cursor.getColumnIndex(articlesTable.HORAIRE7)); 

        items.add(a); 

        System.out.println("added_items:"+items); 
       } 
       while (cursor.moveToNext()); 
      } 
      if (cursor != null && !cursor.isClosed()) 
      { 
      cursor.close(); 

      } 
     } 
     catch(SQLiteException e){ 

      e.printStackTrace(); 
      return null; 
     } 

     return items; 
    } 
    //--here 
    public boolean addArticle(Article a){ 
     this.database.beginTransaction(); 

     try{ 

      ContentValues contentValues=new ContentValues(); 

      contentValues.put(articlesTable.ENSEIGNE, a.enseigne); 
      contentValues.put(articlesTable.TEL, a.tel); 
      contentValues.put(articlesTable.FAX, a.fax); 

      contentValues.put(articlesTable.LATITUDE, a.latitude); 
      contentValues.put(articlesTable.LONGITUDE, a.longitude); 
      contentValues.put(articlesTable.ADRESSE1, a.adresse1); 
      contentValues.put(articlesTable.ADRESSE2, a.adresse2); 
      contentValues.put(articlesTable.ADRESSE3, a.adresse3); 
      contentValues.put(articlesTable.ADRESSE4, a.adresse4); 
      contentValues.put(articlesTable.ADRESSE5, a.adresse5); 
      contentValues.put(articlesTable.ADRESSE6, a.adresse6); 

      contentValues.put(articlesTable.HORAIRE1, a.horaires1); 
      contentValues.put(articlesTable.HORAIRE2, a.horaires2); 
      contentValues.put(articlesTable.HORAIRE3, a.horaires3); 
      contentValues.put(articlesTable.HORAIRE4, a.horaires4); 
      contentValues.put(articlesTable.HORAIRE5, a.horaires5); 
      contentValues.put(articlesTable.HORAIRE6, a.horaires6); 
      contentValues.put(articlesTable.HORAIRE7, a.horaires7); 

      this.database.insert(articlesTable.TABLE_NAME,null,contentValues); 
     this.database.setTransactionSuccessful(); 
     }catch(Exception e){ 
      e.printStackTrace(); 
      return false; 
     }finally{ 
      this.database.endTransaction(); 
     } 
     return true; 
    } 


    public boolean deleteArticle(String id){ 
     try 
     { 
      String query="delete from " + articlesTable.TABLE_NAME+" where "+articlesTable.NOM+"='"+id+"'"; 
      this.database.execSQL(query); 
     } 
     catch(SQLiteException e){ 
      e.printStackTrace(); 
      return false; 
     } 
     return true; 
    } 

在上面的代码,Article a=new Article();是如下一类的保持值:

public class Article { 
    public String enseigne, type,nom,latitude,longitude, 
    tel,fax,adresse1,adresse2,adresse3,adresse4,adresse5, 
    adresse6,horaires1,horaires2,horaires3,horaires4,horaires5, 
    horaires6,horaires7 ; 
} 

在我的MainActivity.classonCreate()方法。我想打印名称。我怎样才能做到这一点。
MainActivity.class我初始化一个Article像如下Article a = new Article();然后调用a.name但这不是这样。

回答

0

您正在使用Article a = new Article()创建新实例,因此对于新对象,所有String变量都是null

MainActivity中调用DbHelper类的方法getArticlesList()并得到ArrayList那个方法returns。然后你可以使用nameOfArrayList.get(position).name和其他...

希望这有助于...

+0

DBHelper helper = DBHelper.getInstance(context); ArrayList

mArticles = helper.getArticlesList(); \t \t \t \t System.out.println(“TODAY:”+ mArticles.get(0).adresse1);不工作 – Christina 2013-04-24 07:14:10

+0

“不工作”是指?数据库中是否有数据?即您是否在数据库中添加了数据? – 2013-04-24 07:22:19

+0

是数据库有数据。 “不工作”仅表示实际输出=“TODAY:”。预期的输出“TODAY:addresse1” – Christina 2013-04-24 07:26:41

0

1)在你的onCreate(),你会想你的instiantiate类DBHelper

DBHelper dbhelper = new DBHelper(); 

2 )在的onCreate(),你会打电话给getArticlesList()

ArrayList<Article> mArticles = dbhelper.getArticlesList(); 

3)当你要使用的物品,只要抓住你想要哪一个通过指数:

Article = mArticles.get(x); 

这应该正是你所需要的。

+0

我这样做了但没有显示 DBHelper helper = DBHelper.getInstance(context); ArrayList

mArticles = helper.getArticlesList(); \t \t \t \t System.out.println(“TODAY:”+ mArticles.get(0).adresse1); – Christina 2013-04-24 07:13:39

+0

你真的使用System.out.println()吗?这个调用显示给普通Java的控制台,但为了看到LogCat中的输出,我猜你在看,你将不得不使用Log消息,像android.util.Log.i(“myTag” ,“mArticles adresse1 =”+ mArticles.get(0).adresse1);然后您可以通过LogCat搜索“myTag”并查看您的消息。 – MarsAtomic 2013-04-24 07:21:55

+0

只是试图仍然null :( – Christina 2013-04-24 07:25:13