0

I have a problem which cannot show listview from my DB sqlite, Log error is : Caused by: android.database.sqlite.SQLiteException: no such table: tb_gejala (code 1): , while compiling: SELECT nama_gejala. In my browser sqlite this query is successfully run. What's wrong with my code??

this is my MainActivity :

MyCustomAdapter dataAdapter = null;
DatabaseHelperInfopenyakit db;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    db = new DatabaseHelperInfopenyakit(this);
    setContentView(R.layout.main_deteksi);
    Button myButton = (Button) findViewById(R.id.button1);
    myButton.setOnClickListener(new OnClickListener() {

       // public AbsListView gejalaList;

        @Override
        public void onClick(View v) {

                StringBuffer responseText = new StringBuffer();
                responseText.append("Gejala Yang dipilih adalah");

                ArrayList<Gejala> gejalaList = dataAdapter.gejalaList;
                for (int i = 0; i < gejalaList.size(); i++) {
                    Gejala gejala = gejalaList.get(i);
                    if (gejala.isSelected()) {
                        responseText.append("\n" + gejala.getName());
                    }
                }

                Toast.makeText(getApplicationContext(), responseText,
                        Toast.LENGTH_SHORT).show();

            }

    });

    displayListView();

}

    // Mendeklarasikan  arraylist gejalaList dan menginisialiasai dengan data dr db


        private ArrayList <Gejala> displayListView() {
            ArrayList<Gejala> gejalaList = new ArrayList<Gejala>();
            SQLiteDatabase sd = db.getReadableDatabase();
            Cursor cursor = sd.rawQuery("SELECT nama_gejala FROM tb_gejala", null);
            cursor.moveToFirst();
            while (!cursor.isAfterLast()) {
                gejalaList.add(new Gejala(cursor.getString(0)));
                cursor.moveToNext();
            }
            cursor.close();



            // Buata array adapter dari data gejalaList

            dataAdapter = new MyCustomAdapter(this, R.layout.gejala_row, gejalaList);

            ListView listView = (ListView) findViewById(R.id.listView1);
            // Assign adapter to ListView
            listView.setAdapter(dataAdapter);

            listView.setOnItemClickListener(new OnItemClickListener() {
                public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                // When clicked, show a toast with the TextView text
                    Gejala gejala = (Gejala) parent.getItemAtPosition(position);
                    Toast.makeText(getApplicationContext(),
                        "Clicked on Row: " + gejala.getName(),
                        Toast.LENGTH_SHORT).show();
                 }
            });
        return gejalaList;
        }



private class MyCustomAdapter extends ArrayAdapter<Gejala> {

    private ArrayList<Gejala> gejalaList;

    public MyCustomAdapter(Context context, int textViewResourceId,
                           List<Gejala> gejalaList) {
        super(context, textViewResourceId, gejalaList);
        this.gejalaList = new ArrayList<Gejala>();
        this.gejalaList.addAll(gejalaList);
    }



    private class ViewHolder {
        TextView id;
        CheckBox name;
    }

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

        ViewHolder holder = null;
        Log.v("ConvertView", String.valueOf(position));

        if (convertView == null) {
            LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = vi.inflate(R.layout.gejala_row, null);

            holder = new ViewHolder();
          //  holder.id = (TextView) convertView.findViewById(R.id.code);
            holder.name = (CheckBox) convertView
                    .findViewById(R.id.checkBox1);
            convertView.setTag(holder);

            holder.name.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    CheckBox cb = (CheckBox) v;
                    Gejala gejala = (Gejala) cb.getTag();
                    Toast.makeText(
                            getApplicationContext(),
                            "Clicked on Checkbox: " + cb.getText() + " is "
                                    + cb.isChecked(), Toast.LENGTH_SHORT)
                            .show();
                    gejala.setSelected(cb.isChecked());
                }
            });
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        Gejala gejala = gejalaList.get(position);
       // holder.id.setText(" (id:" + gejala.getId() + ")");
        holder.name.setText(gejala.getName());
        holder.name.setChecked(gejala.isSelected());
        holder.name.setTag(gejala);
        return convertView;
    }
}

