1

I'm a newbie in programming on Android Studio. I'm trying to create a simple application to gain basic experience. In the application, I would need to store individual inputs to a file (ideally CSV) in internal memory. First of all, I am trying to save user data - my name and phone number. The save method looks like this:

public void save(View view)
    {
        String fileName = "user.csv";
        ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
        File directory = contextWrapper.getDir(getFilesDir().getName(), ContextWrapper.MODE_PRIVATE);
        File file = new File(directory, fileName);

        String data = "FirstName,LastName,PhoneNumber";
        FileOutputStream outputStream;
        try {
            outputStream = openFileOutput(fileName, Context.MODE_PRIVATE);
            outputStream.write(data.getBytes());
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
    }

The data seems to be saved and I'm redirected to MainActivity. Here is the method:

protected void onCreate(Bundle savedInstanceState) {
    File file = new File(getFilesDir(),"user.csv");
    if(!file.exists()) {
        Intent intent = new Intent(this, activity_login.class);
        startActivity(intent);
    }
    else {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView tv_name = findViewById(R.id.tv_name);
        TextView tv_phone = findViewById(R.id.tv_phone);

        BufferedReader br = null;
        try {
            String sCurrentLine;
            br = new BufferedReader(new FileReader("user.csv"));
            while ((sCurrentLine = br.readLine()) != null) {
                tv_name.setText(sCurrentLine);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null)br.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

No value is stored in TextView tv_name and the box is empty. Where am I making mistake?

Thank you very much for your help!

Mangesh Pawar
  • 309
  • 1
  • 14
  • try using local database, it will be more easier to implement and is more secure rather than writing to csv. – karan Jan 22 '19 at 10:12
  • did you try to use the same code as writing to the file for opening it, with ContextWrapper? Is the file on the onCreate contains data? – Leze Jan 22 '19 at 10:22

3 Answers3

0

Use as this to read file:

FileInputStream fis = new FileInputStream("your full file path");
BufferedReader bfr = new BufferedReader(new InputStreamReader(fis));
DB377
  • 403
  • 4
  • 11
0

Below is the code for creating .csv file and inserting data into it.

For more look into my answer :https://stackoverflow.com/a/48643905/8448886

CODE HERE:

    String csv = (Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyCsvFile.csv"); // Here csv file name is MyCsvFile.csv


    //by Hiting button csv will create inside phone storage.
      buttonAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            CSVWriter writer = null;
                try {
                    writer = new CSVWriter(new FileWriter(csv));

                    List<String[]> data = new ArrayList<String[]>();
                    data.add(new String[]{"Country", "Capital"});
                    data.add(new String[]{"India", "New Delhi"});
                    data.add(new String[]{"United States", "Washington D.C"});
                    data.add(new String[]{"Germany", "Berlin"});

                    writer.writeAll(data); // data is adding to csv 

                    writer.close();
                    callRead();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
Abhishek kumar
  • 4,347
  • 8
  • 29
  • 44
0

For reading data saved use this method uses, UTF_8 ENCODING

public static String readAsString(InputStream is) throws IOException {
    BufferedReader reader = null;
    StringBuilder sb = new StringBuilder();
    try {
        String line;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            reader = new BufferedReader(new InputStreamReader(is,UTF_8));
        }
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
    } finally {
        if (reader != null) {
            reader.close();
        }
    }
    return sb.toString();
}

Use this method as follows, parsing file "user.csv".

public static String readFileAsString(File file) throws IOException {
    return readAsString(new FileInputStream(file));
}

Fetch string and set textView

nyulan
  • 311
  • 3
  • 12