I got button wich save changes, and put this in internal storage, then when app start I want to read file if there is any ofc. i thought that would be enought but im fresh coder and dunno that is good.
I dont know where is mistake, and also that is good code, pls help me becous i stuck
My code:
public class MyGameDetailsFragment extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_my_game_details, container, false);
try {
FileInputStream is = getActivity().openFileInput(file);
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
is.close();
} catch(OutOfMemoryError om) {
om.printStackTrace();
} catch(Exception ex) {
ex.printStackTrace();
}
String result = sb.toString();
saveBtn = (Button) view.findViewById(R.id.savechangesbtn);
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Data1 = s1.getText().toString();
Data2 = s2.getText().toString();
Data3 = s3.getText().toString();
Data4 = s4.getText().toString();
Data5 = s5.getText().toString();
Data6 = s6.getText().toString();
try {
FileOutputStream fos=getActivity().openFileOutput(file, getActivity().MODE_PRIVATE);
ObjectOutputStream outputStream = new ObjectOutputStream(fos);
outputStream.write(Data1.getBytes());
outputStream.write(newline.getBytes());
outputStream.write(Data2.getBytes());
outputStream.write(newline.getBytes());
outputStream.write(Data3.getBytes());
outputStream.write(newline.getBytes());
outputStream.write(Data4.getBytes());
outputStream.write(newline.getBytes());
outputStream.write(Data5.getBytes());
outputStream.write(newline.getBytes());
outputStream.write(Data6.getBytes());
outputStream.close();
//Toast.makeText(context,"file saved",Toast.LENGTH_SHORT).show();
}catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream inputStream = getActivity().openFileInput(file);
BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
r.close();
inputStream.close();
Log.d("File", "File contents: " + total);
} catch (Exception e) {
e.printStackTrace();
}
}
});
return view;
}
}
Ps: s1,s2 etc are created in code etc
Permission
<uses-permission android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Other = (TextView) view.findViewById(R.id.Details);
OtherD = (TextView) view.findViewById(R.id.OtherDetails);
try {
FileInputStream is = getActivity().openFileInput(file);
byte[] input = new byte[is.available()];
while(is.read(input) != -1){
value += new String(input);
}
is.getFD().sync();
//is.flush();
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String[] strArray = value.split(";");
s1.setText(strArray[1]);
s2.setText(strArray[2]);
s3.setText(strArray[3]);
s4.setText(strArray[4]);
s5.setText(strArray[5]);
s6.setText(strArray[6]);
s7.setText(strArray[7]);
saveBtn = (Button) view.findViewById(R.id.savechangesbtn);
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Data1 = s1.getText().toString();
Data2 = s2.getText().toString();
Data3 = s3.getText().toString();
Data4 = s4.getText().toString();
Data5 = s5.getText().toString();
Data6 = s6.getText().toString();
Data7= s7.getText().toString();
try {
FileOutputStream fos=getActivity().openFileOutput(file, getActivity().MODE_PRIVATE);
ObjectOutputStream outputStream = new ObjectOutputStream(fos);
outputStream.write(string3.getBytes());
outputStream.write(Data1.getBytes());
outputStream.write(string3.getBytes());
outputStream.write(Data2.getBytes());
outputStream.write(string3.getBytes());
outputStream.write(Data3.getBytes());
outputStream.write(string3.getBytes());
outputStream.write(Data4.getBytes());
outputStream.write(string3.getBytes());
outputStream.write(Data5.getBytes());
outputStream.write(string3.getBytes());
outputStream.write(Data6.getBytes());
outputStream.write(string3.getBytes());
outputStream.write(Data7.getBytes());
outputStream.write(string3.getBytes());
//outputStream.getFD().sync();
outputStream.flush();
outputStream.close();
//Toast.makeText(context,"file saved",Toast.LENGTH_SHORT).show();
}catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream inputStream = getActivity().openFileInput(file);
BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
r.close();
inputStream.close();
Log.d("File", "File contents: " + total);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Solve it on my own
First of all i would suggest you that, Dont write code in OnCreateView() method in fragments, always write code in OnViewCreated method.
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_my_game_details, container, false);
return view;
}
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
try {
FileInputStream is = getActivity().openFileInput(file);
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
is.close();
} catch(OutOfMemoryError om) {
om.printStackTrace();
} catch(Exception ex) {
ex.printStackTrace();
}
String result = sb.toString();
saveBtn = (Button) view.findViewById(R.id.savechangesbtn);
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Data1 = s1.getText().toString();
Data2 = s2.getText().toString();
Data3 = s3.getText().toString();
Data4 = s4.getText().toString();
Data5 = s5.getText().toString();
Data6 = s6.getText().toString();
try {
FileOutputStream fos=getActivity().openFileOutput(file, getActivity().MODE_PRIVATE);
ObjectOutputStream outputStream = new ObjectOutputStream(fos);
outputStream.write(Data1.getBytes());
outputStream.write(newline.getBytes());
outputStream.write(Data2.getBytes());
outputStream.write(newline.getBytes());
outputStream.write(Data3.getBytes());
outputStream.write(newline.getBytes());
outputStream.write(Data4.getBytes());
outputStream.write(newline.getBytes());
outputStream.write(Data5.getBytes());
outputStream.write(newline.getBytes());
outputStream.write(Data6.getBytes());
outputStream.close();
//Toast.makeText(context,"file saved",Toast.LENGTH_SHORT).show();
}catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream inputStream = getActivity().openFileInput(file);
BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
r.close();
inputStream.close();
Log.d("File", "File contents: " + total);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
If you are facing any error, then Please write the stacktrace of error.
Thanks
Cheers!! Simplicity is the best!
Related
I've created Test.txt on sdcard and write string "test example" on it.
after that, I replace string "test" by "etc" in Test.txt.
this is my code :
String origin_str, old_str , new_str;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_t2);
origin_str = "test example";
old_str = "test";
new_str = "etc";
Button bt_create2 = (Button)findViewById(R.id.bt_createfileT2);
bt_create2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
File newFolder = new File(Environment.getExternalStorageDirectory(), "TestFolder");
if (!newFolder.exists()) {
newFolder.mkdir();
}
File file = new File(newFolder, "Test" + ".txt");
if (!file.exists()) {
file.createNewFile();
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter myOutWriter =new OutputStreamWriter(fOut);
myOutWriter.append(origin_str);
myOutWriter.close();
fOut.close();
}
} catch (Exception e) {
System.out.println("e: " + e);
}
}
});
Button bt_replacefileT2 = (Button)findViewById(R.id.bt_replacefileT2);
bt_replacefileT2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
File file = new File(Environment.getExternalStorageDirectory() + "/TestFolder/Test.txt");
FileInputStream in = new FileInputStream(file);
int len = 0;
byte[] data1 = new byte[1024];
while ( -1 != (len = in.read(data1)) ){
if(new String(data1, 0, len).contains(old_str)){
String s = "";
s = s.replace(old_str, new_str);
}
}
}
catch (Exception e){
e.printStackTrace();
}
}
});
with this code, it was create Test.txt on sdcard and write "test example" on it.
but when replace string "test" by "etc", it not working.
how to fix it?
I will give my code, always worked for me :)
Hope thi can help you :DD
public void saveString(String text){
if(this.isExternalStorageAvailable()){
if(!this.isExternalStorageReadOnly()){
try {
FileOutputStream fos = new FileOutputStream(
new File(this.getExternalFilesDir("text"), "text.dat"));
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeBytes(text);
oos.close();
fos.close();
} catch (FileNotFoundException e) {
//Toast.makeText(main, "Eror opening file", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
//Toast.makeText(main, "Eror saving String", Toast.LENGTH_SHORT).show();
}
}
}
}
private static boolean isExternalStorageAvailable(){
String estadoSD = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED.equals(estadoSD))
return true;
return false;
}
private static boolean isExternalStorageReadOnly(){
String estadoSD = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED_READ_ONLY.equals(estadoSD))
return true;
return false;
}
public String getString(){
FileInputStream fis = null;
ObjectInputStream ois = null;
if(this.isExternalStorageAvailable()) {
try {
fis = new FileInputStream(
new File(this.getExternalFilesDir("text"), "text.dat"));
ois = new ObjectInputStream(fis);
String text = (String)ois.readObject();
return familia;
} catch (FileNotFoundException e) {
//Toast.makeText(main, "The file text doesnt exist", Toast.LENGTH_SHORT).show();
} catch (StreamCorruptedException e) {
//Toast.makeText(main, "Eror opening file", Toast.LENGTH_SHORT).show();
} catch(EOFException e){
try {
if(ois != null)
ois.close();
if(fis != null)
fis.close();
} catch (IOException e1) {
e1.printStackTrace();
}
} catch (IOException e) {
//Toast.makeText(main, "eror reading file", Toast.LENGTH_SHORT).show();
} catch (ClassNotFoundException e) {
//Toast.makeText(main, "String class doesnt exist", Toast.LENGTH_SHORT).show();
}
}
return null;
}
try this
File file = new File(Environment.getExternalStorageDirectory() + "/TestFolder/Test.txt");
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
line = line.replace(old,new);
}
br.close();
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter myOutWriter =new OutputStreamWriter(fOut);
myOutWriter.write(line);
myOutWriter.close();
fOut.close();
}
catch (IOException e) {
//You'll need to add proper error handling here
}
I am currently encountering a problem saving a text file on the internal storage.
The problem is that whenever i exit the application, the file seems to be deleted.
I wrote this method that is called at the start of the application, to create a blank text file :
private void init() {
String FILE_NAME = "save.txt";
try {
new BufferedWriter(new FileWriter(getFilesDir() + FILE_NAME));
Toast.makeText(this, "GOOD", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
this function is called to read all lines written in it :
private List<String> readFromFile() {
List<String> ret = new ArrayList<>();
try {
InputStream inputStream = new FileInputStream(getFilesDir()+"save.txt");
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = bReader.readLine()) != null) {
ret.add(line);
}
} catch (IOException e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
Toast.makeText(this, "GOOD", Toast.LENGTH_LONG).show();
return ret;
}
And finaly this method is called to append a string in the text file if it's not already in it :
private void save(String unNom) {
String FILE_NAME = "save.txt";
List<String> ret = new ArrayList<>();
try {
InputStream inputStream = new FileInputStream(getFilesDir()+"save.txt");
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = bReader.readLine()) != null) {
ret.add(line);
}
if(!ret.contains(unNom)){
ret.add(unNom);
}
bReader.close();
FileOutputStream fos = new FileOutputStream(getFilesDir() +FILE_NAME);
for (String ligne: ret) {
ligne+="\n";
fos.write(ligne.toString().getBytes());
}
fos.flush();
fos.close();
Toast.makeText(this, "GOOD", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
What should I do to save correctly the file in the internal storage ?
Sorry for my bad english,
Thank you for your help !
The init was'nt necessary. I removed the method and I edited the save method, so it could create a new file if a not found exception was raised :
private void save(String unNom) {
String FILE_NAME = "save.txt";
List<String> ret = new ArrayList<>();
try {
InputStream inputStream = openFileInput("save.txt");
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = bReader.readLine()) != null) {
ret.add(line);
}
if (!ret.contains(unNom)) {
ret.add(unNom);
}
bReader.close();
FileOutputStream fos = null;
fos = openFileOutput("save.txt", this.MODE_PRIVATE);
for (String ligne : ret) {
ligne = "\n" + ligne;
fos.write(ligne.getBytes());
}
fos.close();
Toast.makeText(this, "GOOD", Toast.LENGTH_LONG).show();
} catch (Exception e) {
try {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
FileOutputStream fos = null;
fos = openFileOutput("save.txt", this.MODE_PRIVATE);
fos.write(unNom.getBytes());
fos.close();
Toast.makeText(this, "NEW FILE", Toast.LENGTH_LONG).show();
}
catch(Exception e2){}
}
}
I have been working on this for a while and I am about to pull my hair out!!
If I use this...
public void readFile() {
BufferedReader buffReader = null;
StringBuilder result = new StringBuilder();
try {
FileInputStream fileIn = openFileInput("VariableStore.txt");
buffReader = new BufferedReader(new InputStreamReader(fileIn));
String line;
while ((line = buffReader.readLine()) != null) {
result.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
assert buffReader != null;
buffReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
String resultString = result.toString();
String[] controlString = resultString.split("$");
// String wb = controlString[4];
// String sb = controlString[5];
((Button) this.findViewById(R.id.wakeButton)).setText(resultString);
// ((Button) this.findViewById(R.id.sleepButton)).setText(sb);
// ((Button)this.findViewById(R.id.wakeButton)).setText(result);
// ((Button)this.findViewById(R.id.wakeButton)).setText(result);
// ((Button)this.findViewById(R.id.wakeButton)).setText(result);
}
The Button.setText works fine with "resultString" or with "result" which is a string I have input formatted as xxx$xxx$xxx$xxx$xxx so when I read it back in with the readFile() I want to use .Split and put it into an array "controlString" and then assign the array elements to my widgets i.e. setText(controlString[0]); but if I so much as even uncomment the lines String wb = controlString[4]; or String sb = controlString[5]; my program crashes. Why wont the array elemts work here?
Here is my writeFile().... (Which works perfectly.
public void writeFile() {
BufferedWriter buffWriter = null;
String wb = ((Button)this.findViewById(R.id.wakeButton)).getText().toString();
String sb = ((Button)this.findViewById(R.id.sleepButton)).getText().toString();
String tb = ((EditText)this.findViewById(R.id.textHoursBetween)).getText().toString();
String ti = ((EditText)this.findViewById(R.id.textIncrementTime)).getText().toString();
String td = ((EditText)this.findViewById(R.id.textIncrementDays)).getText().toString();
String writeString = wb + "$" + sb + "$" + tb + "$" + ti + "$" + td;
try {
FileOutputStream fileOut = openFileOutput("VariableStore.txt", Context.MODE_PRIVATE);
buffWriter = new BufferedWriter(new OutputStreamWriter(fileOut));
try {
buffWriter.write(writeString);
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
try {
assert buffWriter != null;
buffWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I found the problem...
Instead of this:
String[] controlString = resultString.split("$");
I had to use this:
String[] controlString = resultString.split(Pattern.quote("$"));
I have succesfully saved int values to sd but cant read. It always gives numberformat information. I made all logics, but cant find why it gives error.
Here is my code ;
this my constant
private final static String EXTERNAL_FILES_DIR = "ARDROID";
private final static String FILE_NAME = "turkcell.txt";
private boolean isThereAnySavedFile = false;
when this method called, it tries to open file, if file does not exist, create the file
public void anySavedDataInSD() {
String textFromSD = String.valueOf(read());
if (isThereAnySavedFile) {
int numberOfSendedSMS = Integer.parseInt(textFromSD.toString());
numberOfSendedSMS++;
writeToSD(String.valueOf(numberOfSendedSMS));
} else {
int first=60;
String g = String.valueOf(first);
writeToSD(g);
}
}
this method for writing
private void write(File file, String msg) {
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(file);
outputStream.write(msg.getBytes());
Logger.info("oldu bu kez");
} catch (IOException e) {
Logger.info("oldu bu kez2" + e);
} finally {
Logger.info("oldu bu kez3");
try {
if (outputStream != null)
outputStream.close();
} catch (IOException exception) {
}
}
}
this methof for reading
public StringBuilder read() {
StringBuilder textBuilder = new StringBuilder();
BufferedReader reader = null;
try {
File externalFilesDir = getExternalFilesDir(EXTERNAL_FILES_DIR);
File file = new File(externalFilesDir, FILE_NAME);
Logger.info("oldu2");
reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
textBuilder.append(line);
textBuilder.append("\n");
}
isThereAnySavedFile = true;
} catch (FileNotFoundException e) {
Logger.info("oldu3");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return textBuilder;
}
I am using the code below to read the the txt files from my SD card, but how can I display it as Text View?
try{
File f = new File(Environment.getExternalStorageDirectory()+"/filename.txt");
FileInputStream fileIS = new FileInputStream(f);
BufferedReader buf = new BufferedReader(new InputStreamReader(fileIS));
String readString = new String();
//just reading each line and pass it on the debugger
while((readString = buf.readLine())!= null){
Log.d("line: ", readString);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
This should do it :
public void displayOutput()
{
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard,"/TextFile.txt");
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
}
catch (IOException e) {
Toast.makeText(getApplicationContext(),"Error reading file!",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
catch (FileNotFoundException e) {
Toast.makeText(getApplicationContext(),"File not found!",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
TextView output=(TextView) findViewById(R.id.output);
// Assuming that 'output' is the id of your TextView
output.setText(text);
}
LinearLayout myVerticalLinearLayout = (LinearLayout) findViewById(R.id.myLinearLayout);
TextView text = new TextView(getApplicationContext());
text.setText(readString);
myVerticalLinearLayout.addView(text);
That should add vertical text views in a linear layout you should have created before.
public String readText(){
//this is your text
StringBuilder text = new StringBuilder();
try{
File f = new File(Environment.getExternalStorageDirectory()+"/filename.txt");
FileInputStream fileIS = new FileInputStream(f);
BufferedReader buf = new BufferedReader(new InputStreamReader(fileIS));
String readString = "";
//just reading each line and pass it on the debugger
while((readString = buf.readLine())!= null){
Log.d("line: ", readString);
text.append(readString + "\n");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
return text.toString();
}
...
TextView tv=findViewById(.....);
tv.setText(readText());
public class ReadFileActivity extends Activity {
/** Called when the activity is first created. */
TextView text;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text=(TextView)findViewById(R.id.textview);
text.setText(readTxt());
}
private String readTxt(){
InputStream inputStream = getResources().openRawResource(R.raw.aaa);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i;
try {
i = inputStream.read();
while (i != -1)
{
byteArrayOutputStream.write(i);
i = inputStream.read();
}
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return byteArrayOutputStream.toString();
}
}