SQLITE DATABASE
If you want to save your data to your storage of your device it is one of the easiest way to use SQLite
Basically we will use context to open or create a database and then we will use the SQLiteDatabase class to provide table or data to database also query the database
tables at last we will focus on to Cursor to trace the records on tables
context.openOrCreateDatabase("tablename",/*mode of table*/,null);
mode of table is related the permission of the table
as you know databases for the each program is different in device you can look your DDMS data/data/yourpackagename/databases
so if another program wants to reach to another programs database there should be permission for the table defined when it is created
1 ) If you want another program to reach your database your mode should be MODE_WORLD_READABLE or MODE_WORLD_WRITABLE
2 ) If you want another program not to reach your database your mode should be MODE_PRIVATE
now lets move on.
SQLiteDatabase sqlite = this.openOrCreateDatabase("abctable",MODE_PRIVATE,null);
sqlite.execSQL("CREATE TABLE ABC (F1 VARCHAR);");
sqlite.execSQL("INSERT INTO CAN (F1) values ('ABC') ");
--> Now second important class we will look at. That is Cursor which is associated with pointer structure. It enables you to trace your table rows.
Cursor cursor = sqlite.rawQuery("SELECT * FROM ABC");
Then if you use the code below you can be sure the cursor is on the first row
cursor.moveToFirst();
String str = cursor.getString(0);
now you handled the data from database of your device.
package com.example.myxdb;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
public class MainActivity extends Activity {
SQLiteDatabase mydb = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
mydb = this.openOrCreateDatabase("tablename", MODE_PRIVATE, null);
mydb.execSQL("CREATE TABLE ABC (F1 VARCHAR);");
mydb.execSQL("INSERT INTO ABC (F1) VALUES ('DATABC')");
Cursor cursor = mydb.rawQuery("SELECT * FROM ABC", null);
cursor.moveToFirst();
String str = cursor.getString(0);
} catch (Exception e) {
Log.e("Error In Database Operations ", null);
}
}
@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;
}
}
No comments:
Post a Comment