0

I have an activity named Awal.java and the code :

public class Awal extends Activity implements OnItemClickListener {


    private Cursor kategori;
    private MyDatabase db;
    private List<String> ktg;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

            setContentView(R.layout.activity_main);


            db = new MyDatabase(this, null);
            ktg = db.getKategori();



            String namaKtg[] = ktg.toArray(new String[ktg.size()]);

            ListView listView = (ListView) findViewById(R.id.list);
            listView.setAdapter(new ArrayAdapter<String>(this, R.layout.list, R.id.label, namaKtg));
            listView.setOnItemClickListener(this);

    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        kategori.close();
        db.close();
    }

    public void onItemClick(AdapterView<?> adapter, View v, int pos, long l) {

        Intent intent = new Intent(Awal.this,Detail.class);
        intent.putExtra("namaKategori", adapter.getItemAtPosition(pos).toString());
        startActivity(intent);
    }

}

and also databaseHelper named MyDatabase.java and here is the code :

package com.mroring.belajarperancis;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class MyDatabase extends SQLiteOpenHelper {
    // Variable declaration
    private static String DB_PATH = "/data/data/com.mroring.belajarperancis/databases/";
    public static String DB_NAME = "MY_DATABASE";
    private final Context myContext;
    private String strMypath;


    public MyDatabase(Context context, String DB_NAME) {
        super(context, DB_NAME, null, 1);
        this.myContext = context;
        try {
            MyDatabase.DB_NAME = DB_NAME;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void createDatabase() throws IOException {
        try {
            // check if the database exists
            boolean dbExist = checkDatabase();
            if (!dbExist) {
                // database is not present copy databse
                this.getReadableDatabase();
                try {
                    copyDatabse(DB_NAME);
                } catch (IOException e) {
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 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() {
        try {
            File dbFile = new File(DB_PATH + DB_NAME);
            return dbFile.exists();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 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.
     * */
    public void copyDatabse(String DB_NAME) throws IOException {
        try {
            // Open your local db as the input stream
            Input`enter code here`Stream myInput = myContext.getAssets().open(DB_NAME);
            // Path to the just created empty db
            String outFileName = DB_PATH + DB_NAME;
            // 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 * 2];
            int length;
            while ((length = myInput.read(buffer)) > 0) {
                try {
                    myOutput.write(buffer, 0, length);
                } catch (Exception e) {
                }
            }
            if (myOutput != null) {
                myOutput.flush();
                myOutput.close();
            }
            if (myInput != null)
                myInput.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * This function is used to open the database
     * 
     * @throws SQLException
     */
    public void openDatabase() throws SQLException {
        SQLiteDatabase checkDB = null;
        // Open the database
        try {
            strMypath = DB_PATH + DB_NAME;
            checkDB = SQLiteDatabase.openDatabase(strMypath, null,
                    SQLiteDatabase.OPEN_READWRITE);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (checkDB != null) {
            checkDB.close();
        }
    }


        public List<String> getKategori() {
            String query = "SELECT _id FROM kategori";
            List<String> kategori = new ArrayList<String>();

            SQLiteDatabase db = getReadableDatabase();
            Cursor cursor = db.rawQuery(query, null);

            //looping through
            if (cursor.moveToFirst()) {
                do {
                    kategori.add(cursor.getString(0)); // add id & nama
                }
                while (cursor.moveToNext());
            }

            cursor.close();
            db.close();
            return kategori;
        }

        public List<List<String>> getDetail(String namaKategori) {
            String query = "select pra, ina, baca from kata,kategori where kata.id_kategori=kategori._id and kategori.nama = '"+namaKategori+"'";
            List<List<String>> detail = new ArrayList<List<String>>();

            SQLiteDatabase db = getReadableDatabase();
            Cursor cursor = db.rawQuery(query, null);

            //looping
            if (cursor.moveToFirst()) {

                do {
                    List<String> item = new ArrayList<String>();
                    item.add(cursor.getString(0)); //add french word
                    item.add(cursor.getString(1)); //add indonesian word
                    item.add(cursor.getString(2)); //add baca
                    detail.add(item);
                }
                while (cursor.moveToNext());
            }
            cursor.close();
            db.close();
            return detail;
        }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        try {
            copyDatabse(DB_NAME);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
    }

}

And this combination always makes errors and here are the error :

06-18 01:23:01.694: E/AndroidRuntime(17219): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mroring.belajarperancis/com.mroring.belajarperancis.Awal}: android.database.sqlite.SQLiteException: no such table: kategori: , while compiling: SELECT _id FROM kategori
06-18 01:23:01.694: E/AndroidRuntime(17219): Caused by: android.database.sqlite.SQLiteException: no such table: kategori: , while compiling: SELECT _id FROM kategori

I have a database named 'MY_DATABASE' in .../BelajarPerancis/assets/databases/MY_DATABASE and also .../BelajarPerancis/assets/MY_DATABASE (I tried to put the DB in two places).

I have tried to pull the database from DDMS, and it returns the same Database with the same contents/tables and it has table 'Kategori'.

My 'Kategori' table contains the field of '_id' and here is the proof 3 Rows returned from: select nama from kategori; (took 5ms).

CL.
  • 173,858
  • 17
  • 217
  • 259

2 Answers2

0

Are you sure that you create the database?

I say that because you're using a absolute path to get the file of the database, the best thing to do in that case is create a database as the standard of Google.

here is a good answer, of how do that:

How do I create a database in android?

You can check too the name of your table, if you use with the first letter in uppercase you must use in that way all time.

att.

Community
  • 1
  • 1
JVidiri
  • 23
  • 7
0
  1. You are passing database name as null in line db = new MyDatabase(this, null);
  2. I can not see code to create 'kategori' table and in query you are trying to get data from table name as 'kategori' String query = "SELECT _id FROM kategori"; which do not exists..

Change db = new MyDatabase(this, null); to db = new MyDatabase(this, "SOME_DATABASE_NAME");

and then write code to create table in database.

Activity launch is not working because db.getKategori(); is called from onCreate() method and which is throwing exception.

please go through http://www.vogella.com/tutorials/AndroidSQLite/article.html

Hope this helps you !!

aksdch11
  • 683
  • 6
  • 14