Cara Load Data dari Database Sqlite di Android

hola bray ketemu lagi sama saya danang ganteng aka dananx dpapayas :3 … kali ini saya mau bagi bagi ilmu nih tentang cara load data dari Database Sqlite di android caranya susah susah gampang sih :3 tapi tutorial yang saya share ini kurang fleksibel soalnya masih newbie nih :3
ya udah deh langsung aje ye

1. Create New Project

2. Buat Class MainActivity.java

1:  package com.dananx.papayas.sqlitenew;  
2:  import android.os.Bundle;  
3:  import android.app.Activity;  
4:  import android.content.Intent;  
5:  import android.view.View;  
6:  import android.widget.AdapterView;  
7:  import android.widget.AdapterView.OnItemClickListener;  
8:  import android.widget.ArrayAdapter;  
9:  import android.widget.ListView;  
10:  public class MainActivity extends Activity {  
11:       private String[] items = { "Gedang",  
12:                 "Cilok" };  
13:       private ListView list1;  
14:       @Override  
15:       public void onCreate(Bundle savedInstanceState) {  
16:            super.onCreate(savedInstanceState);  
17:            setContentView(R.layout.activity_main);  
18:            list1 = (ListView) findViewById(R.id.listView1);  
19:            list1.setAdapter(new ArrayAdapter<String>(this,  
20:                      android.R.layout.simple_list_item_1, items));  
21:            list1.setOnItemClickListener(new OnItemClickListener() {  
22:                 @Override  
23:                 public void onItemClick(AdapterView<?> parent, View view,  
24:                           int position, long id) {  
25:                      switch (position) {  
26:                      case 0:  
27:                           Intent first = new Intent(MainActivity.this,  
28:                                     First.class);  
29:                           startActivity(first);  
30:                           break;  
31:                      case 1:  
32:                           Intent second = new Intent(MainActivity.this,  
33:                                     Second.class);  
34:                           startActivity(second);  
35:                           break;  
36:                      }  
37:                 }  
38:            });  
39:       }  
40:  }  

3. Buat Class ExternalDbOpenHelper.java untuk mengontrol databasenya

1:  package com.dananx.papayas.sqlitenew;  
2:  import java.io.FileOutputStream;  
3:  import java.io.IOException;  
4:  import java.io.InputStream;  
5:  import java.io.OutputStream;  
6:  import android.content.Context;  
7:  import android.database.SQLException;  
8:  import android.database.sqlite.SQLiteDatabase;  
9:  import android.database.sqlite.SQLiteException;  
10:  import android.database.sqlite.SQLiteOpenHelper;  
11:  public class ExternalDbOpenHelper extends SQLiteOpenHelper {  
12:       private static String DB_PATH = "/data/data/com.dananx.papayas.sqlitenew/databases/";  
13:       private static String DB_NAME = "cobadb.sqlite";  
14:       private SQLiteDatabase myDataBase;  
15:       private final Context myContext;  
16:       /**  
17:        * Constructor Takes and keeps a reference of the passed context in order to  
18:        * access to the application assets and resources.  
19:        *   
20:        * @param context  
21:        */  
22:       public ExternalDbOpenHelper(Context context) {  
23:            super(context, DB_NAME, null, 1);  
24:            this.myContext = context;  
25:       }  
26:       public void createDataBase() throws IOException {  
27:            boolean dbExist = checkDataBase();  
28:            if (dbExist) {  
29:            } else {  
30:                 this.getReadableDatabase();  
31:                 try {  
32:                      copyDataBase();  
33:                 } catch (IOException e) {  
34:                      throw new Error("Error copying database");  
35:                 }  
36:            }  
37:       }  
38:       private boolean checkDataBase() {  
39:            SQLiteDatabase checkDB = null;  
40:            try {  
41:                 String myPath = DB_PATH + DB_NAME;  
42:                 checkDB = SQLiteDatabase.openDatabase(myPath, null,  
43:                           SQLiteDatabase.OPEN_READONLY);  
44:            } catch (SQLiteException e) {  
45:            }  
46:            if (checkDB != null) {  
47:                 checkDB.close();  
48:            }  
49:            return checkDB != null ? true : false;  
50:       }  
51:       @Override  
52:       public synchronized SQLiteDatabase getReadableDatabase() {  
53:            return super.getReadableDatabase();  
54:       }  
55:       private void copyDataBase() throws IOException {  
56:            // Open your local db as the input stream  
57:            InputStream myInput = myContext.getAssets().open(DB_NAME);  
58:            // Path to the just created empty db  
59:            String outFileName = DB_PATH + DB_NAME;  
60:            // Open the empty db as the output stream  
61:            OutputStream myOutput = new FileOutputStream(outFileName);  
62:            // transfer bytes from the inputfile to the outputfile  
63:            byte[] buffer = new byte[1024];  
64:            int length;  
65:            while ((length = myInput.read(buffer)) > 0) {  
66:                 myOutput.write(buffer, 0, length);  
67:            }  
68:            // Close the streams  
69:            myOutput.flush();  
70:            myOutput.close();  
71:            myInput.close();  
72:       }  
73:       public void openDataBase() throws SQLException {  
74:            // Open the database  
75:            String myPath = DB_PATH + DB_NAME;  
76:            myDataBase = SQLiteDatabase.openDatabase(myPath, null,  
77:                      SQLiteDatabase.OPEN_READONLY  
78:                                | SQLiteDatabase.NO_LOCALIZED_COLLATORS);  
79:       }  
80:       @Override  
81:       public synchronized void close() {  
82:            if (myDataBase != null)  
83:                 myDataBase.close();  
84:            super.close();  
85:       }  
86:       @Override  
87:       public void onCreate(SQLiteDatabase db) {  
88:       }  
89:       @Override  
90:       public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
91:       }  
92:  }  

