0

I am trying to write and read to a text file name students but I am having all kinds of hassles I am very new to android programming so I am trying this out for the first time. I have looked at code here and there to try and figure out what I am doing wrong but I cant find one specific thing to help, this question has probably been asked a couple of times, so I am sorry for asking it again. Please see my different .xml and .java files below. The actual question is to be able to write data to a textfile and from the main screen click on a textfield which will take you to the edit screen, where you get to edit that specific field and save it to a text file (this however has not been done yet as I am still struggling to figure out why my writing and reading to the textfile is not working, I hope my poor attempt at coding will shed some light on the matter. Please don't crucify me for my bad coding I am super new to android

/////////////////////////////add screen.java///////////////////////////////

public class AddNew extends Activity {
private static final String newLine = System.getProperty("line.separator");
TextView txtText; 
EditText Modules;
EditText Types;

@Override
protected void onCreate(Bundle SavedInstanceState){
    super.onCreate(SavedInstanceState);
    setContentView(R.layout.add);

    txtText = (TextView)findViewById(R.id.textView1);
    Modules = (EditText)findViewById(R.id.etMod);
    Types = (EditText)findViewById(R.id.etType);

Button backMan = (Button)findViewById(R.id.btnBackMain);
backMan.setOnClickListener(new OnClickListener(){
  public void onClick(View v){
  //This is where your code will go
      startActivity(new Intent(AddNew.this, MainActivity.class));
  }
});  //end back Button

//get the day, month & year from the Date picker
DatePicker myDPicker = (DatePicker)findViewById(R.id.dpDate);
Integer Year = myDPicker.getYear();
Integer Month = myDPicker.getMonth();
Integer Day = myDPicker.getDayOfMonth();
StringBuilder sb = new StringBuilder();
sb.append(Year.toString()).append("-").append(Month.toString()).append
("-").append(Day.toString());
final String dobStr=sb.toString();

txtText.setText("TEST");

Button Save = (Button)findViewById(R.id.btnSaveAdded);
Save.setOnClickListener(new OnClickListener(){
public void onClick(View v){
 //This is where your code will go       
try {
    writeToFile(Modules.getText().toString(),    
Types.getText().toString(),dobStr);

} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}    
 }

private void writeToFile(String Mod, String AsType, String dobDate) throws
 IOException {
    // TODO Auto-generated method stub
    //String textTofile;
    StringBuilder sbText = new StringBuilder();
    sbText.append(Mod + "," + dobStr + "," + AsType);
    //textTofile=sbText.toString();


        String fileName = "student";
        PrintWriter printWriter = null;
        File file = new File(fileName);
        try {
            if (!file.exists()) file.createNewFile();
            printWriter = new PrintWriter(new FileOutputStream(fileName, 
        true));
            printWriter.write(newLine ); //+textTofile);
        } catch (IOException ioex) {
            ioex.printStackTrace();
        } finally {
            if (printWriter != null) {
                printWriter.flush();
                printWriter.close();
        }
    }               
}

}); //end back Button

}

}

`public class MainActivity extends Activity { TextView fDisplay; TextView fTest; int numItems=0; //use it later to keep track of the number of items. String inText; //use this variable for the information read in from the textfile.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button but1=(Button)findViewById(R.id.btnAdd);
    but1.setOnClickListener(new OnClickListener(){

      public void onClick(View v){
      //This is where your code will go
          startActivity(new Intent(MainActivity.this, AddNew.class));
      }
    });  //end but1

    Button but2 = (Button)findViewById(R.id.btnEditCur);
    but2.setOnClickListener(new OnClickListener(){

      public void onClick(View v){
      //This is where your code will go
          startActivity(new Intent(MainActivity.this, EditCur.class));
      }
    });  //end of button 2

    fDisplay = (TextView)findViewById(R.id.tvAssign1); 


    try {
    readFromFile();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 

}

private void readFromFile() throws IOException {
     // TODO Auto-generated method stub
    // String ret="";
    BufferedReader br;
    FileReader fr = null;
    try {
        fr = new FileReader("student");
        br = new BufferedReader(fr);
        String line = br.readLine();
        while (null != line) {
            fDisplay.append(line);
            fDisplay.append("\n");
            line = br.readLine();
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (null != fr) {
            try {
                fr.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }



    }

} `

phenom5001
  • 19
  • 5

3 Answers3

0

For writting on a file I have used this

String filename;
String content;

filename = "PATH_AND_FILE";
content = "CONTENT ON THE FILE"

BufferedWriter out = new BufferedWriter(new FileWriter(filename));
                            out.write(myString.toString());  
                            out.flush();  
                            out.close(); 

And for reading I have this function:

public static String readFileAsString() {
    String result = "";
String filename;

filename = "PATH_AND_FILE";
    File file = new File(filename);
    if ( file.exists() ) {
        FileInputStream fis = null;
        try {                   fis = new FileInputStream(file);
            char current;
            while (fis.available() > 0) {
                current = (char) fis.read();
                result = result + String.valueOf(current);
            }
        } catch (Exception e) {
            // System.out.println("DEBUG Exception String :"+ e.toString());
        } finally {
            if (fis != null)
            { try {
                fis.close();
            } catch (IOException ignored) {
            }}
            else {// System.out.println("DEBUG Exception String NULL");
            }
        }
        return result;
    }
    else
    {
        return "DEFAULT CONTENT";
    }
}
Armando SM
  • 142
  • 5
0

In Android, the file' directory is different then that on a PC, like :the files are stored in a directory related to your App, the accessing permissions are different. This link might be helpful:

How To Read/Write String From A File In Android

Community
  • 1
  • 1
Mr. M
  • 62
  • 1
  • 15
0

Two simple functions (Java) to read and write:

private static void writeToFile(String path, String text) {
        PrintWriter writer;
        try {
            writer = new PrintWriter(path, "UTF-8");
            writer.print(text);
            writer.close();
        } catch (FileNotFoundException | UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


public static String getFileContent(String filename){
        String everything = "";
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(filename));
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            StringBuilder sb = new StringBuilder();
            String line = null;
            try {
                line = br.readLine();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            while (line != null) {
                sb.append(line);
                sb.append(System.lineSeparator());
                try {
                    line = br.readLine();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            everything = sb.toString();
        } finally {
            try {
                br.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return everything;
    }
Vyacheslav
  • 26,359
  • 19
  • 112
  • 194