用Java引用生成的代码

时间:2016-10-04 18:35:31

标签: java android android-contentprovider generated-code

我正在创建一个Android应用程序。我使用schematic生成内容提供商。

我知道应用程序使用的实际代码是从我创建的类中生成的。基于此,如果我在源代码中引用生成的代码,我想知道我将面临哪些问题。

我使用的代码如下:

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语句,使用上述库的想法是避免所有样板代码。

还有其他选择吗?

1 个答案:

答案 0 :(得分: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会将此突出显示为编译错误,直到生成类(在第一次构建期间)。