Summary Notes : Storing and Retrieving data (SQLiteDatabase, Preference, File)

Application Preference (/data/data//shared_prefs/.xml)


Private Preference (Data sharing within activity)
Storing Data

SharedPreference sp = getPreferences(MODE_PRIVATE);
SharedPreference.Editor e = sp.edit();
e.putInt(“Score”,10);
e.putString(“Name”,”abc”);
e.commit();

Retrieving Data

SharedPreference sp = getPreferences(MODE_PRIVATE);
int score = sp.getInt(“Score”,null);
String name = sp.getString(“Name”,null);

Shared Preference (Data sharing between multiple activities of application)

Storing Data (In Activity1.java)

SharedPreference sp = getSharedPreferences(“game”,0);
SharedPreference.Editor e = sp.edit();
e.putInt(“Score”,10);
e.putString(“Name”,”abc”);
e.commit();
Intent i = new Intent(getApplicationContext(), Activity2.class);
startActivity(i);

Retrieving Data (In Activity2.java)

SharedPreference sp = getSharedPreferences(“game”,0);
int score = sp.getInt(“Score”,null);
String name = sp.getString(“Name”,null);

Reading and Writing data to file


Writing data to file

FileOutputStream fos;
String strFileContents = “Some text to write to the file.”;
fos = openFileOutput(“Filename.txt”, MODE_PRIVATE);
fos.write(strFileContents.getBytes());
fos.close();

• or

FileOutputStream fOut = null;
OutputStreamWriter osw = null;
try
{
fOut = openFileOutput("test.txt", Context.MODE_PRIVATE);
osw = new OutputStreamWriter(fOut);
osw.write("Good morning!!! MCA-5");
osw.write("Hi");
osw.close();
fOut.close();
}
catch(Exception e)
{ e.printStackTrace(System.err); }

Appending data to file

FileOutputStream fos;
String strFileContents = “More text to write to the file.”;
fos = openFileOutput(“Filename.txt”, MODE_APPEND);
fos.write(strFileContents.getBytes());
fos.close();

Reading data to file

FileInputStream fIn = null;
InputStreamReader isr = null;
try
{
char[] b = newchar[1024];
String data = null;
fIn = openFileInput("test.txt");
isr = new InputStreamReader(fIn);
isr.read(b);
data = new String(b);

TextView tv = (TextView) findViewById(R.id.textview1);
tv.setText(data);
isr.close();
fIn.close();
}
catch(IOException e)
{ e.printStackTrace(System.err); }

Creating, deleting database and table with SQLite Database.


Creating and Deleteing Database:

SQLiteDatabase db;
db = openOrCreateDatabase(“mca.db”,SQLiteDatabase.CREATE_IF_NECESSARY,null);
deleteDatabase(“mca.db”);

Creating Table:

String s = “CREATE TABLE stud (id INTEGER PRIMARY KEY AUTOINCREMENT, firstname TEXT, lastname TEXT);”;
db.execSQL(s);

Insert, Update and Delete operation with SQLite Database.

Insert Operation:

ContentValues cv = new ContentValues();
cv.put(“firstname”,”abc”);
cv.put(“lastname”,”def”);
db.insert(“stud”, null,cv);

or

db.execSQL( “insert into tbl_authors(firstname, lastname) values (‘abc‘, ‘def‘ );” );

Update Operation:

ContentValues values = new ContentValues();
values.put(“firstname“, “aaa”);
db.update(“tbl_authors”, values, “lastname=?”, new String[] {“def“});

or

db.execSQL(“update tbl_authors set firstname=’aaa’ where lastname=’def‘;”);

Delete Operation:

db.delete(“tbl_authors”, “firstname=?”, new String[]{“aaa”});

or

db.execSQL(“delete from tbl_authors where firstname=’aaa'”);

Querying SQLite Database

SELECT * FROM tbl_books;

Cursor c = mDatabase.query(“tbl_books”,null,null,null,null,null,null);

Or

Cursor c = db.rawQuery(“select * from tbl_books”);
SELECT * tbl_books WHERE id=9;
Cursor c = mDatabase.query(“tbl_books”, null, “id=?”, new String[]{“9”}, null, null, null);
SELECT title, id FROM tbl_books ORDER BY title ASC;
String asColumnsToReturn[] = { “title”, “id” };
String strSortOrder = “title ASC”;
Cursor c = mDatabase.query(“tbl_books”, asColumnsToReturn, null, null, null, null, strSortOrder);

Retrieving data from cursor

c.moveToFirst();
while(c.moveToNext())
{
String s= c.getString(c.getColumnIndex(“fname”));
}
c.getCount(); (Count no. of rows)
c.getColumnCount(); (Count no. of columns)

Fetching data from multiple table

SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(“tbl_books, tbl_authors”);
queryBuilder.appendWhere(“tbl_books.authorid=tbl_authors.id”);
String asColumnsToReturn[] = {
“tbl_books.title”,
“tbl_books.id”,
“tbl_authors.firstname”,
“tbl_authors.lastname”,
“tbl_books.authorid” };
String strSortOrder = “title ASC”;
Cursor c = queryBuilder.query(mDatabase, asColumnsToReturn,
null, null, null, null,strSortOrder);

• or

String sqlUnionExample = “SELECT title AS Name, ‘tbl_books’ AS OriginalTable from tbl_books WHERE Name LIKE ? UNION SELECT (firstname||’ ‘|| lastname) AS Name, ‘tbl_authors’ AS OriginalTable from tbl_authors WHERE Name LIKE ? ORDER BY Name ASC;”;
Cursor c = mDatabase.rawQuery(sqlUnionExample, new String[]{ “%ow%”, “%ow%”});

Working with transactions

mDatabase.beginTransaction();
try
{
// Insert some records, updated others, delete a few
// Do whatever you need to do as a unit, then commit it
mDatabase.setTransactionSuccessful();
} catch (Exception e) {
// Transaction failed. Failed! Do something here.
// It’s up to you.
} finally {
mDatabase.endTransaction();
}

Summary Notes Chapter 10 Download

Advertisements