Skip to main content
Bumped by Community user
Bumped by Community user
Bumped by Community user
Spelling, grammar and punctuation fixes
Source Link
Toby Speight
  • 88.4k
  • 14
  • 104
  • 327

I have created code for inserting and retrieving data from a specific table i. I tried to optimize it and make it as beautiful and easy to read as iI can  , but maybe, or, (almost certainly i'm) I'm missing something. 

It works well, but I wonder if I did all right? Haven't Have I forgotenforgotten about something?

I have created code for inserting and retrieving data from a specific table i tried to optimize it and make it as beautiful and easy to read as i can  , but maybe, or, certainly i'm missing something. It works well, but I wonder if I did all right? Haven't I forgoten about something?

I created code for inserting and retrieving data from a specific table. I tried to optimize it and make it as beautiful and easy to read as I can, but maybe (almost certainly) I'm missing something. 

It works well, but I wonder if I did all right? Have I forgotten about something?

Source Link
Alex
  • 11
  • 1

Code for writing and reading from the database

I have created code for inserting and retrieving data from a specific table i tried to optimize it and make it as beautiful and easy to read as i can , but maybe, or, certainly i'm missing something. It works well, but I wonder if I did all right? Haven't I forgoten about something?

public class EpgManager {

private DatabaseHandler db;
private List<JSONEpgManagerModel> jsonEpgManagerModel;
private EPGManagerEvent epgManagerEvent;
private SQLiteDatabase sqlDB;
private List<EPGModel> singleEpgChannel;
private List<EPGFullRowModel> fullRowModelList = new ArrayList<>();

public EpgManager(Context context, EPGManagerEvent epgManagerEvent) {
    db = new DatabaseHandler(context);
    sqlDB = db.getWritableDatabase();
    this.epgManagerEvent = epgManagerEvent;
}

/**
 * Method: Serializes Json String into Object of type JsonEpgManagementModel
 * <ul>
 * <li>Creates a sql insert query</li>
 * <li>Cleans epg_table</li>
 * <li>Loads data from JSON</li>
 * <li>Calls the {@link #epgManagerEvent onEpgUpdated} to show completion</li>
 * </ul>
 *
 * @param JSON epg json array
 */
public void updateEpgTable(final String JSON, final HashMap<String, Integer> channelNumberMap,
    final HashMap<String, String> channelImageMap) {

    new AsyncTask<Void, Void, Void>() {

        @Override
        protected Void doInBackground(Void... params) {
            sqlDB.delete(db.EPG_TABLE, null, null);

            try {
                jsonEpgManagerModel = Arrays
                    .asList(new Gson().fromJson(JSON, JSONEpgManagerModel[].class));
            } catch (Exception e) {
                e.printStackTrace();
            }

            writeEPGTable(jsonEpgManagerModel, channelNumberMap, channelImageMap);

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);

            epgManagerEvent.onEpgUpdated();

        }
    }.execute();
}

/**
 * Method: Inserts rows into epg_table
 *
 * @param jsonEpgManagerModel Serialized EPG Model
 * @param channelNumberMap Channel ID and Channel Number HashMap
 * @param channelImageMap Channel ID and Channel Image HashMap
 */
private void writeEPGTable(List<JSONEpgManagerModel> jsonEpgManagerModel,
    HashMap<String, Integer> channelNumberMap, HashMap<String, String> channelImageMap) {
    String epgSqlInsertStatement = "INSERT INTO "
        + db.EPG_TABLE
        + "("
        + db.KEY_EPG_ID + "," + db.KEY_EPG_DATE + ","
        + db.KEY_EPG_DATE_MILLISECONDS + "," + db.KEY_EPG_DISPLAY_TIME + ","
        + db.KEY_EPG_TITLE + "," + db.KEY_EPG_DESCRIPTION + "," + db.KEY_EPG_IMAGE_URL + ","
        + db.KEY_EPG_DURATION + "," + db.KEY_EPG_CHANNEL_ID + ","
        + db.KEY_EPG_CHANNEL_NUMBER + "," + db.KEY_EPG_CHANNEL_IMAGE_LINK
        + ")"
        + " values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";

    sqlDB.beginTransaction();
    SQLiteStatement sqLiteStatement = sqlDB.compileStatement(epgSqlInsertStatement);

    for (int i = 0; i < jsonEpgManagerModel.size(); i++) {
        for (int k = 0; k < jsonEpgManagerModel.get(i).getEPGList().size(); k++) {

            ChannelPrograms epgProgram = jsonEpgManagerModel.get(i).getEPGList().get(k);

            sqLiteStatement.bindString(1, epgProgram.getEpgId());
            sqLiteStatement.bindString(2, epgProgram.getEpgDate());
            sqLiteStatement.bindLong(3, getDateInMilliseconds(epgProgram.getEpgDate()));
            sqLiteStatement.bindString(4, epgProgram.getEpgDisplayTime());
            sqLiteStatement.bindString(5, epgProgram.getEpgTitle());
            sqLiteStatement.bindString(6, epgProgram.getEpgDescription());
            sqLiteStatement.bindString(7, epgProgram.getEpgImageUrl());
            sqLiteStatement.bindString(8, epgProgram.getEpgDuration());
            sqLiteStatement.bindString(9, jsonEpgManagerModel.get(i).getEpgChannelId());
            sqLiteStatement.bindString(10, "" + channelNumberMap.get(jsonEpgManagerModel.get(i).getEpgChannelId()));
            sqLiteStatement.bindString(11, "" + channelImageMap.get(jsonEpgManagerModel.get(i).getEpgChannelId()));

            sqLiteStatement.executeInsert();
            sqLiteStatement.clearBindings();
        }
    }

    sqlDB.setTransactionSuccessful();
    sqlDB.endTransaction();
}

/**
 * Method returns list of epg channels and programs in order to build the epg
 * <ul>
 * <li>Gets rows from channel_table</li>
 * <li>Gets rows from epg_table by channel_table channel_id</li>
 * <li>Populates list of EPGFullRowModel class</li>
 * </ul>
 *
 * @return EPG Screen data list of type EPGFullRowModel
 */
public List<EPGFullRowModel> getAllChannelPrograms() {
    List<EPGModel> epgProgramList = new ArrayList<>();

    Cursor channelCursor = sqlDB.query(db.CHANNEL_TABLE,
        new String[] {db.KEY_CHANNEL_ID, db.KEY_CHANNEL_IMG_LINK, db.KEY_CHANNEL_NUMBER}, null,
        null, null, null, null);
    Cursor epgCursor;

    while (channelCursor.moveToNext()) {

        epgCursor = sqlDB.query(db.EPG_TABLE, null, db.KEY_EPG_CHANNEL_ID + "=?",
            new String[] {channelCursor.getString(0)}, null, null,
            db.KEY_EPG_DATE_MILLISECONDS + " ASC");
        while (epgCursor.moveToNext()) {
            epgProgramList.add(
                new EPGModel(
                    epgCursor.getString(1),epgCursor.getString(2),
                    epgCursor.getString(3),epgCursor.getString(4),
                    epgCursor.getString(5),epgCursor.getString(6),
                    epgCursor.getString(7),epgCursor.getString(8),
                    epgCursor.getString(9),channelCursor.getString(2),
                    epgCursor.getString(1)
                )
            );

        }
        fullRowModelList.add(new EPGFullRowModel(
            new ChannelModel(channelCursor.getString(0), channelCursor.getString(1),
                Integer.valueOf(channelCursor.getString(2))), epgProgramList));

        epgCursor.close();
        epgProgramList = new ArrayList<>();
    }

    channelCursor.close();
    return fullRowModelList;
}

/**
 * Method returns list of epg programs in order to build the single channel epg
 *
 * @param channelId Channel unique id
 * @return Single epg row list of type EPGModel
 */
public List<EPGModel> getSingleChannelPrograms(String channelId) {

    Cursor cursor = sqlDB
        .query(db.EPG_TABLE, null, db.KEY_EPG_CHANNEL_ID + "=?", new String[] {channelId}, null,
            null,  db.KEY_EPG_DATE_MILLISECONDS + " ASC", null);

    singleEpgChannel = new ArrayList<>();
    Log.e("CURSOR ", String.valueOf(cursor.getCount()));
    if (cursor.moveToFirst()) {
        do {
            singleEpgChannel.add(
                new EPGModel(cursor.getString(1), cursor.getString(2), cursor.getString(3),
                    cursor.getString(4), cursor.getString(5), cursor.getString(6),
                    cursor.getString(7), cursor.getString(8), cursor.getString(9),
                    cursor.getString(10), cursor.getString(11)));
        } while (cursor.moveToNext());
    }
    cursor.close();
    return singleEpgChannel;
}

/**
 * Method transforms the date of string into long of milliseconds
 *
 * @param date Epg program date
 * @return Milliseconds
 */
private long getDateInMilliseconds(String date) {

    date = date.replaceAll("T", " ");
    date = date.replaceAll("Z", "");
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Calendar calendar = Calendar.getInstance();
    try {
        calendar.setTime(simpleDateFormat.parse(date));
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    return calendar.getTimeInMillis();
}
}