InnocentKiller
InnocentKiller

Reputation: 5234

Android : Reading File

I am trying to get last 10 rows from file but not able to fetch.

i have two activities: in the first, i want to write text from an EditText to a file. in the second activity i try to read the stored data and write it to a textView

public class Date_Location extends Activity {

ImageView imageView;
EditText editTextDate, editTextLocation, editTextEdit;

private static final String TAG = Date_Location.class.getName();
private static final String FILENAME = "myFile.txt";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.date_location);

    editTextDate = (EditText) findViewById(R.id.editText1);
    editTextLocation = (EditText) findViewById(R.id.editText2);
    editTextEdit = (EditText) findViewById(R.id.editText3);
    imageView = (ImageView) findViewById(R.id.next);
}

public void goNext(View view) {
    String Date = editTextDate.getText().toString();
    String Location = editTextLocation.getText().toString();
    String Comment = editTextEdit.getText().toString();

    writeToFile(Date);
    writeToFile(Location);
    writeToFile(Comment);

    Intent intent = new Intent(this, Detail_Data.class);
    startActivity(intent);
    Date_Location.this.finish();
}

private void writeToFile(String data) {
    String newline = "\r\n";
    try {

        OutputStreamWriter oswName = new OutputStreamWriter(openFileOutput(
                FILENAME, Context.MODE_APPEND));
        oswName.write(newline);
        oswName.write(data);
        oswName.close();
    } catch (IOException e) {
        Log.e(TAG, "File write failed: " + e.toString());
    }
}
}

And my second Activity is below

public class Detail_Data extends Activity {

TextView textView1;
ImageView imageView;
private static final String FILENAME = "myFile.txt";

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

    textView1 = (TextView) findViewById(R.id.textView1);
    imageView = (ImageView) findViewById(R.id.imageView2);

    String date = readFromFile();
    textView1.setText(date);

}

private String readFromFile() {
    String ret = "";

    try {
        InputStream inputStream = openFileInput(FILENAME);
        ArrayList<String> bandWidth = new ArrayList<String>();

        if (inputStream != null) {
            InputStreamReader inputStreamReader = new InputStreamReader(
                    inputStream);
            BufferedReader bufferedReader = new BufferedReader(
                    inputStreamReader);
            String receiveString = "";
            StringBuilder stringBuilder = new StringBuilder();

            while ((receiveString = bufferedReader.readLine()) != null) {
                 stringBuilder.append(receiveString+'\n');
                 bandWidth.add(receiveString);
                 if (bandWidth.size() == 10)
                  bandWidth.remove(0);
                }
            ret = stringBuilder.toString();
            inputStream.close();
        }
    } catch (FileNotFoundException e) {
        Log.i("File not found", e.toString());
    } catch (IOException e) {
        Log.i("Can not read file:", e.toString());
    }
    return ret;
}

public void goNext(View view) {
    imageView.setColorFilter(0xFFFF3D60, PorterDuff.Mode.MULTIPLY);

    Intent intent = new Intent(this, Agreement.class);
    startActivity(intent);
    Detail_Data.this.finish();
}
}

please if any one have any idea then help me. I have tried with other solution too but then also i am not getting last 10 records. Instead of last 10 data i am getting all the records which is written in file.

Upvotes: 1

Views: 4888

Answers (3)

gokaka
gokaka

Reputation: 136

Firstly, If you are writing file on SDcard, be sure that you have added the uses-permission tag in AndroidManifest.xml

<uses-permission Android:name="Android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

Secondly, don't forget flush()

oswName.write(data);
oswName.flush();
oswName.close();

Then, there is something wrong with your readFromFile() method, remove this line from while loop

stringBuilder.append(receiveString+'\n');

and add this right after the while loop

for(String str : bandWidth)
    stringBuilder.append(str + "\n");

readFromFile() should be like following

private String readFromFile() {
    String ret = "";

    try {
        InputStream inputStream = openFileInput(FILENAME);
        ArrayList<String> bandWidth = new ArrayList<String>();

        if (inputStream != null) {
            InputStreamReader inputStreamReader = new InputStreamReader(
                    inputStream);
            BufferedReader bufferedReader = new BufferedReader(
                    inputStreamReader);
            String receiveString = "";
            StringBuilder stringBuilder = new StringBuilder();

            while ((receiveString = bufferedReader.readLine()) != null) {
                 bandWidth.add(receiveString);
                 if (bandWidth.size() == 10)
                  bandWidth.remove(0);
                }

            for(String str : bandWidth)
                stringBuilder.append(str + "\n");

            ret = stringBuilder.toString();
            inputStream.close();
        }
    } catch (FileNotFoundException e) {
        Log.i("File not found", e.toString());
    } catch (IOException e) {
        Log.i("Can not read file:", e.toString());
    }
    return ret;
}

Upvotes: 1

Maxim Shoustin
Maxim Shoustin

Reputation: 77904

You store each line to list and remove 0 position only if list size = 10

So as 1st step store all file in list:

Instead

while ((receiveString = bufferedReader.readLine()) != null) {
             stringBuilder.append(receiveString+'\n');
             bandWidth.add(receiveString);
             if (bandWidth.size() == 10)
              bandWidth.remove(0);
            }

Write

while ((receiveString = bufferedReader.readLine()) != null) {
             stringBuilder.append(receiveString+'\n');
             bandWidth.add(receiveString);                
            }

After copy last 10 lines to new list.

For example if you have :

List<String> bandWidth = new ArrayList<String>(Arrays.asList("a1", "a2", "a3","a4", "a5", "a6","a7", "a8", "a9","a10", "a11", "a12"));

Than with subList:

List<String> bandWidth10rows= bandWidth.subList(bandWidth.size()-10, bandWidth.size());

It will copy last 10 list items to new list.

Totally it should be something like:

while ((receiveString = bufferedReader.readLine()) != null) {
             stringBuilder.append(receiveString+'\n');
             bandWidth.add(receiveString);                
            }
List<String> bandWidthLastTenRows= bandWidth.subList(bandWidth.size()-10, bandWidth.size()); 

Upvotes: 0

Didac Perez Parera
Didac Perez Parera

Reputation: 3814

After opening the input/output stream, use that methods:

import java.io.FileInputStream;
import java.io.FileOutputStream;

public class Files {

    public static String readStringFile(FileInputStream fis) throws java.io.IOException {
        StringBuffer fileContent = new StringBuffer("");

        byte[] buffer = new byte[1024];

        while (fis.read(buffer) != -1) {
            fileContent.append(new String(buffer));
        }

        return fileContent.toString();
    }

    public static void writeStringFile(FileOutputStream fos, String text) throws java.io.IOException {
        fos.write(text.getBytes());
    }
}

First, create the FileInputStream or FileOutputStream with your desired file name and then call the methods above. Please notice that the methods only work for reading and writing strings.

Upvotes: 0

Related Questions