0

I have a list strings:

abc
def
xyz

I am writing code to insert each string (from first row to last row) to file by click a button. That means I need click three times on the button to insert all string to a file. After that, I have other button to display the data to gridview. Each row of gridview corresponds to each string such as

1. abc (1. is just index of gridview row)
2. def
3. xyz

For my task, I want to find a simple solution to do it by using android. I know that we can save it in sql or text file. What is simpler solution for my task? For saving in text file, how to distinguish between two strings in the file? If it is possible, could you give me the code? thanks

This is my solution for wring text file

String filepath = Environment.getExternalStorageDirectory().getPath();
String filename=filepath+"/" + FOLDER +  "/" + "list.txt"   ;   
FileOutputStream fop = null;
File file = null;

try {
    file =new File(filename);
    fop=new FileOutputStream(file,true);
    // if file doesn't exists, then create it
    if (!file.exists()) {
        file.createNewFile();
    }

    // get the content in bytes
    byte[] contentInBytes = filecontent.getBytes();

    fop.write(contentInBytes);
    fop.flush();
    fop.close();

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

However, output is abcdefxyz. It is very difficult to classify them.

2
  • A little notice. Use a recyclerview. Its much better than gridview Commented Sep 27, 2015 at 13:43
  • i suggest using sqlite. also using recyclerview will be a better option. Commented Sep 27, 2015 at 13:52

1 Answer 1

1

Well if you have

string[] items={abc,def,xyz};

writing to file

OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("filename.txt", Context.MODE_PRIVATE));
   for(String data : items)
   {
        outputStreamWriter.write(data);
   }
        outputStreamWriter.close();

Reading from File

 InputStream inputStream = openFileInput("filename.txt");

        if ( inputStream != null ) {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String receiveString = "";
            ArrayList<String> data = new ArrayList<String>();

            while ( (receiveString = bufferedReader.readLine()) != null ) {
                data.Add(receiveString);
            }

            inputStream.close();

in Grid View Adpater use data ArrayList

Sign up to request clarification or add additional context in comments.

1 Comment

Thank rajan ks. However, I am working in a class which is TestThread extends Thread. How to use your function openFileOutput?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.