sosegon
sosegon

Reputation: 119

Reference generated code in Java

I'm creating an android application. I'm using schematic to generate a content provider.

I understand that the actual code used by the application is generated out of the classes I create. Based on that, I'd like to know what problems I will face if I reference the generated code in the source code.

The code I'm using is the following:

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);
  }
}

The generated code is next:

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);
  }
}

As you can see, I need the SQL statements generated by the source code, and the idea of using the mentioned library is to avoid all the boilerplate code.

Are there other alternatives?

Upvotes: 0

Views: 391

Answers (1)

MyDogTom
MyDogTom

Reputation: 4606

Slightly better approach would be:

  @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);
  }

At least you do not need to specify each table.

Based on that, I'd like to know what problems I will face if I reference the generated code in the source code.

I would say no real problems.

The only noticeable thing is that Android Studio will highlight this as compilation error until class is generated (during the first build).

Upvotes: 0

Related Questions