Вы находитесь на странице: 1из 10

Modules: Print Module

Lesson 9 Text Files, Data tables and SQL Lite.htm[27/03/2014 03:13:15 PM]
Send to Printer | Close Window

Lesson 9: Text Files, Data tables and SQL Lite
Outcomes for this lesson
Copyright (c) 2014, Unisa
Outcomes for this lesson
In this lesson you will learn how to create an Android application
- that can write and read from and to a PRIVATE text file
- read the information from a PRIVATE text file into an array
- that can write and read from and to data tables using SQLite.
Purpose
Very often you will create applications where you need to be able to store and retrieve information from one session to another. Or in
other instances the user must be allowed to add additional information.
Read from Text Files
Copyright (c) 2014, Unisa
Read from Text Files - readFromFile()
Consider the following scenario:
As a student you would like to keep track, with a list, of the due dates for your assignments.
The applications that we've developed thus far, only allow us to create the information when the application is created. As soon as the
application is killed (closed) all the captured information is gone.
A text file is one way of saving and retrieving the information from one session to another.
In this slide we will create the code required to read from a text file.
In the next slide we will create the code required to write to a text file.
Modules: Print Module
Lesson 9 Text Files, Data tables and SQL Lite.htm[27/03/2014 03:13:15 PM]
Create a new Android Application, save it as MyTextFiles
- One screen
- One EditText field (where we will enter the text that must be saved to a text file).
- Two buttons (SAVE and CLEAR) - where all our code will go.
- One TextView field (where we will display the text read from the text file).

In the XML view of the activity_main.xml, change the layout_width and layout_height for TextView
e.g.

andr oi d: i d=" @+i d/ t xt Di spl ay"
andr oi d: l ayout _wi dt h="400dp"
andr oi d: l ayout _hei ght ="100dp"
andr oi d: l ayout _cent er Ver t i cal =" t r ue"
andr oi d: t ext =" " / >

