Gautham Vinod
Gautham Vinod

Reputation: 413

How to save text from an EditText as a table text file in Android?

I am trying to save text from multiple text-boxes to a single file arranging itself in a table

For Example :

Student : ....
Class : ...
Marks : ...

This should be saved as :

Student                Class          Marks

....                   ....           ....

....                   ....           ....

Everytime it saves, a new row should be created for a new student....

Is this possible as a text file ? If not, how else will I be able to do this ?

Also, the activity should display this table.... if possible

The code I got is :

public class Save extends Activity implements SwipeInterface, OnFocusChangeListener {
Double marks = 0.0;
EditText et1 = (EditText) findViewById(R.id.roll_no);
EditText et2 = (EditText) findViewById(R.id.name);
EditText et3 = (EditText) findViewById(R.id.grade);
EditText et4 = (EditText) findViewById(R.id.subject);
EditText et5 = (EditText) findViewById(R.id.marks);
EditText et6 = (EditText) findViewById(R.id.filename);
....
ActivitySwipeDetector swipe = new ActivitySwipeDetector(this, this);
    RelativeLayout swipe_layout = (RelativeLayout) findViewById(R.id.Save_port);
    swipe_layout.setOnTouchListener(swipe);

    Intent receiveIntent = this.getIntent();
    Double e3 = receiveIntent.getDoubleExtra("DoubleValue_e3", 0.00);
    marks = e3;
    EditText ebar = (EditText) findViewById(R.id.marks);
    ebar.setText(marks.toString());

    et3.setOnFocusChangeListener((OnFocusChangeListener)this);
    try{
        File dir = new File("/mnt/sdcard/Teacher's Aid/");

        if (!dir.exists()) {
            dir.mkdir();
          } 

    }catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    }
}
 ....
public void butt_save(View view)
{
    try {
        String row = et1.getText().toString() + "," + et2.getText().toString() + "," + et3.getText().toString() + "," + et4.getText().toString() + "," + et5.getText().toString() + "\n";
        File myFile = new File("/mnt/sdcard/Teacher's Aid/" + et6.getText().toString() + ".csv");
   if (!myFile.exists()) {
           myFile.createNewFile();
           FileOutputStream fOut = new FileOutputStream(myFile.getAbsoluteFile(),true);
            OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);


                   //Write the header : in your case it is : Student class Marsk (only one time)
            myOutWriter
            .write("Roll no,Name,Grade,Subject,Marks"+"\n");

            myOutWriter.close();
   }
   FileOutputStream fOut = new FileOutputStream(myFile.getAbsoluteFile(),true);
   OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);

               //write to CSV
   myOutWriter.write(row);
   myOutWriter.close();
   Toast.makeText(getApplication(), "Sucessful",Toast.LENGTH_LONG).show();

} catch (Exception e) {
 e.printStackTrace();
 }
}

@Override
public void onFocusChange(View v, boolean hasFocus) {
    if(!hasFocus)
    {
        et6.setText("Class " + et3.getText().toString());

}

}}

However, this doesn't even open... when I go from main activity to this, thee app crashes.... The LogCat shows ...

