Storing data to Shared Preferences and SQLite Database
1. Create a
new Android Project called DataStorage with package mdad.localdata
and Activity name: DataStorage.
2. Copy/replace
activity_data_storage.xml file with the file downloaded from LMS.
<TabHost xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/DStabhost" android:layout_width="match_parent" android:layout_height="match_parent"> <TabWidget android:id="@android:id/tabs" android:layout_width="match_parent" android:layout_height="60dp" /> <FrameLayout android:id="@android:id/tabcontent" android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingTop="60dp"> <LinearLayout android:id="@+id/content1" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:orientation="horizontal"> <EditText android:id="@+id/etName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:ems="10" android:hint="Enter Player Name" android:inputType="textPersonName" /> <Button android:id="@+id/btnEnterName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="Submit" /> </LinearLayout> </LinearLayout> <LinearLayout android:id="@+id/content2" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/etIntroTab2A" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Write data into SQLite and Read name from SharedPref" > </TextView> <TextView android:id="@+id/etIntroTab2" android:textSize="30sp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Enter a number from 0 to 10 "></TextView> <EditText android:id="@+id/etNum" android:layout_width="match_parent" android:layout_height="wrap_content" > <requestFocus /> </EditText> <Button android:id="@+id/btnPlay" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Play " > </Button> </LinearLayout> <LinearLayout android:id="@+id/content3" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/etIntroTab3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Read data from SQLite" > </TextView> <Button android:id="@+id/btnShow" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Show " > </Button> <TextView android:id="@+id/tvDisplay" android:layout_width="wrap_content" android:layout_height="wrap_content" android:inputType="textMultiLine" > </TextView> </LinearLayout> </FrameLayout> </TabHost>
3. Run>Run
apps and you are expected to see a messy output
4. Edit DataStorage.java
and add a method called setupTabs.
//Create a setupTabs method Within the class but outside onCreate method
//Create a setupTabs method Within the class but outside onCreate method
private void setupTabs(){ TabHost tabs =(TabHost) this.findViewById(R.id.DStabhost); tabs.setup(); //Tab #1 SharedPreferences Example TabHost.TabSpec ts1 = tabs.newTabSpec("SharedPreferences"); ts1.setIndicator("SharedPref"); ts1.setContent(R.id.content1); tabs.addTab(ts1); //Tab #2 SQLiteDatabase Example TabHost.TabSpec ts2 = tabs.newTabSpec("SQLiteDatabase"); ts2.setIndicator("SQLiteDB"); ts2.setContent(R.id.content2); tabs.addTab(ts2); //Tab #3 Display Data from Sqlite Example TabHost.TabSpec ts3 = tabs.newTabSpec("DisplayAll"); ts3.setIndicator("Display"); ts3.setContent(R.id.content3); tabs.addTab(ts3); }
Test it out/ Discussion on codes
5. Edit DataStorage.java.
Invoke the method setupTabs as shown below:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_data_storage); setupTabs(); }
6. Run>Apply Changes and you are expected to see the output with 3 Tabs.
7. Copy all
text from activity_data_storage.xml and paste it on
Android Layout Finder at
Android Layout Finder at
This
online tools help you to create java coding very quickly for declaring
variables,
binding and all the button Listener. Copy the java codes and paste it on a notepad.
binding and all the button Listener. Copy the java codes and paste it on a notepad.
8. Edit DataStorage.java.
paste the declared variable in the DataStorage class level
Paste
the methods findViews() and onClick(View v) within the class but outside
onCreate() method. Use Intellisense and ALT+Enter to import class whenever
necessary.
//Within the class but outside onCreateprivate void findViews() { TabWidget tabs = (TabWidget)findViewById( android.R.id.tabs ); etName = (EditText)findViewById( R.id.etName ); btnEnterName = (Button)findViewById( R.id.btnEnterName ); etNum = (EditText)findViewById( R.id.etNum ); btnPlay = (Button)findViewById( R.id.btnPlay ); btnShow = (Button)findViewById( R.id.btnShow ); tvDisplay = (TextView)findViewById( R.id.tvDisplay ); btnEnterName.setOnClickListener( this ); btnPlay.setOnClickListener( this ); btnShow.setOnClickListener( this ); }
public void onClick(View v) { if ( v == btnEnterName ) { // Handle clicks for btnEnterName } else if ( v == btnPlay ) { // Handle clicks for btnPlay } else if ( v == btnShow ) { // Handle clicks for btnShow } }
9. Edit DataStorage.java
|
You are
expected to see this error >
To solve
this error
Type the
highlighted code and this will
implements the listener interface
public class DataStorage extends AppCompatActivity implements View.OnClickListener {
10. Edit DataStorage.java
Given the partial codes, put it in the correct sections.
Given the partial codes, put it in the correct sections.
//#1 Declare Class variables db SQLiteDatabase db; int score=100; int rnum;
//#2 inside onCreate method setContentView(R.layout.activity_data_storage); setupTabs(); findViews(); //#3 Create Sqlite Database and Table String sqlStatement="create table if not exists gamedata (recID integer PRIMARY KEY autoincrement, pname text, score integer)"; db = openOrCreateDatabase("NumberGame.db", MODE_PRIVATE, null); db.execSQL(sqlStatement); //#3 Read value from SharedPreferences SharedPreferences myPrefs = getSharedPreferences("SPREF_NAME",0); SharedPreferences.Editor myEditor = myPrefs.edit(); String pName = myPrefs.getString("pName",""); if (pName.equals ("")) //If user first time running app or never set name before { } //do nothing else etName.setText(pName) ; //else show the name set previously which was stored in SharedPreference //#4 create a random number rnum=(int)(Math.random()*10); //random number from 0 to 10 Log.d("rnum","rnum is "+rnum); //write to Logcat (Press ALT+6 to see Logcat)
11. Edit DataStorage.java
The following codes is written when user click on submit button and it will
write the playername to the local phone memory, SharedPreferences with the
Filename SPREF_NAME and variable name pName
//if ( v == btnEnterName ) {
String playerName = etName.getText().toString();
SharedPreferences myPrefs = getSharedPreferences("SPREF_NAME",0);
SharedPreferences.Editor myEditor = myPrefs.edit();
myEditor.putString("pName", playerName);
myEditor.commit();
Toast toast = Toast.makeText(getApplicationContext(),
"playerName" +" entered.", Toast.LENGTH_SHORT);
// Set the Gravity to Top and Left
toast.setGravity(Gravity.TOP | Gravity.LEFT, 100, 800);
toast.show();
Test it out/ Discussion on codes
The following codes is written when user click on Play button and it will compare
the number entered by the user and check if it is correct, if wrong score minus
10. When user gets it right, it will write the player name (get from
SharedPreference memory) and the score to the Sqlite table.
//else if ( v == btnPlay )
int num = 0;
try {
num= Integer.parseInt(etNum.getText().toString());
}
catch(Exception e)
{ num = 0; }
if(num==rnum)
{
etNum.setText("");
etNum.setHint("Bravo! Score: "+score);
//Read value from SharedPreferences
SharedPreferences myPrefs = getSharedPreferences("SPREF_NAME",0);
SharedPreferences.Editor myEditor = myPrefs.edit();
String playerName = myPrefs.getString("pName","No name set");
try {
db.beginTransaction();
db.execSQL("insert into gamedata(pname,score) values('"+playerName+"','"+score+"');");
db.setTransactionSuccessful();
db.endTransaction();
}
catch (Exception e) {
Toast.makeText(DataStorage.this, e.getMessage(),Toast.LENGTH_LONG).show();
}
//Reset Score and start new random number
rnum=(int)(Math.random()*10); //random number from 0 to 10
Log.d("rnum","rnum is "+rnum);
score=100; //reset score to initial value of 100
}else{
etNum.setText("");
if (num>rnum)
etNum.setHint("Try smaller number..." );
else
etNum.setHint("Try bigger number..." );
score-=10; //reduce score by 10 points
if(score<0) score=0;//lowest score is 0
}
Test it out/ Discussion on codes
The following codes is written when user click on Display Tab and Show button and
it display the names and the score from Sqlite memory.
//else if ( v == btnShow )
try {
Cursor c1 = db.rawQuery("select * from gamedata", null);
String s1, s2, sc="";
while(c1.moveToNext())
{
s1=c1.getString(1);
s2=c1.getString(2);
sc+=s1+"\t"+s2+"\n";
}
tvDisplay.setText("Scoreboard\n"+sc);
}
catch (Exception e) {
Toast.makeText(DataStorage.this, e.getMessage()
, Toast.LENGTH_LONG).show();
}
Test it out/ Discussion on codes
LAB 7: Mobile Device Application (Part B)
Modify DataStorage.java such that score is displayed from highest to lowest score
No comments:
Post a Comment
Note: only a member of this blog may post a comment.