Sunday, May 13, 2012

File reading example

This example shows how to read text and xml resource files. It has 3 activities, a main one that has two buttons, a second one that reads a text file into a TextView control and a third one that reads an XML file into a TableLayout. The app provides a brief overview of the Doctor Who show and a list of all the doctors.

I am not going to show all the code, but you can download a zip file of the whole project here.

The text file is stored in a new folder under res called "raw". For the xml file I added a new folder called "xml" also under res.

Here is a complete expanded view of the project directory



First we will look at the text file. The Activity consists of just a TextView nested in a ScrollView

<?xml version="1.0" encoding="utf-8"?>

  
    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:scrollbars="vertical">

    <TextView
        android:id="@+id/txtContent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium" />
    
    </ScrollView>

Here is the Java code for the activity that reads the text file named overview.txt

package com.spconger.doctorwho;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import android.util.*;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class OverViewActivity extends Activity{

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  setContentView(R.layout.overview);
  
  fillOverView();
  
  
  
 }
 
 private void fillOverView(){
  
  try{
   //create an Input stream to read the file
  InputStream overviewFile = getResources().openRawResource(R.raw.overview);
  //assign it to a string the method is down below
  String overviewData=inputStreamToString(overviewFile);
  
  //get the TextView
  TextView txtOverview=(TextView)findViewById(R.id.txtContent);
  //set the text
  txtOverview.setText(overviewData);
  
  }
  catch(IOException e)
  {
   Log.e("DEBUG","InputStreamToString failure");
  }
  
  
  
 }
 
 private String inputStreamToString(InputStream is) throws IOException{
  //create a buffer
  StringBuffer sBuffer = new StringBuffer();
  DataInputStream dataIO = new DataInputStream(is);
  String strLine=null;
  
  while((strLine=dataIO.readLine()) != null){
   sBuffer.append(strLine + "\n");
   
  }
  dataIO.close();
  is.close();
  return sBuffer.toString();
 }

}

The xml file is called "doctorlist.xml" and follows this pattern:

\
<?xml version="1.0" encoding="UTF-8"?>
<doctors>
<doctor
 number="First"
 name="William Hartnell"
 tenure="1963-1966" />

...

</doctors>

The xml is read into a TableLayout. Here is the xml of the Activity

<?xml version="1.0" encoding="utf-8"?>

    
   <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:scrollbars="vertical">
        
       <TableLayout
           android:id="@+id/tableLayout_doctors"
           android:layout_width="fill_parent"
           android:layout_height="wrap_content"
           android:stretchColumns="*" />
      
       
   </ScrollView>

here is the java code for the activity that reads the xml

package com.spconger.doctorwho;

import android.app.Activity;
import android.os.Bundle;
import android.util.*;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.content.Intent;
import android.content.res.XmlResourceParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.*;

public class DoctorActivity extends Activity {
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  setContentView(R.layout.doctors);
  try
  {
   getDoctors();
  }
  catch(Exception e){
   Log.e("DEBUG", "Failed to load Doctors",e);
  }
 }

 private void getDoctors()throws XmlPullParserException, IOException{
  TableLayout doctorTable=(TableLayout)findViewById(R.id.tableLayout_doctors);
  
  XmlResourceParser doctorsXML=getResources().getXml(R.xml.doctorlist);
  
  int eventType=-1;
  
  while (eventType != XmlResourceParser.END_DOCUMENT){
   if (eventType==XmlResourceParser.START_TAG){
    String strName=doctorsXML.getName();
    
    if (strName.equals("doctor")){
     String doctorNumber=doctorsXML.getAttributeValue(null,"number");
     String doctorName=doctorsXML.getAttributeValue(null,"name");
     String doctorTenure=doctorsXML.getAttributeValue(null,"tenure");
     insertDoctorRow(doctorTable, doctorNumber, doctorName, doctorTenure);
    }
   }
   eventType=doctorsXML.next();
  }
  
 }
 
 private void insertDoctorRow(final TableLayout doctorTable, 
               String doctorNumber, String doctorName, String doctorTenure){
     
  final TableRow newRow=new TableRow(this);
  addTextToRowWithValues(newRow, doctorNumber);
  addTextToRowWithValues(newRow, doctorName);
  addTextToRowWithValues(newRow, doctorTenure);
  
  doctorTable.addView(newRow);
 }
 
 private void addTextToRowWithValues(final TableRow tableRow, String text){
  TextView textView = new TextView(this);
  textView.setText(text);
  tableRow.addView(textView);
 }
 
 @Override
 public void onStop(){
  super.onStop();
 }
}


Here are pictures of the activities when executed

No comments:

Post a Comment