Android Studio SQLite Database Multiple Tables Example

Tan Woon How

He is a learner and know little around .Net and Java. He learned and share if you see his mistake... feel free to comment and laugh at him... and also please help to correct him.

You may also like...

  • HawkServ

    Hi, Thanks for the wonderful tutorial. I could successfully run this. However, when i tried to display the output to a new layout page, i can’t get it right. 😀 any suggestion? i am new to android. i wanted to display each output to a new page/layout.

  • Chirag Tolani

    Hi, actually im trying to make an app where the user decides what table , what sort of database he wants to create. Basically an app which helps the user to create his database in his own way. But it seems like we need a defined database and a table for SQLite if im not wrong. Is there any way i can achieve user-generated databases and tables in my app? Please do suggest 🙂

  • Pingback: IllegalStateException: unable to start Activity ComponentInfo – Android Apps Development()

  • Padma Priya

    Iam getting error unable to start a activity.This is my Logcat

    Process: com.example.madhu.samplec, PID: 20957
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.madhu.samplec/com.example.madhu.samplec.mtcresult}: java.lang.IllegalStateException: BusDataManager is not initialized, call initializeInstance(..) method first.
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2279)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2329)
    at android.app.ActivityThread.access$800(ActivityThread.java:145)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:136)
    at android.app.ActivityThread.main(ActivityThread.java:5214)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:814)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:630)
    at dalvik.system.NativeStart.main(Native Method)
    Caused by: java.lang.IllegalStateException: BusDataManager is not initialized, call initializeInstance(..) method first.
    at com.example.madhu.samplec.BusDataManager.getInstance(BusDataManager.java:26)
    at com.example.madhu.samplec.Bus_StageRepo.getStage(Bus_StageRepo.java:60)
    at com.example.madhu.samplec.mtcresult.displaylistview(mtcresult.java:537)
    at com.example.madhu.samplec.mtcresult.onCreate(mtcresult.java:293)
    at android.app.Activity.performCreate(Activity.java:5231)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2243)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2329)
    at android.app.ActivityThread.access$800(ActivityThread.java:145)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:136)
    at android.app.ActivityThread.main(ActivityThread.java:5214)
    at java.lang.reflect.Method.invokeNative(Native Method)

    Why are you declaring “is not initialized, call initializeInstance(..) method first.” in getinstance() function ???? Please solve my problem

    • Tan Woon How

      Hi,
      I’m not truly sure what is your errors, but i guess you’re not configure “App” in your AndroidManifest.xml in step 10?

      • Padma Priya

        I declared app class too in manifest file..can u suggest some other way to execute or give some snippet ..please help me out thanks

        • Tan Woon How

          Its look to me busdatamanager not initialized. One way to find out you set break point on the App.java file when you run you code in debug mode.

          We have other simple follow tutorial please refer this link http://instinctcoder.com/android-studio-sqlite-database-example/

          • Padma Priya

            Ya I didn’t initialize DatabaseManager.initializeInstance(new DatabaseHelper()) in my app.If I have to do where I should do it.Iam new to Android and sqlite,sorry to ask silly doubts

          • Tan Woon How

            You need to make sure you setup correctly in AndroidManifest.xml file if you like to follow this tutorial or else i advise to understand the basic first by visit the link i provided earlier.

          • Padma Priya

            Sorry I made a mistake in initializing app.java in manifest …thanks for ur help

          • Tan Woon How

            Great! Do you mind to tell us what mistake you made so if next time others readers facing the same issue know what happened . Thanks .

          • Padma Priya

            Misspelled the word app.java in manifest

  • Sergey Blogpost

    Exellent!

  • Vinay

    Good work ! nice structure

    • Tan Woon How

      Thanks.

  • bayu

    Hi, it is clear step by step tutorial, but how if we are using external Database, are we still need to create the dtabase using DBHelper, or we just need to connecting it with our app? if yes how i can do that, in which folder i need to store my database?

    • Tan Woon How

      When you said external. Do you mean by outside the app or database locate at the server?

      • bayu

        i meant, i created database using sqlite manager in firefox, and then imported to my app in android studion, is there any tutorial how to do that, especialy to read or query in android studio, thx

        • Tan Woon How

          I have not tried the import way, but i think it should be the same. You could use this tutorial as the example for your work. Just curious why don’t let sqliteDatabse to handler the creation of the table like in the onCreate function of DBHelper.java?

          This is the recommend way for you reference which i think it should be work.
          1. Import the predefined database – you could refer to this link http://instinctcoder.com/how-to-browse-android-studio-emulator-sqlite-database/. It guided you on browse database but the import function is in there. So should be easy.

          2. Refer to this tutorial but omit the onCreate and onUpgrade function in DBHelper.java. the rest should be work the same.

  • Bestami Kuloğlu

    I copied ur all class but ı got this error. I tried to something but i can not solve.. Can u help me ??

    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.suleymansahin.sqlitedbmultitbl/com.example.suleymansahin.sqlitedbmultitbl.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method ‘android.database.sqlite.SQLiteDatabase android.database.sqlite.SQLiteOpenHelper.getWritableDatabase()’ on a null object reference

    • Tan Woon How

      Hi
      It seem to me you didn’t initialize your database connection. In your project did you did something like what I did in app.java from line 14 to 22?

      I not sure you copy the whole project but if you like to follow you must change the startup file you need to change the AndroidManifest.xml. check the line 6.

      Good luck

  • Wayweary

    im i correct to assume that you are not running your database operations in a separate thread? Why then did you implement dmytrodanylyk solution? Is it not necessary to do them not on the UI? Would dmytrodanylyk aproach of doing this ( DatabaseManager.getInstance().executeQuery(new QueryExecutor() {.) be good, or should one use an AsynTack or use a ContentProvidor with LoaderCallbacks? Maybe you have an article on this?

    Really good article btw, easy to read and understand

    • Tan Woon How

      Would you think is better you ask him :)? As i’m not implement his solution and not tried before anyway thanks for dropping by.

      • Wayweary

        I saw that you responds to comments, so i thought i would give it a go :). I will email him and ask. But i will try to test his code too when i get home, maybe google improved the connection to the database so his solution wouldnt be needed anymore, will see soon :D..

        But my thought about threading still stand. I dont see that u made any such implementation when operating the db, but i might have missed it? If not, than that could be an improvement to this otherwise well implemented solution.

        • Wayweary

          Said and done. Dmytro answered very fast and his implementation is still usefull. Even tested it myself to see it in action. Made a youtube video of it so anyone interested can see for themself
          , https://github.com/wayweary/TestConcurrentDb (unfortunately i had no time to clean up the code, its mostly copy n paste from Dmytro with the addition of a GUI to execute the db operations)

          • Tan Woon How

            Mind to share, what type of application you trying to do. Because i haven’t have a chance to work in heavily db process app that needed to work on separate thread. and thanks for sharing.

          • Wayweary

            It might be complete overkill to do CRUD operations in a different thread. But since you implemented a thread safe solution in this tutorial i just thought it strange that all operations where on the main thread. Having multiple tables, joins will probably be necessary, those operations would probably be better off in a separate thread though.

            Im making an inventory application. But im mostely thinking about best practises and im not really sure if the best practises are to make all db operations in a different thread. That is what im trying to figure out ;D.

          • Tan Woon How

            This is something out of topic from this tutorial, If you are working with inventory application, i guess your app may need deal with a lot of data, and if i were you, i’ll try look at realm, better performance database to work with, try it out. https://realm.io/ .
            Good luck.

          • Wayweary

            Thanks, will look into that

  • Wayweary

    What does dmytrodanylyk mean by “Concurrent Database Access @Depricated”. Is it not thread safe anymore?

  • Ahmad Muzzammil

    How did i make the database from excel? sorry new here

    • Tan Woon How

      Sorry new to me too!!!
      I not sure what you try to achieve. May be could you elaborate a little more? 🙂

      • Ahmad Muzzammil

        i wanna make app with search box and could search from database that i make. when i search the result display a detail view of keyword that previously i search. So, how can i make these database that contain column and row ? And how to make the result display a detail view?

        • Tan Woon How

          Hmmm. sound similiar to me just that in my tutorial is lack of search function, would that be fine for you to get your hand warm by study this? instinctcoder.com/android-studio-sqlite-database-example/

          • Ahmad Muzzammil

            Well if i just want to read the detail without be able to change it, how can i make like that? and can i modify the .db file?

          • Tan Woon How

            If you don’t want to change database content then just dont do update and insert query.

            What do you mean by modify .db file ?

          • Ahmad Muzzammil

            If someday i want update the database, how can i do that? I want the database from excel. I have a lot of data to be database.

          • Tan Woon How

            If I understand you correctly you want to creaye app that read data from excel and import into sqlite for viewing purposes ? If yes. I not try Excel sdk before so not sure how to do it.

          • Ahmad Muzzammil

            Well is there anyway to make an app that has functioin read data have a big size? should i write the code completely one by one? its a very much data. Thank you.

          • Tan Woon How

            For reading part im not sure as i have no try on excel sdk before. For writing part you could use transaction like point 5 execute 2 statements at the same time. Meaning you construct all insert query at 1 time and execute. This way will be faster.

          • Ahmad Muzzammil

            no. forget the excel, i just want make an app that function with search and the result is detailview by what im searching for. Can you help me? Thank you

          • Ahmad Muzzammil

            well i want app with data from json that locate inside the app and there is searchview in the main screen

  • Nor Hanis

    why i got error cannot resolve method createTable() in dbhelper.java ?

    • Tan Woon How

      I guess is because of your class for the table not valid? Do you debug?

      • Nor Hanis

        Which one is class for table? Yes I debug already. I’m so sorry I’m still new to Android. I’m sorry if I have so many questions to you I hope I can learn from you.

        • Tan Woon How

          Err…set a break point and run in debug mode see which line cause error.

          • Nor Hanis

            i just follow your tutorial 100% but i got error on create table i dont know why

          • Tan Woon How

            Hi Morning!

            Try to find which line cause the error. Your given error message is too general. I can’t give you suggestion base on this. So you got which line hit you with error? And sorry to ask you know how to do step-by-step (F7) debugging?

            ANd also i check the image you given i saw you got this function in your class (create_Table_initial, sorry forgot the exact name, my com block FB) but not in the dbHelper.java. Please check again and make sure you have the correct function name.

          • Nor Hanis

            i managed to create the function createTable. but now i want to know repo file that you created is that for the database?

          • Tan Woon How

            Hooray!!! Party time. 🙂 Yes, all related query will be place in this package.

          • Nor Hanis

            so for example my apps have many sections (1,2,3,4,5,6,7) and in different screen. lets say that i want to create 4 tables in my database for my apps so my repo file gonna be my tables name is it?

          • Tan Woon How

            Hi,
            This is somehow depend on how you like to categorize the file. doesn’t mean you need to have different file for each table. So is up to you. For me, i like the direct query that relate to table( like insert,update,delete selectall, getbyid.) group into 1 class, and if let say in case there is some query that involve more than 1 table so group it in some other class.

          • Nor Hanis

            now i get error when trying to create my table name. when i point my cursor it shows cannot resolve symbol

          • Tan Woon How

            Thanks for your cooperation, as mentioned in chat. You class name of your table need to import into this class and also is case sensitive

          • Nor Hanis

            can I create other activity for ui under the same package with main activity?

          • Tan Woon How

            Yes. you can. Why not? In term of best practice, we normally group things that are relate into same package. It’s just made thing organized and you know where to find the file.

          • Nor Hanis

            yes I did already but when I try to debug I got this. is this normal? https://uploads.disquscdn.com/images/fc294cb3d1b761f525e27ce7986278cb46ae3be5c0cbe44cdce7640ae70adaa1.png

          • Tan Woon How

            Something is wrong with your environment. 1 hour, is either your machine is too slow, or, setting got issue. which i not sure.

          • Nor Hanis

            the emulator took 1 hour to display and until now it still shows black screen.

        • Tan Woon How

          Can you make sure the function createTable is in the function?

  • Seemanta Bhowmick

    Thanks admin for the amazing work your doing, by helping new android developers like me out with such detailed projects. Highly appreciate it buddy.