4. Buat Class First.java untuk mengambil data dari database

1:  package com.dananx.papayas.sqlitenew;  
2:  import android.os.Bundle;  
3:  import android.widget.TextView;  
4:  import android.app.Activity;  
5:  import android.database.Cursor;  
6:  import android.database.SQLException;  
7:  import android.database.sqlite.SQLiteDatabase;  
8:  public class First extends Activity {  
9:       @Override  
10:       public void onCreate(Bundle savedInstanceState) {  
11:            super.onCreate(savedInstanceState);  
12:            setContentView(R.layout.first);  
13:            TextView contentLog = (TextView) findViewById(R.id.content_log);  
14:                      ExternalDbOpenHelper myDbHelper = new ExternalDbOpenHelper(  
15:                                this.getApplicationContext());  
16:                      myDbHelper = new ExternalDbOpenHelper(this);  
17:                      try {  
18:                           myDbHelper.openDataBase();  
19:                      } catch (SQLException sqle) {  
20:                           sqle.printStackTrace();  
21:                      }  
22:                      SQLiteDatabase db = myDbHelper.getReadableDatabase();  
23:                      Cursor cur = db.rawQuery(  
24:                                "SELECT _id, name FROM friends WHERE _id=1 ;",  
25:                                null);  
26:                      cur.moveToFirst();  
27:                      while (cur.isAfterLast() == false) {  
28:                           contentLog.append(cur.getString(0) + "\t"  
29:                                     + cur.getString(1) + "\n");  
30:                           cur.moveToNext();  
31:                      }  
32:       }  
33:  }  

5. Buat Class Second.java

1:  package com.dananx.papayas.sqlitenew;  
2:  import android.os.Bundle;  
3:  import android.widget.TextView;  
4:  import android.app.Activity;  
5:  import android.database.Cursor;  
6:  import android.database.SQLException;  
7:  import android.database.sqlite.SQLiteDatabase;  
8:  public class Second extends Activity {  
9:       @Override  
10:       public void onCreate(Bundle savedInstanceState) {  
11:            super.onCreate(savedInstanceState);  
12:            setContentView(R.layout.first);  
13:            TextView contentLog = (TextView) findViewById(R.id.content_log);  
14:                      ExternalDbOpenHelper myDbHelper = new ExternalDbOpenHelper(  
15:                                this.getApplicationContext());  
16:                      myDbHelper = new ExternalDbOpenHelper(this);  
17:                      try {  
18:                           myDbHelper.openDataBase();  
19:                      } catch (SQLException sqle) {  
20:                           sqle.printStackTrace();  
21:                      }  
22:                      SQLiteDatabase db = myDbHelper.getReadableDatabase();  
23:                      Cursor cur = db.rawQuery(  
24:                                "SELECT _id, name FROM friends WHERE _id=2 ;",  
25:                                null);  
26:                      cur.moveToFirst();  
27:                      while (cur.isAfterLast() == false) {  
28:                           contentLog.append(cur.getString(0) + "\t"  
29:                                     + cur.getString(1) + "\n");  
30:                           cur.moveToNext();  
31:                      }  
32:       }  
33:  }  

nah kekurangannya dari sistem ini adalah di setiap menu tersebut ngambil datanya harus pake class baru soalnya saya masih bingung caranya ngambil data di setiap menu dan ditaruh di di satu Class yang menghandle masih newbie soalnya😀
ya udah sekian dari tutorial ini semoga bermanfaat bagi nusa dan bangsa :3

link donlot

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s