Add the initial coding to your application that will link the widgets to the code.
Step 1: Create the static and class variables (those variables that we will use in all the buttons and code)
publ i c cl ass Mai nAct i vi t y ext ends Act i vi t y {
/ / st at i c var i abl es

private static final String TAG = MainActivity.class.getName();
private static final String FILENAME = "mystuff.txt";

/ / cl ass var i abl es

TextView fDisplay;
EditText fInput;
Button btnSave;
Button btnClear;
String inText; //use this variable for the information read in from the textfile.

int numItems=0; //use it later to keep track of the number of items.

@Over r i de
pr ot ect ed voi d onCr eat e( Bundl e savedI nst anceSt at e) {
super . onCr eat e( savedI nst anceSt at e) ;
set Cont ent Vi ew( R. l ayout . act i vi t y_mai n) ;

/ / l i nk t he wi dget s t o t he code
fDisplay = (TextView)findViewById(R.id.txtDisplay);
fInput = (EditText)findViewById(R.id.edInput);
}
Step 2: Add the code, calling method that will readFromFile().
We would like the application, when it opens to immediately read the information from the textfile, "mystuff.txt" and display it on the
screen in our TextView field. If there is no information then nothing must be displayed. The information from the file must be read into
the variable i nText that we've initialised.
Add the following code that will read the information in from our text file and display it in the TextView field:
super . onCr eat e( savedI nst anceSt at e) ;
Modules: Print Module
Lesson 9 Text Files, Data tables and SQL Lite.htm[27/03/2014 03:13:15 PM]
set Cont ent Vi ew( R. l ayout . act i vi t y_mai n) ;

/ / l i nk t he wi dget s t o t he code
f Di spl ay = ( Text Vi ew) f i ndVi ewByI d( R. i d. t xt Di spl ay) ;
f I nput = ( Edi t Text ) f i ndVi ewByI d( R. i d. edI nput ) ;

/ / r ead f r omt he f i l e

inText = readFromFile();


fDisplay.setText(inText);
Step 3: Add coding to our method readFromFile()
You will notice that as soon as you've entered the code r eadFr omFi l e( ) that it is underlined in red. This is because this method
does not exist. We will need to code it!
Hover the mouse over it and select the option: Create method " readFromFile() "
Scroll down in your code, until you see the code that is created for you for the method:
pr i vat e St r i ng r eadFr omFi l e( ) {
/ / TODO Aut o- gener at ed met hod st ub
r et ur n nul l ;
}
Notice that there is a return. Why because we need to do something in the code and then return it from where it was called. J ust go
back and see what we've done in the calling code: inText = readFromFile();
Thus whatever is returned from this method will be read into i nText and then use where required.
Let's add some coding to this method:
Step 4a: Add coding for readFromFile().
Start by creating a String ret ="";
This is what we are going to return to the calling program. Replace return null; with return ret;
pr i vat e St r i ng r eadFr omFi l e( ) {
/ / TODO Aut o- gener at ed met hod st ub
String ret="";
//where your code will go
return ret;
}
Step 4b: continue to add code for readFromFile(). The code must be entered before return ret;
1) As you enter the code, resolve the "import widgets".
2) At this stage leave the underlines that requests: Add throw/exception || Surround try/catch.
pr ot ect ed St r i ng r eadFr omFi l e( ) {
/ / TODO Aut o- gener at ed met hod st ub
St r i ng r et =" " ;

InputStream is = openFileInput(FILENAME);

InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String inString ="";
StringBuilder sb = new StringBuilder();
while ((inString = br.readLine())!= null){
sb.append(inString);}
Modules: Print Module
Lesson 9 Text Files, Data tables and SQL Lite.htm[27/03/2014 03:13:15 PM]

is.close();

ret = sb.toString();

r et ur n r et ;


}
Step 4c: Resolve the unresolved issues.
Now, you can resolve the underlined issued.
Hover the mouse on each of them.
For openFi l eI nput ( FI LENAME) ; select the option " Add t hr ows decl ar at i on"
Notice that where the method is declared that there is now a throws exception added:
pr ot ect ed St r i ng r eadFr omFi l e( ) t hr ows Fi l eNot FoundExcept i on
Resolve the other two: br.readLine() and is.close(); with "Surround with try/catch"
Eclipse will not allow J ava to compile without these throws and try/catch coding.
Add a user friendly message where there are "catches". Use the Toast to send a message to the user.
Below is the complete code with all the throws and exceptions:
pr ot ect ed St r i ng r eadFr omFi l e( ) t hr ows Fi l eNot FoundExcept i on {
/ / TODO Aut o- gener at ed met hod st ub
St r i ng r et =" " ;

I nput St r eami s = openFi l eI nput ( FI LENAME) ;

I nput St r eamReader i sr = new I nput St r eamReader ( i s) ;
Buf f er edReader br = new Buf f er edReader ( i sr ) ;
St r i ng i nSt r i ng =" " ;
St r i ngBui l der sb = new St r i ngBui l der ( ) ;
t r y {
whi l e ( ( i nSt r i ng = br . r eadLi ne( ) ) ! = nul l ) {
sb. append( i nSt r i ng) ; }
} cat ch ( I OExcept i on e) {
/ / TODO Aut o- gener at ed cat ch bl ock
e. pr i nt St ackTr ace( ) ;
Toast.makeText(MainActivity.this, "Couldn't read from file",
Toast.LENGTH_LONG).show();
}

t r y {
i s. cl ose( ) ;
} cat ch ( I OExcept i on e) {
/ / TODO Aut o- gener at ed cat ch bl ock
e. pr i nt St ackTr ace( ) ;
Toast.makeText(MainActivity.this, "Couldn't read from file",
Toast.LENGTH_LONG).show();
}

r et = sb. t oSt r i ng( ) ;

r et ur n r et ;

}
Modules: Print Module
Lesson 9 Text Files, Data tables and SQL Lite.htm[27/03/2014 03:13:15 PM]
Step 4d: Resolve the unresolved issues in the calling program.
Verify the code in the calling selection. Often Eclipse will force you to add try/catch exceptions to any code where you are reading to
or from a file. Add the try/catch coding.
Save, resolve all errors. Compile and run the program. At this we haven't entered text into the file mystuff.txt, but your program should
at least compile and run.
Write to a text file - writeToFile()
Copyright (c) 2014, Unisa
Write to a text file - writeToFile()
In the previous slide we've created the code necessary to read from a text file. Now we are going to create a method, writeToFile()
that will write whatever is on the screen, append it to the information already in the text file, and save it.
If you haven't created the code for the SAVE button, do it now
Step 1: Enter the following code for the SAVE button
bt nSave = ( But t on) f i ndVi ewByI d( R. i d. bt nSave) ;
bt nSave. set OnCl i ckLi st ener ( new OnCl i ckLi st ener ( ) {
publ i c voi d onCl i ck( Vi ew v) {
/ / Thi s i s wher e your code wi l l go
/ / r ead t he i nput f r omt he user i nt o t ext ToSave

String textToSave = fInput.getText().toString();
//Writes textToSave to the file
//The # indicates the next item
writeToFile(inText + textToSave +"#");




fInput.setText(null); //clear the input field
// to allow user to enter new data

//call our readFromFile() again to read the old and new info
inText = readFromFile();
fDisplay.setText(inText); //display old and new info
}/ / end of onCl i ck
}) ; / / bt nSave
After entering the code, you will notice again that wr i t eToFi l e( . . . . ) is underlined. This is because we still need to create the
method for it. (J ust as in the previous slide).
Hover the mouse on wr i t eToFi l e and select the option "Create method writeToFile(String) in MainActivity"
Modules: Print Module
Lesson 9 Text Files, Data tables and SQL Lite.htm[27/03/2014 03:13:15 PM]
The type MainActivity is important, if you choose the Create method "writeToFile(String)" then the method will be created within the
button and not visible to other classes and coding.
Scroll down until you see the code for this method. Notice that there is no return statement. We are not going to return anything to the
calling code. We are going to write something to the text file. The void type indicates this as well.

But there is a parameter String string. Change string to "data". (You can leave it string, but it is easier to understand your coding when
we refer to data).
This data is what we are bringing along from the calling program. wr i t eToFi l e(inText + textToSave +"#");
And this data is what is going to be written to the text file.

pr ot ect ed void wr i t eToFi l e( St r i ng data) {
/ / TODO Aut o- gener at ed met hod st ub

}
Step 2a: Enter the code
Enter the following code that will open all the necessary buffers and write the data to the text file: Resolve the underlined reds again,
by importing the necessary widgets. As previously, leave the exception requests to the end.
pr ot ect ed voi d wr i t eToFi l e( St r i ng data) {
/ / TODO Aut o- gener at ed met hod st ub
OutputStreamWriter osw = new OutputStreamWriter(openFileOutput(FILENAME,
MainActivity.this.MODE_PRIVATE));
BufferedWriter bw = new BufferedWriter(osw);
bw.write(data);
bw.newLine();
bw.close();
osw.close();

}
Step 2b: Resolve the exceptions
As previously resolve the exceptions now.
For openFileOutput choose the "Add throws declaration"
and for the rest choose the try/catch code.
Your final code will look something like this:
Add user friendly error messages using Toast where the exceptions are.
pr ot ect ed voi d wr i t eToFi l e( St r i ng dat a) t hr ows Fi l eNot FoundExcept i on {
/ / TODO Aut o- gener at ed met hod st ub
Out put St r eamWr i t er osw = new Out put St r eamWr i t er ( openFi l eOut put ( FI LENAME,
Mai nAct i vi t y. t hi s. MODE_PRI VATE) ) ;
Buf f er edWr i t er bw = new Buf f er edWr i t er ( osw) ;
t r y {
bw. wr i t e( dat a) ;
} cat ch ( I OExcept i on e) {
/ / TODO Aut o- gener at ed cat ch bl ock
e. pr i nt St ackTr ace( ) ;
Toast.makeText(MainActivity.this,
"Couldn't write to file", Toast.LENGTH_LONG).show();
Modules: Print Module
Lesson 9 Text Files, Data tables and SQL Lite.htm[27/03/2014 03:13:15 PM]
}
t r y {
bw. newLi ne( ) ;
} cat ch ( I OExcept i on e) {
/ / TODO Aut o- gener at ed cat ch bl ock
e. pr i nt St ackTr ace( ) ;
Toast.makeText(MainActivity.this,
"Couldn't write to file", Toast.LENGTH_LONG).show();
}
t r y {
bw. cl ose( ) ;
} cat ch ( I OExcept i on e) {
/ / TODO Aut o- gener at ed cat ch bl ock
e. pr i nt St ackTr ace( ) ;
Toast.makeText(MainActivity.this,
"Couldn't write to file", Toast.LENGTH_LONG).show();
}
t r y {
osw. cl ose( ) ;
} cat ch ( I OExcept i on e) {
/ / TODO Aut o- gener at ed cat ch bl ock
e. pr i nt St ackTr ace( ) ;
Toast.makeText(MainActivity.this,
"Couldn't write to file", Toast.LENGTH_LONG).show();
}

}
Save, sort the errors, compile and run your program.
The program should now allow you to SAVE some text, and display it on the screen,
J ust one button left to code: the CLEAR button.
This is easy:
If you haven't created the CLEAR button, do it now and add the following code:
This button will clear the Input field as well as the text file.
bt nCl ear = ( But t on) f i ndVi ewByI d( R. i d. bt nCl ear ) ;
bt nCl ear . set OnCl i ckLi st ener ( new OnCl i ckLi st ener ( ) {
publ i c voi d onCl i ck( Vi ew v) {
/ / Thi s i s wher e your code wi l l go
/ / cl ear t he scr een
fDisplay.setText(null);



//clear the file
fInput.setText(null);



writeToFile("");

inText = readFromFile();

}/ / end of onCl i ck
}) ; / / bt nCl ear

As with the previous steps, resolve the imports as well as the try/catch exceptions.
Modules: Print Module
Lesson 9 Text Files, Data tables and SQL Lite.htm[27/03/2014 03:13:15 PM]
SAVE, correct all errors, compile and run your application
You can download the code from myUNISA if you really struggle!
Can you think of how to use the above code and read the information from the text file into an array and then displaying the array
as options in a Radio Button??
Can you think of ways that the user then can modify the radio button to alter the content???
There are many possibilities that you can use with text files.
Assignment 1 - Task 10
Copyright (c) 2014, Unisa
Assignment 1 - Task 10
You should now be very near to the end of developing your application.
In this lesson we have learned how to create files (text and sql) that we can use to save information.
Indicate how you are going to apply it in your final project.
Edit the notes on the ideas for your project.
Include the following in your project:
- How will you link the pages (screens) - are you going to use buttons or lists.
- What is the purpose of each screen
- Do you need to create / download images?
- How can you optimize your code using classes, objects and arrays?
- Do I need to link with external webpages?
- What about splash screens. Are you going to use images from the internet? What about copyright issues?
- Are you going to include music / audio. What about copyright issues.
- How you are going to deal with user input. Catching errors. Think of errors that may occur where you are dealing with arrays as well
- Overloading of methods
- Inheritance between classes
- How you will use files in your application
Continue with the implementation and finalisation of your coding.
Remember you can update and change as we go along (but you may not change from your initial choice of app.)
Upload this document on DropBox.
Give it a proper version number, e.g. 12345678_dev_v9.docx. (Where 12345678 is your student number).
I am only going to mark the final document, BUT, I am going to refer back to the different versions. If you haven't worked during the
semester on your project, then you are not going to get good marks for the final document. Further, if you contact me to assist you,
then I am going to refer to your documentation as well.
Lesson 9: Summary
Copyright (c) 2014, Unisa
Modules: Print Module
Lesson 9 Text Files, Data tables and SQL Lite.htm[27/03/2014 03:13:15 PM]
Lesson 9: Summary
Now it is your turn ...
In the blogger add a blog entry. Label it Lesson 9. In this blog, enter a short summary for yourself of everything that we've learned.
Specifically those components that you've battled with and how you solved it.
Remember to keep notes and updates in your little black book.
I am not going to mark it, but if you request of me to assist you then I will first of all look at your blogger. Your entries, when you've
made it, your comments etc.
Lesson 9b: Creating SQLite data file
Copyright (c) 2014, Unisa
Creating SQLite data files
You have been exposed to Oracle XE in the first year of study thus the SQL part of this lesson should not be a problem to you.
What is SQLite?
SQLite is an Open Source database and supports standard relational database features and requires limited memory at runtime
(approx. 250 KByte) which makes it a good candidate from being embedded into other runtimes and Android applications.

SQLite supports only three data types
TEXT (similar to String in J ava and varchar(2) in Oracle),
INTEGER (similar to long in J ava and number in Oracle )
REAL (similar to double in J ava and number(9,2) in Oracle).
All other types must be converted into one of these fields before getting saved in the database. SQLite itself does not validate if the
types written to the columns are actually of the defined type, e.g. you can write an integer into a string column and vice versa. It will
thus be good programming from your side to verify the data before it is entered into the database.
You can read more on SQLite at: http://www.sqlite.org.

How can use SQLite in an Android application?
Using an SQLite database in Android does not require a setup procedure or administration of the database as it is embedded into
Android.

You only have to define the SQL statements for creating and updating the database. Afterwards the database is automatically
Modules: Print Module
Lesson 9 Text Files, Data tables and SQL Lite.htm[27/03/2014 03:13:15 PM]
managed for you by the Android platform!!!

Access to an SQLite database involves accessing the file system. But, this can be slow.
Therefore it is recommended to perform database operations asynchronously.
The programmer has the option of creating the database either on the first run of the application or bundle it with the application. You
can read more on how to bundle a database with an application at:

If your application creates a database, this database is by default saved in the directory
DATA/data/APP_NAME/databases/FILENAME.

The parts of the above directory are constructed as follows.
DATA is the path which the Environment.getDataDirectory() method returns.
APP_NAME is your application name
FI LENAME is the name you will specify in your code for the database.
It is quite a lengthy process to create an application that uses a SQLite database.
I am not going to go into the detail.
I am going to take you through the creation of an application that uses a SQLite database, but you are going to copy and past a lot of
the code. Then you are welcome thereafter to manipulate it, play around and use it the best you can for your application.
You are welcome to read more on how to create an Android application using a SQLite database at:
http://www.vogella.com/articles/AndroidSQLite/article.html

Вам также может понравиться