致命异议:主要在Android Studio上

时间:2018-03-15 04:31:31

标签: android sqlite android-studio

这是我第一次使用stackoverflow.com发布问题。我关心的问题是,每当我点击此页面时出现错误。当我在新活动上测试它时,编码完全正常没有任何问题,但是当我测试我的最后一年项目时,我目前正在为客户的需求进行测试,并且每次点击该活动页面时它都会崩溃。我是android工作室的新手,对android studio不熟悉。希望你们能解决这个问题,非常感谢你们!到目前为止,这是我的编码和错误:

Logcat错误:

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

1 个答案:

答案 0 :(得分:1)

添加Manifest可能不适用于API 23及更高版本。运行应用程序时请求许可:

  

从Android 6.0(API级别23)开始,用户授予权限   应用程序运行时的应用程序,而非安装应用程序时的应用程序。这个   方法简化了应用安装过程,因为用户没有   需要在安装或更新应用时授予权限。

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;
    }
}

还设置DB_PATH以创建数据库。

SQLiteDatabase.openDatabase(DB_PATH + "\" + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE);