-1

Hi im creating an app that retrieves sqlite database in the assets folder. When i run the program, it says no such table: students while compiling SELECT * FROM students. The assets folder has students.sqlite and has a table name students that composed of id,name and gender. I'll show my codes below.

DatabaseHelper class

public class DatabaseHelper extends SQLiteOpenHelper {

    private static String DB_PATH = "/data/data/com.example.user.students/databases/";
    private static String DB_NAME = "students.sqlite";
    private SQLiteDatabase myDataBase;
    private Context myContext = null;


    public DatabaseHelper(Context context) {
        super(context, DB_NAME, null, 1);
        this.myContext = context;
    }

    public void createDataBase() throws IOException {
        boolean dbExist = this.checkDataBase();
        if (!dbExist) {
            this.getReadableDatabase();

            try {
                this.copyDataBase();
            } catch (IOException e) {
                throw new Error("Error");
            }
        }
    }

    public void copyDataBase() throws IOException {
        InputStream myInput = this.myContext.getAssets().open(DB_NAME);
        String outFileName = DB_PATH + DB_NAME;
        FileOutputStream myOutput = new FileOutputStream(outFileName);
        byte[] buffer = new byte[1024];

        int length;
        while ((length = myInput.read(buffer)) > 0) {
            myOutput.write(buffer, 0, length);
        }

        myOutput.flush();
        myOutput.close();
        myInput.close();
    }

    public boolean checkDataBase() {
        SQLiteDatabase checkDB = null;

        try {
            String e = DB_PATH + DB_NAME;
            checkDB = SQLiteDatabase.openDatabase(e, null, 0);
        } catch (SQLiteException e) {
            ;
        }

        if (checkDB != null) {
            checkDB.close();
        }

        return checkDB != null;
    }

    public void openDataBase() throws SQLException {
        String myPath = DB_PATH + DB_NAME;
        this.myDataBase = SQLiteDatabase.openDatabase(myPath, null, 0);
    }

    public synchronized void close() {
        if (this.myDataBase != null) {
            this.myDataBase.close();
        }

        super.close();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

    public List<Students> getAll() {
        List<Students> sList = new ArrayList<Students>();
        {
            String selectQuery =
                    "SELECT * FROM students";
            Log.e("students query: ", selectQuery);
            SQLiteDatabase db = this.getWritableDatabase();
            Cursor cursor = db.rawQuery(selectQuery, null);

            // looping through all rows and adding to list
            if (cursor.moveToFirst()) {
                do {
                    Students si = new Students();
                    si.setid(Integer.parseInt(cursor.getString(0)));
                    si.setname(cursor.getString(1));
                    si.setgender(cursor.getString(2));

                    sList.add(si);
                } while (cursor.moveToNext());
            }

            db.close();
        }
        return sList;
    }
}

Students class

public class Students {

    //private variables
    int id;
    String name;
    String gender;

    // Empty constructor
    public Students(){

    }
    // constructor
    public Students(int id, String name, String gender){

        this.id = id;
        this.name = name;
        this.gender = gender;

    }

    // getting ID
    public int getid(){
        return this.id;
    }

    // setting id
    public void setid(int id){
        this.id = id;
    }

    // getting name
    public String getname(){
        return this.name;
    }

    // setting name
    public void setname(String name){
        this.name = name;
    }

    // getting gender
    public String getgender(){
        return this.gender;
    }

    // setting gender
    public void setgender(String gender){
        this.gender = gender;
    }



}

Main Activity class

public class MainActivity extends Activity {

    List<Students> GetAll;
    DatabaseHelper db = new DatabaseHelper(this);

    Context context = this;
    ListView list_doctors;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        list_students = (ListView) findViewById(R.id.list);
        GetAll = db.getAll();
        list_students.setAdapter(new ViewAdapter());
    }



    public class ViewAdapter extends BaseAdapter {

        LayoutInflater mInflater;

        public ViewAdapter() {
            mInflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount() {
            return GetAll.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.list_item,null);
            }

            final TextView names = (TextView) convertView.findViewById(R.id.name);
            final TextView gender = (TextView) convertView.findViewById(R.id.gender);

            names.setText(GetAll.get(position).getname());
            gender.setText(GetAll.get(position).getgender());

            return convertView;
        }

    }

}

