I have a read and write operation at a android app. On onCreate, a file will be read and display it to an editext and can be editted. When the save is pressed, the data will be written to the same file that will be read on onCreate. But I got an error. No such file in directory. I don't get it. I'm creating the file when the save button is pressed. Any ideas?
Java code:
EditText Name;
EditText Age;
EditText Height;
EditText Weight;
EditText MedHistory;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_medicalhistory);
Name = (EditText) findViewById(R.id.medhistName);
Age = (EditText) findViewById(R.id.medhistAge);
Height = (EditText) findViewById(R.id.medhistHeight);
Weight = (EditText) findViewById(R.id.medhistWeight);
MedHistory = (EditText) findViewById(R.id.MedHist);
int i = 0;
String MedHistData[] = new String[5];
try {
File myFile = new File("/data/data/Project.Package.Structure/files/MedicalHistory.txt");
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(new InputStreamReader(fIn));
String aDataRow = "";
while ((aDataRow = myReader.readLine()) != null)
{
MedHistData[i] = aDataRow;
i++;
}
i = 0;
Name.setText(MedHistData[0]);
Age.setText(MedHistData[1]);
Height.setText(MedHistData[2]);
Weight.setText(MedHistData[3]);
MedHistory.setText(MedHistData[4]);
myReader.close();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
Button Save = (Button) findViewById(R.id.SaveBtn);
Save.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
File myFile = new File("/data/data/Project.Package.Structure/files/MedicalHistory.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(Name.getText() + "\n");
myOutWriter.append(Age.getText() + "\n");
myOutWriter.append(Height.getText() + "\n");
myOutWriter.append(Weight.getText() + "\n");
myOutWriter.append(MedHistory.getText());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Medical History Saved'",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
});
}
You should use openFileInput() method to open file for reading and openFileOutput() for writing. These functions return a FileInputStream and FileOutputStream respectively.
My guess: you don't have write access to the file.
You only can access specific folders for writing in android.
Have a look at
http://developer.android.com/guide/topics/data/data-storage.html#filesInternal
They have a simple example on how to write a text file.
Related
This code receives information from an acquaintance you want to register in editText, and then clicks finButton to save the information you receive as a file called friendlist.txt.
However, the Toast message is outputted from the try-catch statement that is currently performed when finButton is pressed.
Also, the checkpermission does not work, which is wrapped in a try~catch statement, but does not have output on the logcat.
And manifest.
uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
is written.
Please let me know the solution.
And this content is written with a translator, so the sentence can be strange.
when you press finButton, the logcat is shown below.
The code corresponding to the 116th line is this.
FileOutputStream outstream = openFileOutput("friendList.txt", Activity.MODE_WORLD_WRITEABLE);
logcat
public class EnteringInformationOfFriendActivity extends AppCompatActivity {
Button finButton;
EditText phoneNumberEditText, nameEditText, emailEditText, groupEditText, memoEditText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_entering_information_of_friend);
phoneNumberEditText = (EditText) findViewById(R.id.phoneNumberEditText);
nameEditText = (EditText) findViewById(R.id.nameEditText);
emailEditText = (EditText) findViewById(R.id.emailEditText);
groupEditText = (EditText) findViewById(R.id.groupEditText);
memoEditText = (EditText) findViewById(R.id.memoEditText);
try{
checkPermission();
}
catch (Exception e){
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsStrting = sw.toString();
Log.e("CSP", exceptionAsStrting);
e.printStackTrace();
}
finButton = (Button) findViewById(R.id.finButton);
finButton.setOnClickListener(v -> {
try{
String phoneTxt = phoneNumberEditText.getText().toString().trim();
String nameTxt = nameEditText.getText().toString().trim();
String emailTxt = emailEditText.getText().toString().trim();
String groupTxt = groupEditText.getText().toString().trim();
String memoTxt = memoEditText.getText().toString().trim();
String friendInfoTxt = phoneTxt + "-" + nameTxt + "-" + emailTxt + "-" + groupTxt + "-" + memoTxt;
FileOutputStream outstream = openFileOutput("friendList.txt", Activity.MODE_WORLD_WRITEABLE);
outstream.write(friendInfoTxt.getBytes());
outstream.close();
Intent intent = new Intent(v.getContext(), FriendListActivity.class);
startActivity(intent);
} catch (Exception e){
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsStrting = sw.toString();
Log.e("Filesave", exceptionAsStrting);
e.printStackTrace();
Toast.makeText(this.getApplicationContext(), "Save failed.", Toast.LENGTH_SHORT).show();
}
});
}
public void checkPermission(){
if(checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}
}
}
Try with Context.MODE_APPEND or Context.MODE_PRIVATE instead of Activity.MODE_WORLD_WRITEABLE
my App saves the text of a multi-line EditView to a text file, but the problem is that if I restart my app, only the last line gets restored. (Perhaps it's also possible that the FileOutputStream only saves the last line, I am not sure ¯_(ツ)_/¯)
Here is my code:
private static final String TAG = "EditDataActivity";
public static String Textfile = "test.txt";
private Button btnSave,btnDelete;
private EditText editable_item;
EditText Zutaten, Zubereitung;
DatabaseHelper mDatabaseHelper;
private String selectedName;
private int selectedID;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_data_layout);
btnSave = (Button) findViewById(R.id.btnSave);
btnDelete = (Button) findViewById(R.id.btnDelete);
editable_item = (EditText) findViewById(R.id.editable_item);
mDatabaseHelper = new DatabaseHelper(this);
Zutaten = (EditText)findViewById(R.id.editText4);
Zubereitung = (EditText)findViewById(R.id.editText2);
Zutaten.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
try{
EditText test = (EditText)findViewById(R.id.editable_item);
String testText = test.getText().toString();
String Textfile2 = testText + ".txt";
EditText field = (EditText)findViewById(R.id.editText4);
String text = field.getText().toString();
FileOutputStream fos = openFileOutput(Textfile2, Context.MODE_PRIVATE);
fos.write(text.getBytes());
fos.close();
}catch (IOException e){
System.out.println("Error");
}
}
});
Intent receivedIntent = getIntent();
selectedID = receivedIntent.getIntExtra("id",-1); //NOTE: -1 is just the default value
selectedName = receivedIntent.getStringExtra("name");
editable_item.setText(selectedName);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try{
EditText test = (EditText)findViewById(R.id.editable_item);
String testText = test.getText().toString();
String Textfile2 = testText + ".txt";
EditText field = (EditText)findViewById(R.id.editText4);
String text = field.getText().toString();
FileOutputStream fos = openFileOutput(Textfile2, Context.MODE_PRIVATE);
fos.write(text.getBytes());
fos.close();
}catch (IOException e){
System.out.println("Error");
}
Toast.makeText(getApplicationContext(), "Rezept erfolgreich gespeichert!", Toast.LENGTH_SHORT).show();
Intent back = new Intent(EditDataActivity.this, MainActivity.class);
startActivity(back);
String item = editable_item.getText().toString();
if (!item.equals("")) {
mDatabaseHelper.updateName(item, selectedID, selectedName);
} else {
toastMessage("Du musst das Rezept benennen!");
}
}
});
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try{
EditText test = (EditText)findViewById(R.id.editable_item);
String testText = test.getText().toString();
String Textfile2 = testText + ".txt";
EditText field = (EditText)findViewById(R.id.editText4);
String text = field.getText().toString();
FileOutputStream fos = openFileOutput(Textfile2, Context.MODE_APPEND);
fos.write("".getBytes());
fos.close();
System.out.println("did it");
}catch (IOException e){
System.out.println("Error");
}
Intent back = new Intent(EditDataActivity.this, MainActivity.class);
startActivity(back);
mDatabaseHelper.deleteName(selectedID,selectedName);
editable_item.setText("");
toastMessage("Rezept erfolgreich gelöscht!");
}
});
}
private void toastMessage(String message){
Toast.makeText(this,message, Toast.LENGTH_SHORT).show();
}
public void loadsavedfile(){
try {
EditText test1 = (EditText) findViewById(R.id.editable_item);
String test1Text = test1.getText().toString();
String Textfile2 = test1Text + ".txt";
if (!Textfile2.isEmpty()) {
FileInputStream fis = openFileInput(Textfile2);
BufferedReader reader = new BufferedReader(new InputStreamReader(new DataInputStream(fis)));
String test;
EditText Test = (EditText) findViewById(R.id.editText4);
while ((test = reader.readLine()) != null) {
Test.setText(test);
}
}else{
}
}catch(IOException e){
}
Hope fully you can help me :)
Thanks!
Just do
while ((test = reader.readLine()) != null) {
Test.setText(Test.getText()+"\n" + test);
}
When you had setText(test) only it was replacing the text from the edit text every time the loop ran but you have to append the new text to the last line. A better way to do this would be to create the String first and then set it to EditText as it is better for performance.
StringBuilder str = new StringBuilder();
while((test = reader.readLine()) != null)
str.append('\n' + test);
Test.setText(str.toString());
Hope this solves your problem.
Now I have app which save and read some text into .txt file by button. How can I make that app save file after app closed and reading file when app opened automatically, without any click on buttons?
public class mAcitivity extends AppCompatActivity {
private Button btn_read, btn_save;
private TextView textView;
private String txt = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveFile();
}
});
btn_read.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
readFile();
textView.setText(txt);
}
});
}
public String readFile() {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/TEST");
myDir.mkdirs();
File file = new File(myDir, "file.txt");
try {
FileInputStream fis = new FileInputStream(file);
int size = fis.available();
byte[] buffer = new byte[size];
fis.read(buffer);
fis.close();
txt = new String(buffer);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(mActivity.this, "Error reading file", Toast.LENGTH_LONG).show();
}
return txt;
}
public void saveFile() {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/TEST");
myDir.mkdirs();
File file = new File(myDir, "file.txt");
if (file.exists()){ file.delete();}
try {
String sometxt = "Hello world";
FileOutputStream out = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(out);
pw.println(sometxt);
pw.flush();
pw.close();
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
You can use your MainActivity lifecycle callbacks to begin your I/O operations directly, or start BoundService which will operate them.
You can achieve this by putting your saveFile() method inside stop() lifecycle method, and putting your readFile() method inside start() lifecycle method. Activity will automatically call start() method once the application starts and it will call stop() method once the applicqtion closes/terminates.
I am trying to read in some data from a text file I created on my SDcard. However, when I am done reading it in, the stringbuilder is still blank. I don't know if it isn't reading the file. I looked on the android device monitor and the fie exists with data in it. It is on my sdcard inside a "Notes" directory. Here is the code.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
welcomeText = (TextView) findViewById(R.id.welcomeText);
userName = (EditText) findViewById(R.id.userName);
submitButton = (Button) findViewById(R.id.submitButton);
password = (EditText) findViewById(R.id.passInput);
viewAll = (Button) findViewById(R.id.viewAll);
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
generateNoteOnSD("info", userName.getText().toString() + "," +password.getText().toString() );
}
});
viewAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
File sdCard = Environment.getExternalStorageDirectory();
File file = new File(sdCard, "info");
String line;
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
}
catch (IOException e) {
}
welcomeText.setText("Welcome, " + text);
}
});
}
public void generateNoteOnSD(String sFileName, String sBody){
try
{
File root = new File(Environment.getExternalStorageDirectory(), "Notes");
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show();
}
catch(IOException e)
{
e.printStackTrace();
}
}
Try to change like below
viewAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "/Notes/info";
File myFile = new File(baseDir + File.separator + fileName);
try {
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String text = "";
String aDataRow = "";
while ((aDataRow = myReader.readLine()) != null) {
text += aDataRow + "\n";
}
}
catch (IOException e) {
}
welcomeText.setText("Welcome, " + text);
}
});
I have an EditText in which the user inputs their name, then i want to push a button and the content of the EditText is transferred into a file.
EDITED: I have this code so far:
Button submitButton = (Button) findViewById(R.id.baddNametoFile);
submitButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try{
ETName.getText().toString();
PrintWriter writer = new PrintWriter(new BufferedWriter(
new FileWriter("/sdcard/Accelerometer.html", true)));
writer.println("<h3 style=padding-left:20px;>" + ETName
+ "</h3><br>");
// new arraylist
writer.close();
}catch (IOException e) {
// put notification here later!!!
e.printStackTrace(); }
}
});
I have it printing to the file what the actual android value is:
android.widget.Button{......./baddNametoFile}
But that is just a placeholder to know the print works. I would like to see what the user has typed printed there instead.
Any help would be great. Thanks
ETName is probably EditText. You didnt post to much code so it should be like:
ETName.getText().toString(); Change View ETName in View v (it is click on a button not on a EditText). Lets try like this:
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try{
String etName = ETName.getText().toString();
if(!etName.trim().equals("")){
File file =new File("/sdcard/Accelerometer.html");
//if file doesnt exists, then create it
if(!file.exists()){
file.createNewFile();
}
FileWriter fileWritter = new FileWriter(file.getName(),true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.write(etName);
bufferWritter.close();
}
}catch (IOException e) {
e.printStackTrace(); }
}
try{
File dir = new File("/mnt/sdcard/MyApp/");
if (!dir.exists()) {
dir.mkdir();
System.out.println("Directory created");
}
//ceate .rtf file with header
myFile = new File("/mnt/sdcard/MyApp/Student.rtf");
if (!myFile.exists()) {
myFile.createNewFile();
System.out.println("File created");
}
fOut = new FileOutputStream(myFile.getAbsoluteFile(),true);
myOutWriter = new OutputStreamWriter(fOut);
//Write the header : in your case it is : Student class Marsk (only one time)
myOutWriter.write("Student,class,Marks"+"\n");
myOutWriter.flush();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}