Reputation: 67
I'm trying to get my app to write text into a text file from an EditText and read from it into a TextView. It never updated the TextView earlier and now the app is crashing. Any advise would be very appreciated!
public class MainActivity extends Activity implements OnClickListener {
String file = Environment.getExternalStorageDirectory() + "/CSCI598.txt";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button rea = (Button) findViewById(R.id.reads1);
rea.setOnClickListener(this);
Button ap = (Button) findViewById(R.id.appends1);
ap.setOnClickListener(this);
}
private void toast(String text)
{
Context context = getApplicationContext();
Toast toast = Toast.makeText(context, text, Toast.LENGTH_LONG);
toast.show();
}
@SuppressWarnings("resource")
@Override
public void onClick(View v) {
TextView tv=(TextView)findViewById(R.id.textView1);
EditText et=(EditText)findViewById(R.id.editText1);
switch(v.getId()) {
case R.id.reads1:
try
{
FileInputStream fis = new FileInputStream(file);
BufferedReader bfr = new BufferedReader(new InputStreamReader(fis));
String in;
StringBuffer stringBuffer = new StringBuffer();
while ((in = bfr.readLine()) != null) {
stringBuffer.append(in + "\n");
}
tv.setText(stringBuffer.toString());
toast("File successfully loaded.");
}
catch (Exception ex)
{
toast("Error loading file: " + ex.getLocalizedMessage());
}
break;
case R.id.appends1:
String txt=et.getText().toString();
try
{
FileWriter writer = new FileWriter(file);
writer.write(txt);
writer.flush();
writer.close();
toast("File successfully saved.");
}
catch (Exception ex)
{
toast("Error saving file: " + ex.getLocalizedMessage());
}
break;
}
}
}
Upvotes: 0
Views: 867
Reputation: 1518
Get the sdcard directory using Environment.getExternalStorageDirectory()
. Try changing this line in you code:
String file = "sdcard/CSCI598.txt";
With:
String file = Environment.getExternalStorageDirectory() + "/CSCI598.txt";
Also, as @Yahya mentioned make sure you have this permission in your android manifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
If this doesn't work. Try reading the file like this:
FileReader fr = new FileReader(file);
BufferedReader inputReader = new BufferedReader(fr);
Then use your while loop as it is right now.
Write the file like this
FileWriter out = new FileWriter(file, true);
out.write(txt + "\n");
out.close();
Upvotes: 2
Reputation: 1626
Provide crash log.
<
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"><
/uses-permission>
Instead of using hard coded path like String file = "sdcard/CSCI598.txt"; use below
String file = Environment.getExternalStorageDirectory() + "/CSCI598.txt";
As you are using emulator have have you alot sd card space while creating AVD
Upvotes: 0