APCM
  • 1,704
  • 1
  • 11
  • 24
  • what error does it throws..logcat please? – PunitD Oct 26 '15 at 08:12
  • android.database.sqlite.SQLiteException: no such table: students (code 1): , while compiling: SELECT * FROM students – APCM Oct 26 '15 at 08:16
  • Where is the createDataBase call? – KimKulling Oct 26 '15 at 08:18
  • i think you need to call createDataBase() method inside your constructor of DatabaseHelper...In this way, it could check whether database exist or not and if not (which it will be in first case , it will create it).. Clear? – PunitD Oct 26 '15 at 08:20
  • how?sorry im only new i only get the codes in the google @Droidwala – APCM Oct 26 '15 at 08:42
  • public void createDataBase() throws IOException { boolean dbExist = this.checkDataBase(); if (!dbExist) { this.getReadableDatabase(); try { this.copyDataBase(); } catch (IOException e) { throw new Error("Error"); } } } @KimKulling the createDataBase only double but this is located at the top – APCM Oct 26 '15 at 08:42
  • try adding createDatabase() line as first line inside your getAll() method and see if that works?! Check answer below: – PunitD Oct 26 '15 at 08:55

1 Answers1

2

Try adding following lines inside your onCreate() method of MainActivity:

public class MainActivity extends AppCompatActivity {
ListView lv;
ArrayList<Students> GetAll;
DatabaseHelper dbhelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    dbhelper = new DatabaseHelper(MainActivity.this);
    //Add below lines to your original code
    try{
        dbhelper.createDataBase();
    }
    catch(IOException e){
        e.printStackTrace();
    }
    try {
        dbhelper.openDataBase();
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    //Till here
    GetAll = dbhelper.getAll();
    lv = (ListView) findViewById(R.id.lv);
    lv.setAdapter(new ViewAdapter());

}

Basically the two lines added dbhelper.createDataBase() & dbhelper.openDatabase() simply check whether database has been copied from assets folder or not.

If createDatabase() method finds that database doesn't exists at internal Database Path (in your case it is /data/data/com.example.user.students/databases/) ,then it simply copies the database from assets folder to internal database location and and then simple call to OpenDatabase() would open the database for making the required read operations.

And if createDatabase() method finds that database already exists in DB_PATH then rest of method is not executed and then simple call to OpenDatabase() would open the database for making the required read operations.

Hope it clears the picture!!

PunitD
  • 2,293
  • 1
  • 20
  • 29
  • when i add it, I also add throws IOException in public List getAll() but in the main activity, i got error in this line GetAll = db.getAll(); – APCM Oct 26 '15 at 08:57
  • try removing line `this.getReadableDatabase();` from inside `createDataBase()`.. it shouldn't be there as per my thinking – PunitD Oct 26 '15 at 09:03
  • @KimKulling Oops!! :) – PunitD Oct 26 '15 at 09:04
  • i remove it and still the GetAll = db.getAll(); in main activity is error :(( – APCM Oct 26 '15 at 09:07
  • when i add createDataBase();, I will add exception or surround with try/catch? @Droidwala – APCM Oct 26 '15 at 09:08
  • I don't have ide right now with me...otherwise we could have solved it in few mins..i can do one thing..once i reach my development machine at home..i will try this and get back to you.. – PunitD Oct 26 '15 at 09:14
  • okay sir @Droidwala i appreciate your help. sorry im only newbie to android – APCM Oct 26 '15 at 09:17
  • Np..every expert was once a newbie..this is how we learn!! Happy Coding :) ..I will get back to you soon – PunitD Oct 26 '15 at 09:18
  • thank you sir. I'll wait for your help I still cant solve @Droidwala – APCM Oct 26 '15 at 10:24
  • @GemUbaldo I have implemented exact same code you have provided in the question with the above changes made inside MainActivity file and it is working properly at my end...Try adding those lines inside MainActivity file and let me know if that works... – PunitD Oct 26 '15 at 16:52
  • sir it works already i made only some few changes in createDataBase(). I wanna ask you if why did you use ArrayList instead of List which is in my code above? thanks for your help @Droidwala – APCM Oct 27 '15 at 01:56
  • I have a habit of using it that way..actually it is always better to write it in the way you have define List students = new ArrayList..if you are looking for some good explanation related to this topic you could check this [SO Answer](http://stackoverflow.com/a/9853116/2819262)...Happy Coding :) – PunitD Oct 27 '15 at 09:01