Langkah pertama buatlah Buka Eclipse dan buatlah Project Android baru.
Tambahkan Class baru dengan cara Klik File - New - Class, beri nama misalnya SQLHelper, sehingga menjadi file SQLHelper.java dan tambahkan kode program berikut ini :
package com.amijaya.backup_restore_sqlite;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
//http://cariprogram.blogspot.com
//nuramijaya@gmail.com
public class SQLHelper extends SQLiteOpenHelper{
private static final String DATABASE_NAME = "peta.db";
private static final int DATABASE_VERSION = 1;
public SQLHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
String sql = "create table kota( id integer primary key autoincrement, nama text null, " +
"latitude text null, longitude text null);";
Log.d("Data", "onCreate: " + sql);
db.execSQL(sql);
sql = "INSERT INTO kota (id, nama, latitude, longitude) VALUES (1, 'Yogyakarta', '111', '222');";
db.execSQL(sql);
sql = "INSERT INTO kota (id, nama, latitude, longitude) VALUES (2, 'Surakarta', '333', '444');";
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
Kemudian tambahkan kode program berikut ini ke dalam file MainActivity.java :
package com.amijaya.backup_restore_sqlite;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
Button button1;
Button button2;
Button button3;
Button button4;
protected Cursor cursor;
SQLHelper dbHelper;
private static String DB_PATH = "/data/data/com.amijaya.backup_restore_sqlite/databases/";
private static String DB_NAME = "peta.db";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbHelper = new SQLHelper(this);
button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
SQLiteDatabase db = dbHelper.getReadableDatabase();
cursor = db.rawQuery("SELECT * FROM kota",null);
cursor.moveToFirst();
for (int cc=0; cc < cursor.getCount(); cc++)
{
cursor.moveToPosition(cc);
Toast.makeText(getApplicationContext(), cursor.getString(1).toString(), Toast.LENGTH_SHORT).show();
}
}
});
button2 = (Button)findViewById(R.id.button2);
button2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
try {
File file = new File(DB_PATH + DB_NAME); //Uri.toString());
//FileInputStream myInput = FileInputStream(file); // myContext.getAssets().open(DB_NAME);
FileInputStream myInput;
myInput = new FileInputStream(file);
// Path to the just created empty db
String outFileName = "/sdcard/peta.db"; // DB_PATH + DB_NAME;
//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
Toast.makeText(getApplicationContext(), "Berhasil", Toast.LENGTH_LONG).show();
} catch (Exception e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
});
button3 = (Button)findViewById(R.id.button3);
button3.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
try {
File file = new File("/sdcard/peta.db"); //Uri.toString());
//FileInputStream myInput = FileInputStream(file); // myContext.getAssets().open(DB_NAME);
FileInputStream myInput;
myInput = new FileInputStream(file);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
Toast.makeText(getApplicationContext(), "Berhasil", Toast.LENGTH_LONG).show();
finish();
} catch (Exception e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
});
button4 = (Button)findViewById(R.id.button4);
button4.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.execSQL("delete from kota");
Toast.makeText(getApplicationContext(), "Berhasil", Toast.LENGTH_LONG).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Untuk desain tampilan tambahkan empat buah Button, sehingga activity_main.xml tampak seperti ini :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/LinearLayout1" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Backup Restore Database SQLite" /> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Read DB" /> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Backup DB" /> <Button android:id="@+id/button4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Empty DB" /> <Button android:id="@+id/button3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Restore DB" /> </LinearLayout>
Pada file konfigurasi di AndroidManifest.xml jangan lupa ditambahkan Uses Permission READ EXTERNAL STORAGE dan WRITE EXTERNAL STORAGE, misalnya seperti ini :
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.amijaya.backup_restore_sqlite" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="16" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.amijaya.backup_restore_sqlite.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
Hasilnya ketika dijalankan akan tampil sebagai berikut :
Read DB untuk mengetes apakah ada data di dalam database, Backup DB untuk membackup dengan cara mengkopi file Database SQLite ke SDCard, pada contoh ini file database bernama peta.db dan akan terkopi di direktori SDCard/peta.db. Empty DB untuk membuat agar data di database kosong. Bisa dites dengan Read DB maka kelihatan database sudah kosong. Kemudian Restore DB untuk mengembalikan file SQLite peta.db dari SDCard tercopy masuk dan mereplace database yang ada di direktori internal Aplikasi. Bisa dites lagi dengan Read DB maka tampak data sudah kembali ada.
File project dapat anda download disini. Jika bingung cara download, silakan lihat caranya disini.
Semoga bermanfaat ^_^
terimakasih...sangat bermanfaat
BalasHapus