This is my DatabaseHelperInfoPenyakit :

private static String DB_PATH = "";

    private static String DB_NAME = "sistempakar.sqilte3";

    private SQLiteDatabase myDataBase;

    private final Context myContext;

    /**
     * Constructor
     * Takes and keeps a reference of the passed context in order to access to the application assets and resources.
     * @param context
     */
    public DatabaseHelperInfopenyakit(Context context) {

        super(context, DB_NAME, null, 1);
        this.myContext = context;
        DB_PATH= myContext.getDatabasePath(DB_NAME).toString();
    }

    /**
     * Creates a empty database on the system and rewrites it with your own database.
     * */
    public void createDataBase() throws IOException{

        boolean dbExist = checkDataBase();
        SQLiteDatabase db_Read = null;
        if(dbExist){
            //do nothing - database already exist
        }else{

            //By calling this method and empty database will be created into the default system path
            //of your application so we are gonna be able to overwrite that database with our database.
            db_Read = this.getReadableDatabase();
            db_Read.close();

            try {

                copyDataBase();

            } catch (IOException e) {

                throw new Error("Error copying database");

            }

        }

    }

    /**
     * Check if the database already exist to avoid re-copying the file each time you open the application.
     * @return true if it exists, false if it doesn't
     */
    private boolean checkDataBase(){
     //  this.getReadableDatabase();

        SQLiteDatabase checkDB = null;

        try{
            String myPath = DB_PATH ;
            checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

        }catch(SQLiteException e){

            //database does't exist yet.

        }

        if(checkDB != null){

            checkDB.close();

        }

        return checkDB != null ? true : false;
    }

    /**
     * Copies your database from your local assets-folder to the just created empty database in the
     * system folder, from where it can be accessed and handled.
     * This is done by transfering bytestream.
     * */
    private void copyDataBase() throws IOException{

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

        // Path to the just created empty db
        String outFileName = DB_PATH ;

        //Open the empty db as the output stream
        OutputStream myOutput = new FileOutputStream(outFileName);

        //transfer bytes from the inputfile to the outputfile
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer))>0){
            myOutput.write(buffer, 0, length);
        }

        //Close the streams
        myOutput.flush();
        myOutput.close();
        myInput.close();

    }

    public void openDataBase() throws SQLException{

        //Open the database
        String myPath = DB_PATH ;
        myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

    }

    @Override
    public synchronized void close() {

        if(myDataBase != null)
            myDataBase.close();

        super.close();

    }

    @Override
    public void onCreate(SQLiteDatabase db) {

    }
  @Override
 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
   if (newVersion>oldVersion){
  try {
      copyDataBase();
     } catch (IOException e) {
      e.printStackTrace();
      } 
    }

    }
    }
12
  • you need to create your sqlite database first before running query on it. Commented Jul 23, 2017 at 6:42
  • The DB helper class is wrong. You should have used SQLiteAssetHelper. Commented Jul 23, 2017 at 6:55
  • @MehranZamani how to do it? I am newbie Commented Jul 23, 2017 at 7:26
  • String CREATE_MESSAGES_TABLE = "CREATE TABLE " + TABLE_NAME + "(" + ID + " INTEGER PRIMARY KEY," + Title + " TEXT," + BODY + " TEXT)"; db.execSQL(CREATE_MESSAGES_TABLE); Commented Jul 23, 2017 at 7:29
  • @CL. So I must update my DBhelper class using SQLiteAssetHelper? Commented Jul 23, 2017 at 7:29

1 Answer 1

0

I guess u might have resolved this issue, but i would like to provide solution to help others facing this issue

Issue: U might have used a different name for DB_TABLE initially, So while installing an update android doesn't delete app data including DB's.(OnUpgrade u are just copying existing DB)

Simple Solution: Uninstall existing application and reinstall it.

Complex Solution: Add logic within DBManager to create DB_Table if it doesn't exists

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.