android - copy database from assets to phone and access that -


i creating database in sqlitebrowser. copy database file manually converting .sqlite format , copy assets->databases->(file) . , try access it, not able so.

my database code

public class data extends sqliteopenhelper {   sqlitedatabase databaseobject;         static string db_path = "/data/data/vishesh.goswami.ithinkk/databases/";         static string db_name = "project_db.sqlite";         sqlitedatabase db;        private  context mcontext=null;            static int l=1;         static string database_name="project_db.sqlite";         string getquestion=null;         data(context context)          {              super(context, database_name, null, l);              this.mcontext=context;         }        public void createdatabase() throws ioexception {             boolean mdatabaseexist = checkdatabase();             if (!mdatabaseexist) {                 this.getreadabledatabase();                 try {                     copydatabase();                 } catch (ioexception mioexception) {                     mioexception.printstacktrace();                     throw new error("error copying database");                 } {                     this.close();                 }             }         }          /** method checks whether database exists or not **/         private boolean checkdatabase() {             try {                 final string mpath = db_path + db_name;                 db=sqlitedatabase.opendatabase(mpath, null,sqlitedatabase.open_readonly);                  // file file = new file(mpath);                 //if (file.exists())                   //  return true;                // else                  //   return false;             } catch (sqliteexception e) {                 e.printstacktrace();                 return false;             }             if(db!=null){                 db.close();             }             return db!=null?true :false;         }          /**          * method copy database /assets directory application          * package /databases directory          **/         private void copydatabase() throws ioexception {             try {                  inputstream minputstream = mcontext.getassets().open(db_name);                 string outfilename = db_path + db_name;                 outputstream moutputstream = new fileoutputstream(outfilename);                 byte[] buffer = new byte[1024];                 int length;                 while ((length = minputstream.read(buffer)) > 0) {                     moutputstream.write(buffer, 0, length);                 }                 moutputstream.flush();                 moutputstream.close();                 minputstream.close();             } catch (exception e) {                 e.printstacktrace();             }         }          /** method open database operations **/         public boolean opendatabase() throws sqlexception {             string mpath = db_path + db_name;             databaseobject = sqlitedatabase.opendatabase(mpath, null,                     sqlitedatabase.open_readwrite);             return databaseobject!=null;         }          /** method close database connection , released occupied memory **/         @override         public synchronized void close() {             if (databaseobject != null)                 databaseobject.close();             sqlitedatabase.releasememory();             super.close();         }         @override     public void oncreate(sqlitedatabase arg0) {          string query="create table if not exists data (id integer primary key autoincrement, "              + "question text , option1 text ,option2 text ,option3 text,option4 text )"; 

my testactivity code is

public class testactivity extends activity {  data object,projectobject; sqlitedatabase mydatabase; textview t; @override protected void oncreate(bundle savedinstancestate) {     super.oncreate(savedinstancestate);     setcontentview(r.layout.activity_test);     object =new data(this);     object.open();             t=(textview) findviewbyid(r.id.textview1);     t.settext("ques."+ " " + object.fetchquestion(1));       projectobject = new data(this);          try{           projectobject.createdatabase();       }       catch(ioexception e)       {           toast.maketext(getbasecontext(),"it not  worked11"+e.getmessage(), toast.length_short ).show();        }           try{           projectobject.opendatabase();            mydatabase=projectobject.getreadabledatabase();           projectobject.close();        }       catch(exception e){           toast.maketext(getbasecontext(),"it not  worked2222"+e.getmessage(), toast.length_short ).show();        }       object.close1(); } 

but app stops : unfortunately showing unable fetch database. using icecream sandwich 4.0.4 appreciated. logcat :

07-22 17:32:18.583: d/jdwp(21577): sendbufferedrequest : len=0x45 07-22 17:32:18.800: d/activitythread(21577): bind_application handled : 0 / appbinddata{appinfo=applicationinfo{418495f0 vishesh.goswami.ithinkk}} 07-22 17:32:19.248: d/androidruntime(21577): shutting down vm 07-22 17:32:19.249: w/dalvikvm(21577): threadid=1: thread exiting uncaught exception (group=0x40f3d258) 07-22 17:32:19.289: e/androidruntime(21577): fatal exception: main 07-22 17:32:19.289: e/androidruntime(21577): java.lang.runtimeexception: unable start activity componentinfo{vishesh.goswami.ithinkk/vishesh.goswami.ithinkk.testactivity}: java.lang.nullpointerexception 07-22 17:32:19.289: e/androidruntime(21577):    @ android.app.activitythread.performlaunchactivity(activitythread.java:2077) 07-22 17:32:19.289: e/androidruntime(21577):    @ android.app.activitythread.handlelaunchactivity(activitythread.java:2104) 07-22 17:32:19.289: e/androidruntime(21577):    @ android.app.activitythread.access$600(activitythread.java:134) 07-22 17:32:19.289: e/androidruntime(21577):    @ android.app.activitythread$h.handlemessage(activitythread.java:1247) 07-22 17:32:19.289: e/androidruntime(21577):    @ android.os.handler.dispatchmessage(handler.java:99) 07-22 17:32:19.289: e/androidruntime(21577):    @ android.os.looper.loop(looper.java:154) 07-22 17:32:19.289: e/androidruntime(21577):    @ android.app.activitythread.main(activitythread.java:4624) 07-22 17:32:19.289: e/androidruntime(21577):    @ java.lang.reflect.method.invokenative(native method) 07-22 17:32:19.289: e/androidruntime(21577):    @ java.lang.reflect.method.invoke(method.java:511) 07-22 17:32:19.289: e/androidruntime(21577):    @ com.android.internal.os.zygoteinit$methodandargscaller.run(zygoteinit.java:809) 07-22 17:32:19.289: e/androidruntime(21577):    @ com.android.internal.os.zygoteinit.main(zygoteinit.java:576) 07-22 17:32:19.289: e/androidruntime(21577):    @ dalvik.system.nativestart.main(native method) 07-22 17:32:19.289: e/androidruntime(21577): caused by: java.lang.nullpointerexception 07-22 17:32:19.289: e/androidruntime(21577):    @ vishesh.goswami.ithinkk.data.oncreate(data.java:127) 07-22 17:32:19.289: e/androidruntime(21577):    @ android.database.sqlite.sqliteopenhelper.getwritabledatabase(sqliteopenhelper.java:165) 07-22 17:32:19.289: e/androidruntime(21577):    @ vishesh.goswami.ithinkk.data.open(data.java:149) 07-22 17:32:19.289: e/androidruntime(21577):    @ vishesh.goswami.ithinkk.testactivity.oncreate(testactivity.java:22) 07-22 17:32:19.289: e/androidruntime(21577):    @ android.app.activity.performcreate(activity.java:4479) 07-22 17:32:19.289: e/androidruntime(21577):    @ android.app.instrumentation.callactivityoncreate(instrumentation.java:1050) 07-22 17:32:19.289: e/androidruntime(21577):    @ android.app.activitythread.performlaunchactivity(activitythread.java:2041) 07-22 17:32:19.289: e/androidruntime(21577):    ... 11 more 

try following link may because helpful me

database not copying assets

edit

try databasehelper class user jaydeep has used in answer database not copying assets

public class databasehelper extends sqliteopenhelper{ private context mycontext;  private string db_path = "/data/data/gr.peos/databases/"; //private string db_path = mycontext.getapplicationcontext().getpackagename()+"/databases/"; private static string db_name = "blib.sqlite";//the extension may .sqlite or .db public sqlitedatabase mydatabase; /*private string db_path = "/data/data/"                             + mycontext.getapplicationcontext().getpackagename()                             + "/databases/";*/  public databasehelper(context context) throws ioexception  {     super(context,db_name,null,1);     this.mycontext=context;     boolean dbexist = checkdatabase();     if(dbexist)     {         //system.out.println("database exists");         opendatabase();      }     else     {         system.out.println("database doesn't exist");     createdatabase();     }  }  public void createdatabase() throws ioexception{     boolean dbexist = checkdatabase();     if(dbexist)     {         //system.out.println(" database exists.");     }     else{         this.getreadabledatabase();     try{             copydatabase();         }         catch(ioexception e){             throw new error("error copying database");         }     } } private boolean checkdatabase() {     //sqlitedatabase checkdb = null;     boolean checkdb = false;     try{         string mypath = db_path + db_name;         file dbfile = new file(mypath);         //checkdb = sqlitedatabase.opendatabase(mypath,null,sqlitedatabase.open_readwrite);         checkdb = dbfile.exists();     }     catch(sqliteexception e){         system.out.println("database doesn't exist");     }      return checkdb; } private void copydatabase() throws ioexception {      //open local db input stream     inputstream myinput = mycontext.getassets().open(db_name);      // path created empty db     string outfilename = db_path + db_name;      //open empty db output stream     outputstream myoutput = new fileoutputstream("/data/data/gr.peos/databases/blib.sqlite");      // transfer byte inputfile outputfile     byte[] buffer = new byte[1024];     int length;     while ((length = myinput.read(buffer))>0)     {         myoutput.write(buffer,0,length);     }      //close streams     myoutput.flush();     myoutput.close();     myinput.close();  }  public void opendatabase() throws sqlexception {     //open database     string mypath = db_path + db_name;     mydatabase = sqlitedatabase.opendatabase(mypath, null, sqlitedatabase.open_readwrite);  }    public synchronized void close(){     if(mydatabase != null){         mydatabase.close();     }     super.close(); } 

also, note there difference in approach , approach used jaydeep. also, before accessing database using open() method, need call createdatabase() method. maybe can resolve issue.


Comments

Popular posts from this blog

Fail to load namespace Spring Security http://www.springframework.org/security/tags -

sql - MySQL query optimization using coalesce -

unity3d - Unity local avoidance in user created world -