2016-10-04 118 views
0

我正在創建一個android應用程序。我正在使用schematic來生成內容提供者。在Java中引用生成的代碼

我知道應用程序使用的實際代碼是由我創建的類生成的。基於此,我想知道如果在源代碼中引用生成的代碼,我將面臨什麼問題。

我正在使用的代碼如下:

package com.example.movies.data; 

@Database(
    version = MovieDatabase.VERSION, 
    packageName = "com.example.movies.provider" 
) 
public class MovieDatabase { 
    public static final int VERSION = 1; 

    @Table(MovieColumns.class) 
    public static final String MOVIE = "movie"; 

    // Some more tables here 

    @OnUpgrade 
    public static void onUpgrade(Context context, SQLiteDatabase db, int oldVersion, int newVersion) { 
    db.execSQL("drop table if exists " + MOVIE); 

    // The next SQL statement is generated out of the current class 
    db.execSQL(com.example.movies.provider.MovieDatabase.MOVIE); 
    } 
} 

生成的代碼如下:

package com.example.movies.provider; 

public class MovieDatabase extends SQLiteOpenHelper { 
    private static final int DATABASE_VERSION = 1; 

    // The next statement is the one I use in the source code 
    public static final String MOVIE = "CREATE TABLE movie (" 
    + MovieColumns._ID + " INTEGER PRIMARY KEY," 
    + MovieColumns.TITLE + " TEXT NOT NULL," 
    + MovieColumns.SYNOPSIS + " TEXT," 
    + MovieColumns.POSTER_URL + " TEXT NOT NULL," 
    + MovieColumns.RELEASE_DATE + " INTEGER NOT NULL," 
    + MovieColumns.RATING + " REAL)"; 

    // Some other SQL statements and functions 

    // The next function is generated out of onUpgrade 
    // in the source class MovieDatabase 
    @Override 
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
    com.example.movies.data.MovieDatabase.onUpgrade(context, db, oldVersion, newVersion); 
    } 
} 

正如你所看到的,我需要的源代碼生成的SQL語句,並且使用所提到的庫的想法是避免所有的樣板代碼。

是否有其他的選擇?

回答

0

稍微好一點的做法是:

@OnUpgrade 
    public static void onUpgrade(Context context, SQLiteDatabase db, int oldVersion, int newVersion) { 
    db.execSQL("drop table if exists " + MOVIE); 

    // The next SQL statement is generated out of the current class 
    com.example.movies.provider.MovieDatabase.getInstance(context).onCreate(db); 
    } 

至少你不必指定每個表。

基於此,我想知道如果我在源代碼中引用生成的代碼將面臨什麼問題。

我會說沒有真正的問題。

唯一值得注意的是,Android Studio會在生成類(第一次構建期間)之前將其突出顯示爲編譯錯誤。