I am accessing a file from my fragment in my Android app. But my problem is that only 1 line of that file is being read.
My code is:
FragmentTab2.java
package com.adhish.pagertabstriptutorial;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class FragmentTab2 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Get the view from fragmenttab2.xml
View v = inflater.inflate(R.layout.fragmenttab2, container, false);
TextView txt = (TextView)v.findViewById(R.id.optext);
try
{
FileInputStream fIn = getActivity().openFileInput("sample_details.txt");
InputStreamReader in = new InputStreamReader(fIn);
BufferedReader bufferedReader = new BufferedReader(in);
//StringBuilder sb = new StringBuilder();
String line = null;
String str = "";
while ((line = bufferedReader.readLine()) != null) {
str += line;
}
txt.setText(str);
bufferedReader.close();
in.close();
}
catch (Exception e)
{
Log.e("File not found.",e.toString());
}
return v;
}
}
The code which writes the file (in a different fragment) is:
@Override
public void onClick(View view)
{
if(view == getView().findViewById(R.id.button1))
{
//Call all the elements of this Fragment here becuase they are accessible easily through
//getView(); method. Use the getText(); method to get the Text and toString(); to convert
//it.
String name = ((EditText)getView().findViewById(R.id.name)).getText().toString();
String email = ((EditText)getView().findViewById(R.id.email)).getText().toString();
if(name.isEmpty() || email.isEmpty())
{
Toast.makeText(getActivity(), "Cannot store empty values !", Toast.LENGTH_SHORT).show();
}
else
{
try
{
FileOutputStream fOut = getActivity().openFileOutput("sample_details.txt", Context.MODE_MULTI_PROCESS);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fOut);
outputStreamWriter.write(name + " " + email + ";");
Log.e("String Concat Done", "Concatenation of the Strings is done to write in the File. Write Success.");
outputStreamWriter.flush();
Log.e("Flush","Flush Success");
outputStreamWriter.close();
fOut.close();
Log.e("Stream Closed","Both Streams are flushed and closed");
Toast.makeText(getActivity(), "Submitted", Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{
Toast.makeText(getActivity(), "FAILED !", Toast.LENGTH_SHORT).show();
Log.e("Error in File Write",e.toString());
}
}
}
}
I don't know the correct way of implementing this. Please let me know in detail how to do it, because I am new to Android.
Thanks.