2016-10-04 60 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会在生成类(第一次构建期间)之前将其突出显示为编译错误。