Monday, July 16, 2012

Creating Text File and using in Android



Click Here to download source code

Package Name   :   selva.file

Project Name     :   File2

Version              :   1.5 ( Support 1.5 and above versions)

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Please enter some text"/>
    <EditText
    android:id="@+id/txtText2"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />
    <Button
    android:id="@+id/btnLoad"
    android:text="Load"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />
</LinearLayout>



(create raw folder under res) 
res-->raw-->rightclick-->new-->file-->textfile 

















 
textfile.txt

hi.. this is sample file content..


  File2Activity.java


 package selva.file;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.io.IOException;
import java.io.InputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;


public class File2Activity extends Activity
{
    /** Called when the activity is first created. */
    private EditText textBox;

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
       
    textBox = (EditText) findViewById(R.id.txtText2);
    Button loadBtn = (Button) findViewById(R.id.btnLoad);
   
loadBtn.setOnClickListener(new View.OnClickListener()
{
    public void onClick(View v)
    {
        InputStream  is=File2Activity.this.getResources().openRawResource(R.raw.textfile);
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String str=null;
        try {
        while ((str = br.readLine()) != null)
        {
           
            textBox.setText(str);   
        }
   
        is.close();
        br.close();
        }
        catch (IOException e)
        {
        e.printStackTrace();
        }
    }
}); 
}
}


OUTPUT:


























 click Load button










Click Here to download source code


No comments:

Post a Comment