javaandroidsqlite

Retrieve data from asset folder in Android


I can't insert database in asset folder into my main activity. I get an error when I run this.

I need to place in that columns and that columns is in names activity.

public class DatabaseHelper extends SQLiteOpenHelper {

    private static String DB_PATH = "file:///android_asset/bcanew.db";
    private static String DB_NAME = "bcanew.db";
    private SQLiteDatabase myDataBase;
    private Context context;
    public static final String TABLE_NAME = "student_names";
    public static final String COL_1 = "ID";
    public static final String COL_2 = "NAME";
    public static final String COL_3 = "CURRENT_CGPA";
    public static final String COL_4 = "ACTIVE_BACKLOGS";

    public DatabaseHelper(Context context, Names names, SQLiteDatabase.CursorFactory factory, int version) {

        super(context, String.valueOf(names), factory, version);
    }

    private void copyDataBase() throws IOException {

        // Open your local db as the input stream
        InputStream myInput = context.getAssets().open(DB_NAME);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int i, int i1) {

        db = SQLiteDatabase.openDatabase(DB_PATH, null, SQLiteDatabase.OPEN_READONLY);
        onCreate(db);
    }

    public Cursor getData() {
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor res;
        res = db.rawQuery("select * from " + TABLE_NAME, null);
        return res;
    }
}

Solution

  • Try this code.. make method for read file from assets folders.. and return file as string.

    private String readFile(String fileName, Context context) {
        StringBuilder returnString = new StringBuilder();
        InputStream fIn = null;
        InputStreamReader isr = null;
        BufferedReader input = null;
        try {
            fIn = context.getResources().getAssets().open(fileName);
            isr = new InputStreamReader(fIn);
            input = new BufferedReader(isr);
            String line;
            while ((line = input.readLine()) != null) {
                returnString.append(line);
            }
        } catch (Exception e) {
            e.getMessage();
        } finally {
            try {
                if (isr != null) isr.close();
                if (fIn != null) fIn.close();
                if (input != null) input.close();
            } catch (Exception e2) {
                e2.getMessage();
            }
        }
        return returnString.toString();
    }
    

    after that calls method into activity or fragment like this way..

            String jsonObject = readFile("wg_sample.json", this); // define file name here define one json file name.