NBC NBC - 6 months ago 17
Android Question

How to reference a BufferReader variable outside of try/catch block

I'm trying to read a csv file in res/raw/ into a SQLite database. Here is my function:

public void updateDatabase(Context context, SQLiteDatabase database) {

InputStream inputStream = context.getResources().openRawResource(R.raw.teamlist);
try {
BufferedReader buffer = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
} catch (UnsupportedEncodingException ioe) {
Log.e("ERROR", "Could not load " + ioe);
}

String line = "";

database.beginTransaction();
try {
while ((line = buffer.readLine()) != null) {
// read each line from CSV file into a database

}
} catch (IOException ioe){
Log.e("ERROR", "Could not load " + ioe);
}
database.setTransactionSuccessful();
database.endTransaction();
}


But I get the error "Cannot resolve symbol 'buffer'" in the while loop. How do I reference the BufferReader outside the try function? I tried initializing the buffer reader outside the try block using "null", but that caused my app to crash. Any suggestions?

EJP EJP
Answer

Don't write code like this. A more correct way to write it would be:

public void updateDatabase(Context context, SQLiteDatabase database) {

    try (InputStream inputStream = context.getResources().openRawResource(R.raw.teamlist);
        BufferedReader buffer = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));) {

        String line;
        database.beginTransaction();
        while ((line = buffer.readLine()) != null) {
            // read each line from CSV file into a database

        }
        database.setTransactionSuccessful();
        database.endTransaction();
    } catch (IOException ioe){
        Log.e("ERROR", "Could not load " + ioe);
    } catch (UnsupportedEncodingException ioe) {
        Log.e("ERROR", "Could not load " + ioe);
    }
}

In summary, code that depends on the success of code that is in a prior try block should be inside that try block. Don't write strings of try/catch statements like you did.

Note that this also cures a resource leak on the input stream, and that the line variable does not need to be initialized.