02-20 05:53:38.581: E/AndroidRuntime(1664): FATAL EXCEPTION: main
02-20 05:53:38.581: E/AndroidRuntime(1664): Process: com.Candy.teacher, PID: 1664
02-20 05:53:38.581: E/AndroidRuntime(1664): java.lang.RuntimeException: Unable to instantiate  activity ComponentInfo{com.Candy.teacher/com.Candy.teacher.Save}: java.lang.NullPointerException
02-20 05:53:38.581: E/AndroidRuntime(1664):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2102)
02-20 05:53:38.581: E/AndroidRuntime(1664):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2226)
02-20 05:53:38.581: E/AndroidRuntime(1664):     at android.app.ActivityThread.access$700(ActivityThread.java:135)
02-20 05:53:38.581: E/AndroidRuntime(1664):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1397)
02-20 05:53:38.581: E/AndroidRuntime(1664):     at android.os.Handler.dispatchMessage(Handler.java:102)
02-20 05:53:38.581: E/AndroidRuntime(1664):     at android.os.Looper.loop(Looper.java:137)
02-20 05:53:38.581: E/AndroidRuntime(1664):     at android.app.ActivityThread.main(ActivityThread.java:4998)
02-20 05:53:38.581: E/AndroidRuntime(1664):     at java.lang.reflect.Method.invokeNative(Native Method)
02-20 05:53:38.581: E/AndroidRuntime(1664):     at java.lang.reflect.Method.invoke(Method.java:515)
02-20 05:53:38.581: E/AndroidRuntime(1664):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
02-20 05:53:38.581: E/AndroidRuntime(1664):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
02-20 05:53:38.581: E/AndroidRuntime(1664):     at dalvik.system.NativeStart.main(Native Method)
02-20 05:53:38.581: E/AndroidRuntime(1664): Caused by: java.lang.NullPointerException
02-20 05:53:38.581: E/AndroidRuntime(1664):     at android.app.Activity.findViewById(Activity.java:1883)
02-20 05:53:38.581: E/AndroidRuntime(1664):     at com.Candy.teacher.Save.<init>(Save.java:15)
02-20 05:53:38.581: E/AndroidRuntime(1664):     at java.lang.Class.newInstanceImpl(Native Method)
02-20 05:53:38.581: E/AndroidRuntime(1664):     at java.lang.Class.newInstance(Class.java:1208)
02-20 05:53:38.581: E/AndroidRuntime(1664):     at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
02-20 05:53:38.581: E/AndroidRuntime(1664):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2093)
02-20 05:53:38.581: E/AndroidRuntime(1664):     ... 11 more
02-20 05:53:50.241: I/Process(1664): Sending signal. PID: 1664 SIG: 9

Upvotes: 1

Views: 1572

Answers (3)

Brinda K
Brinda K

Reputation: 765

If you want store as .csv file in sdcard , try below code

    try{

        File dir = new File("/mnt/sdcard/MyApp/");

        if (!dir.exists()) {
            dir.mkdir();
             System.out.println("Directory created");
          } 
        //ceate .csv file with header
        myFile = new File("/mnt/sdcard/MyApp/Student.csv");

        if (!myFile.exists()) {
            myFile.createNewFile();
            System.out.println("File created");
        }

        fOut = new FileOutputStream(myFile.getAbsoluteFile(),true);
        myOutWriter = new OutputStreamWriter(fOut);


               //Write the header : in your case it is : Student class Marsk (only one time)
        myOutWriter
        .write("Student,class,Marks"+"\n");

        myOutWriter.flush();

    }catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    }

When you want to write new rows :

           try {
             String row = studentname + "," + studentclass + "," + studentmarks + "\n";
        myFile = new File("/mnt/sdcard/MyApp/Student.csv");
        if (!myFile.exists()) {
                myFile.createNewFile();
        }
        fOut = new FileOutputStream(myFile.getAbsoluteFile(),true);
        myOutWriter = new OutputStreamWriter(fOut);

                    //write to CSV
        myOutWriter.write(row);
        myOutWriter.flush();
        System.out.println("write to student csv .....");

    } catch (Exception e) {
    e.printStackTrace();
    }

Now check your sdcard/MyApp/Student.csv file

Upvotes: 1

Ab5
Ab5

Reputation: 606

First include the permission:

android.permission.WRITE_EXTERNAL_STORAGE

You will have to use FileOutputStream :

File externalStorageDir = Environment.getExternalStorageDirectory();
File myFile = new File(externalStorageDir , "mysdfile.txt");

if(myFile.exists())
{
   try
   {
       FileOutputStream fOut = new FileOutputStream(myFile);
       OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
       myOutWriter.append(string);
       myOutWriter.close();
       fOut.close();
   } catch(Exception e)
      {

      }
}
 else
  {
    myFile.createNewFile();
   }

Before Writing the string into the file append the String in order you want to store the details:

StringBuffer string = new StringBuffer();

then you can simply use :

string.append(editText1.getText());
string.append("  ;  ");
string.append(editText2.getText());
string.append("  ;  ");
string.append(editText3.getText());

Upvotes: 2

nikis
nikis

Reputation: 11234

Just create a tab-delimited file with header and then add new values to the end of this file. Take a look here http://docs.oracle.com/javase/tutorial/essential/io/

Upvotes: 1

Related Questions