2011-11-15 11 views
0

だから、私は以下のように通常のデータベースヘルパークラスを作っています。また、別のクラスでgetDataとinsertDataメソッドを使用して特定のものを取得するクラスを作成しました。たとえば、Userクラスを使用してUser nameを取得します。しかし、私の主なアクティビティでそのControllerクラスを呼び出すときに、そのクラスを使用したい場合は、アクセスしようとする列が存在しないことがわかります。Androidのsqliteカラムにエラーが見つかりません

error code = 1, msg = table userinfo has no column named username 

をまた、私は私のデータベースに_idandroid_metadataのようなものを追加しました:私はsqliteのは、返された... logcatに...

を言うている今、時間のこの時にしようとしてきたし、疲れています。おかげさまで

public class DatabaseHelper extends SQLiteOpenHelper{ 

      //The Android's default system path of your application database. 
      private static final String DB_PATH = "/data/data/com.cslearn/databases/"; 
      private static final String DB_NAME = "example.db"; 
      private static final int DB_VERSION = 1; 
      private final Context myContext; 
      private SQLiteDatabase myDatabase; 

      public DatabaseHelper(Context context) { 
       super(context, DB_NAME, null, DB_VERSION); 
       this.myContext = context; 
       System.out.println(context.getDatabasePath("myDatabase")); 
      } 
      public void createDataBase() throws IOException{ 
       System.out.println("database creating..."); 
       boolean dbExist = checkDataBase(); 

       if(dbExist){ 
        //do nothing - database already exist 
        System.out.println("db exists"); 
       }else{ 
        //By calling this method and empty database will be created into the default system path 
         //of your application so we are gonna be able to overwrite that database with our database. 
        this.getReadableDatabase(); 
        System.out.println("path = "+this.getReadableDatabase().getPath()); 
        System.out.println("get database"); 

        try { 
         this.close(); 
         copyDataBase(); 
        } catch (IOException e) { 
         throw new Error("Error copying database"); 
        } 
       } 
       System.out.println("database created"); 
       this.close(); 
      } 
      private boolean checkDataBase(){ 

       SQLiteDatabase checkDB = null; 

       try{ 
        String myPath = DB_PATH + DB_NAME; 
        checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY); 
       }catch(SQLiteException e){ 
        //database does't exist yet. 
       } 

       if(checkDB != null){ 
        checkDB.close(); 
       } 
       return checkDB != null ? true : false; 
      } 
      private void copyDataBase() throws IOException{ 


       System.out.println("Copying database...."); 
       //Open your local db as the input stream 
       InputStream myInput = myContext.getAssets().open(DB_NAME); 
       System.out.println("input > get assets"); 
       // Path to the just created empty db 
       String outFileName = DB_PATH + DB_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); 
        System.out.println("output write..."); 

       } 
       System.out.println("Database copied!!"); 
       //Close the streams 
       myOutput.flush(); 
       myOutput.close(); 
       myInput.close(); 

      } 
     /** public void openReadonlyDataBase() throws SQLException{ 

       //Open the database 
       String myPath = DB_PATH + DB_NAME; 
       myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY); 

      }*/ 
      public void openDataBase() throws SQLException{ 
       String myPath = DB_PATH + DB_NAME; 
       myDatabase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS); 
      } 

      @Override 
      public synchronized void close() { 

        if(myDatabase != null) 
         myDatabase.close(); 

        super.close(); 
      } 


      public void insertData (String sql){ 
       try { 
        this.createDataBase(); 
       } catch (IOException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 
       try { 
        this.openDataBase(); 
        System.out.println("database opened"); 
       }catch(SQLException e){ 

        throw e; 

       } 
       myDatabase.execSQL(sql); //separate values with , 
       this.close(); 
      } 



      public ArrayList<String> getData (String table,String [] columns, String selection){ 
       try { 
        this.createDataBase(); 
       } catch (IOException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 
       try { 
        this.openDataBase(); 
        System.out.println("database opened"); 

       }catch(SQLException e){ 
        throw e; 
       } 
       System.out.println("getting data"); 
       ArrayList<String> results = new ArrayList<String>(); 
       Cursor c = myDatabase.query(table, columns, selection, null, null, null, null); 
       System.out.println(c.getColumnCount()); 
       System.out.println(c.getColumnNames()); 
       System.out.println("got cursor c");  
        if (c != null) { 
         /* Check if at least one Result was returned. */ 
         if (c.moveToFirst()) { 
           do { 
             /* Retrieve the values of the Entry 
              * the Cursor is pointing to. */ 
              String[] row = new String[c.getColumnCount()];  
              for(int i=0; i<c.getColumnCount(); i++){  
               row[i] = c.getString(i); 
               System.out.println("getting data"); 
               results.add(row[i]); 
               System.out.println("adding string"); 
            } 

           } while (c.moveToNext()); 
         } 
        } 
       close(); 
       return results; 
      } 
      @Override 
      public void onCreate(SQLiteDatabase db) { 
      } 
      @Override 
      public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
      } 

       // Add your public helper methods to access and get content from the database. 
       // You could return cursors by doing "return myDataBase.query(....)" so it'd be easy 
       // to you to create adapters for your views. 
} 
+1

