Thursday, 15 October 2015

Android: Connect with sqlite and perform create, select, delete, update and insert operations

Most of your android app will have to store data locally and this tutorial provides you with all relevant information needed to connect your android app with sqlite database so that you could store and retrieve your data and this might be the simplest way to connect with sqlite and perform the CRUD operations.



Java:
 SQLiteDatabase mydb;  
     private static String DBNAME = "MyDatabase";    
 //Perform Create, Insert, Update and delete Operations:  
     try {  
         mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);  
         mydb.execSQL("<PLACE YOUR QUERY HERE TO CREATE DB,DELETE,INSERT AND UPDATE >");  
         mydb.close();  
         Toast.makeText(getApplicationContext(),”Operation Success!", Toast.LENGTH_LONG).show();  
       } catch (Exception e) {  
             Log.d("error", e.toString());  
                   }  
 //Perform Select Operation:  
 public void loadData(){  
     try {  
         mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);  
         Cursor allrows = mydb.rawQuery("SELECT * FROM ITEMS ", null);  
         if (allrows.moveToFirst()) {  
             do {  
                 String item = allrows.getString(1);//here 1 is the column index in your db  
                 double price = allrows.getDouble(2);  
                 adapter.  
             } while (allrows.moveToNext());  
         }  
     } catch (Exception e) {  
         // TODO: handle exception  
     }  
 }  

No comments:

Post a Comment