-2

it's my first time to using stackoverflow.com to posting a question. For my questions that concern me is that I got an error whenever I click on this page. The coding is perfectly fine without any problem when I tested it on the new activity, but when I test on my final year project, which I doing currently for my client's needs, and it crashes every time I click on that activity page. I'm new to the android studio and not familiar with android studio much. Hope you guys can solve this problem, thank you so much! Here are my coding and errors so far:

Logcat error:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.student.amanvilleapp, PID: 5722
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.student.amanvilleapp/com.example.student.amanvilleapp.event}: android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)                                                                      
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
Caused by: android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
at android.database.sqlite.SQLiteConnection.nativeOpen(Native Method)
at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:209)
at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:193)
at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)
at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)
at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)
at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:808)
at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:793)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:696)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:671)
at com.example.student.amanvilleapp.DBMain.openDB(DBMain.java:114)
at com.example.student.amanvilleapp.event.onCreate(event.java:76)
at android.app.Activity.performCreate(Activity.java:6662)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756) 

event.java:

public class event extends AppCompatActivity {
    String DB_PATH;
    final Context context=this;
    private SQLiteDatabase mDataBase;
    private static String DB_NAME ="Banking.db";
    TextView txt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_event);
        Toolbar myToolbar = (Toolbar) findViewById(R.id.toolbar);
        myToolbar.setTitle("EVENTS & NEWS");
        setSupportActionBar(myToolbar);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txt=(TextView)findViewById(R.id.txt);

        DBMain db;
        db = new DBMain(this);

        try {
            db.createDB();
        } catch (IOException ioe) {
            throw new Error("Database not created....");
        }
        try {
            db.openDB();
        }catch(SQLException sqle){
            throw sqle;
        }

        SQLiteDatabase db1;
        db1=openOrCreateDatabase("Banking",SQLiteDatabase.CREATE_IF_NECESSARY,null);
        Cursor c= db1.rawQuery("SELECT * FROM bank",null);

        c.moveToFirst();
        String temp="";

        while(! c.isAfterLast())
        {
            String s2=c.getString(0);
            String s3=c.getString(1);
            String s4=c.getString(2);
            temp=temp+"\n Id:"+s2+"\tType:"+s3+"\tBal:"+s4;

            c.moveToNext();
        }
        txt.setText(temp);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu2, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.home:
                Intent intent = new Intent();
                intent.setClass(event.this, MainActivity.class);
                event.this.startActivity(intent);
                return true;

            case R.id.about:
                Intent intent1 = new Intent();
                intent1.setClass(event.this, aboutus.class);
                event.this.startActivity(intent1);
                return true;

            case R.id.pricing:
                Intent intent3 = new Intent();
                intent3.setClass(event.this, pricing.class);
                event.this.startActivity(intent3);
                return true;

            case R.id.contact:
                Intent intent4 = new Intent();
                intent4.setClass(event.this, contact.class);
                event.this.startActivity(intent4);
                return true;

            case R.id.rateus:
                Intent intent5 = new Intent();
                intent5.setClass(event.this, rateus.class);
                event.this.startActivity(intent5);
                return true;

            case R.id.aboutapp:
                LayoutInflater factory = LayoutInflater.from(event.this);
                final View view = factory.inflate(R.layout.aboutapp, null);

                AlertDialog alertDialog = new AlertDialog.Builder(this).create();
                alertDialog.setTitle("About This App");
                alertDialog.setMessage("App Version: 1.0" + "\n" + "\n"
                        + "App name: AmanVilleApp" + "\n" + "\n" + "This app is design by Jasper Koay Chin Loong for Sentral College Penang's Final Year Project.");
                alertDialog.setButton("OK", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        //TODO Auto-generated method stub
                    }
                });
                alertDialog.show();
                return true;

            case R.id.exit:
                moveTaskToBack(true);
                android.os.Process.killProcess(android.os.Process.myPid());
                System.exit(1);

            default:
                return super.onOptionsItemSelected(item);
        }
    }
}

DBMain.java

public class DBMain extends SQLiteOpenHelper {
    private static String DB_PATH=             
    "data/data/com.example.dbimportfin/databases/";
    private static String DB_NAME = "Banking";
    private SQLiteDatabase dbObj;
    private final Context context;

    public DBMain(Context context) {
        super(context,  DB_NAME , null, 3);
        this. context  = context;
    }

    public void createDB() throws IOException {
        this.getReadableDatabase();
        Log.i("Readable ends....................","end");

        try {
            copyDB();
            Log.i("copy db ends....................","end");
        } catch (IOException e) {
            throw new Error("Error copying database");
        }
    }

    private boolean checkDB(){
        SQLiteDatabase checkDB = null;

        try{
            String path = DB_PATH + DB_NAME;
            Log.i("myPath ......",path);
            checkDB = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);

            Log.i("myPath ......",path);
            if (checkDB!=null)
            {
                Cursor c= checkDB.rawQuery("SELECT * FROM bank", null);
                Log.i("Cursor.......",c.getString(0));
                c.moveToFirst();
                String contents[]=new String[80];
                int flag=0;

                while(! c.isAfterLast())
                {
                    String temp="";
                    String s2=c.getString(0);
                    String s3=c.getString(1);
                    String s4=c.getString(2);

                    temp=temp+"\n Id:"+s2+"\tType:"+s3+"\tBal:"+s4;
                    contents[flag]=temp;
                    flag=flag+1;
                    Log.i("DB values.........",temp);
                    c.moveToNext();
                }
            }
            else
            {
                return false;
            }

        }catch(SQLiteException e){
            e.printStackTrace();
        }

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

        return checkDB != null ? true : false;
    }

    public void copyDB() throws IOException{
        try {
            Log.i("inside copyDB....................","start");
            InputStream ip =  context.getAssets().open(DB_NAME+".db");
            Log.i("Input Stream....",ip+"");
            String op=  DB_PATH  +  DB_NAME ;
            OutputStream output = new FileOutputStream( op);
            byte[] buffer = new byte[1024];
            int length;

            while ((length = ip.read(buffer))>0){
                output.write(buffer, 0, length);
                Log.i("Content.... ",length+"");
            }
            output.flush();
            output.close();
            ip.close();
        }
        catch (IOException e) {
            Log.v("error", e.toString());
        }
    }

    public void openDB() throws SQLException {
        String myPath = DB_PATH + DB_NAME;
        dbObj = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
        Log.i("open DB......",dbObj.toString());
    }

    @Override
    public synchronized void close() {
        if(dbObj != null)
            dbObj.close();
        super.close();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
    }

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

The activity that should show like this

And this is the image that I put my code on the existing project I created not long ago

This is the reference link I took from and make a test

Ram Koti
  • 2,203
  • 7
  • 26
  • 36
LeUsher
  • 13
  • 3

1 Answers1

1

Adding in Manifest might not work for API 23 and above. Request for permission while running the application:

Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app. This approach streamlines the app install process, since the user does not need to grant permissions when they install or update the app.

String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
        requestPermissions(permissions, WRITE_REQUEST_CODE);

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
       case WRITE_REQUEST_CODE:
         if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
           //Permission granted.
           //Continue with writing files...
         }
       else{
           //Permission denied.
         }
        break;
    }
}

Also set DB_PATH for creating the database.

SQLiteDatabase.openDatabase(DB_PATH + "\" + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE);
Gokul Nath KP
  • 15,485
  • 24
  • 88
  • 126