あなたはデータベースに実際にそのフィールドがあると思いますか?また、それは私たちに理解してもらうための多くのコードです。あなたはそれをだますことができますか? – Gray

+0

最初にDBを作成した後に列を追加した場合は、DBUVERSION = 2を設定してonUpgrade()をトリガーしてください。 –

+0

データベースを作成しましたb4私はヘルパーを作成しました – user1044585

答えて

2

あなたはのonCreate(SQLiteDatabaseデシベル)メソッドをオーバーライドしているが、それは何もしません。次のようにこのメソッドでテーブルを作成する必要があります。

// SQL statements to create new tables. 
private static final String TBL_FRIENDS = "friends"; 
private static final String CREATE_TABLE_FRIENDS = "create table " + 
    TBL_FRIENDS + " (" + KEY_ID + " integer primary key autoincrement, " + 
    FRIEND_ID + " integer not null, " + FRIEND_MARKER + " integer not null, " + 
    FRIEND_MOBILE + " text not null, " + FRIEND_NAME + " text not null);"; 

@Override 
    public void onCreate(SQLiteDatabase db) 
    {   
     db.execSQL("DROP TABLE IF EXISTS " + TBL_FRIENDS);   
     db.execSQL(CREATE_TABLE_FRIENDS);   

    } 

KEY_IDは、他のメソッドで使用される列名です。

+0

こんにちは、ありがとうございました。データベースからコピーして資産にコピーしたいだけです。私はそれをコピーする必要がある場合でも私は別にoncreateでそれらの同じテーブルを作成する必要がありますかshld私はちょうどその代わりにcopyDatabaseを呼び出すか? – user1044585

1

onCreate()onUpgrade()にコードを入力する必要があります。

onCreate()データベースが初めて作成されたときに呼び出されます。 onUpgrade()は、データベースのバージョンを増やすと呼び出されます。 onCreate()onUpgrade()

  • onCreate(SQLiteDatabase db)

    使用例は、テーブルを作成するSQLコマンドを実行します。

  • onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)は、テーブルが存在する場合はテーブルを削除するSQLコマンドを実行し、onCreate()を呼び出す(テーブルに新しい構造が追加されるように)。

onUpgradeを呼び出すときはいつでも、DB_VERSIONを増やすことを忘れないでください。

+0

こんにちは、ありがとうございましたが、iveは既にデータベースを作成しており、資産からコピーしたいだけです。私はそれをコピーする必要がある場合でも私は別にoncreateでそれらの同じテーブルを作成する必要がありますかshld私はちょうどその代わりにcopyDatabaseを呼び出すか? – user1044585

0

テーブルの列名にDEFAULT VALUESを割り当てていますか?