I am trying to set text in EditText by reading a file but app get closed every time. Can someone tell what's wrong with this code?
package com.example;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.content.Intent;
import android.view.View;
import android.widget.*;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class EditNoteActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
String FILENAME = "note_file";
EditText text = (EditText) findViewById(R.id.editText1);
byte[] buffer = new byte[100];
super.onCreate(savedInstanceState);
setContentView(R.layout.editnote);
//Intent intent = getIntent();
FileInputStream fos = null;
try {
fos = openFileInput(FILENAME);
} catch (FileNotFoundException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
assert fos != null;
try {
fos.read(buffer, 0, 10);
String str = buffer.toString();
text.setTextSize(48);
text.setText(str);
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
public void onClickSave(View theButton) {
//Intent intent = new Intent(this, MyActivity.class);
//startActivity(intent);
String FILENAME = "note_file";
EditText text = (EditText) findViewById(R.id.editText1);
FileOutputStream fos = null;
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
assert fos != null;
try {
fos.write(text.getText().toString().getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
finish();
}
public void onClickBack(View theButton) {
//Intent intent = new Intent(this, MyActivity.class);
//startActivity(intent);
finish();
}
}
I tried to edit this to remove irrelevant code but I got error, "Your post does not have much context to explain the code sections; please explain your scenario more clearly.". Unfortunately there is not much and anyway this question has been answered.
You are initializing EditText (text) before setting content view, so that the EditText object is null while finding edit text by id, that's why application crashed.
Modify your code as follows
super.onCreate(savedInstanceState);
setContentView(R.layout.editnote);
String FILENAME = "note_file";
EditText text = (EditText) findViewById(R.id.editText1);
byte[] buffer = new byte[100];
FYI: while asking questions, post error log too then only you can get quick and proper answers.
Update
Refer :
to get error log from eclipse
for converting byte array into string
byte[] bytes = {...}
String str = new String(bytes, "UTF8"); // for UTF8 encoding
this is the issue.
Related
Here's a code of MainActivity.java to save a file named filename.txt in App's Internal Storage, which is working fine.
package com.bla.smthing;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class MainActivity extends Activity {
EditText textmsg;
static final int READ_BLOCK_SIZE = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textmsg=(EditText)findViewById(R.id.editText1);
}
// write text to file
public void WriteBtn(View v) {
// add-write text into file
try {
FileOutputStream fileout=openFileOutput("mytextfile.txt", MODE_PRIVATE);
OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
outputWriter.write(textmsg.getText().toString());
outputWriter.close();
//display file saved message
Toast.makeText(getBaseContext(), "File saved successfully!",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
// Read text from file
public void ReadBtn(View v) {
//reading text from file
try {
FileInputStream fileIn=openFileInput("mytextfile.txt");
InputStreamReader InputRead= new InputStreamReader(fileIn);
char[] inputBuffer= new char[READ_BLOCK_SIZE];
String s="";
int charRead;
while ((charRead=InputRead.read(inputBuffer))>0) {
// char to string conversion
String readstring=String.copyValueOf(inputBuffer,0,charRead);
s +=readstring;
}
InputRead.close();
textmsg.setText(s);
} catch (Exception e) {
e.printStackTrace();
}
}
}
I am able to see the file by File Explorer of Android Studio. How can I save the file in a directory say files/Somefolder/otherfolderchild/filename.txt?
Currently, it is saving as files/filename.txt
Do I need to create additional parent file directories for that?
Try this it might help you. For the above marshmallow version please check the write permissions.
public void saveToExternalStorage() {
String fullPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/directoryName";
try
{
File dir = new File(fullPath);
if (!dir.exists()) {
dir.mkdirs();
}
OutputStream fOut = null;
File file = new File(fullPath, "fileName.txt");
if(file.exists())
file.delete();
file.createNewFile();
fOut = new FileOutputStream(file);
fOut.flush();
fOut.close();
}
catch (Exception e)
{
Log.e("saveToExternalStorage()", e.getMessage());
}
}
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.
Because your
FileOutputStream fOut = getActivity().openFileOutput("sample_details.txt", Context.MODE_MULTI_PROCESS);
should be
openFileOutput(yourFile, Context.MODE_APPEND);
FileOutputStream also have a constructor where you can append to the original file if you don't have context to be used with Android's openFileOutput() instead.
Extra reference for similar questions: OutputStreamWriter does not append
I am trying to write to a text file a list of names. It is written one line at a time and I have a class for Writing to File and Reading from it.
Here is the class:
package com.example.mobiledayoff;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import android.content.Context;
public class userListIO {
Context fileContext;
public userListIO(Context fileContext){
this.fileContext=fileContext;
}
public void writeItems(String fileName, String name){
final String ls = System.getProperty("line.separator");
BufferedWriter writer = null;
try{
writer =
new BufferedWriter(new OutputStreamWriter(fileContext.getApplicationContext().openFileOutput(fileName, Context.MODE_PRIVATE)));
writer.write(name + ls);
} catch (Exception e){
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public ArrayList<CharSequence> readItems(String filename){
ArrayList<CharSequence> list = new ArrayList<CharSequence> ();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(fileContext.getApplicationContext().openFileInput(filename)));
String line;
while((line = br.readLine()) != null){
list.add(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return list;
}
}
I use this class to write a line from user input (EditText) to the file. And then I read from file and Display contents of the file in another EditText. Here is how I do it:
public void addUser(View view){
EditText text = new EditText(this);
text = (EditText)findViewById(R.id.add_user_text);
String name = text.getText().toString();
String filename = "userList.txt";
userListIO messenger = new userListIO(this);
messenger.writeItems(filename, name);
text.setText("");
ArrayList<CharSequence> list = messenger.readItems(filename);
EditText editText = (EditText) findViewById(R.id.debug_text);
String info = "";
int count = 0;
for (CharSequence item: list){
info += item.toString();
count++;
}
info += "; there are " + count + " lines";
editText.setText(info);
}
My main problem is that it seems that file gets overwritten each time I write into it and so I always have 1 line. Do you guys know how to fix this? By fix I mean: How to append to the file if it already exists or create one if it doesn't exist.
Also I found out that after I close and reopen an app, the file does not exist. How to create and save a file, so that after closing and reopening I could still use the data stored there?
p.s. Read/Write was taken from here:
The best way to store user input data for later work
Change
new BufferedWriter(new OutputStreamWriter(fileContext.getApplicationContext().openFileOutput(fileName, Context.MODE_PRIVATE)));
to
new BufferedWriter(new OutputStreamWriter(fileContext.getApplicationContext().openFileOutput(fileName, Context.MODE_PRIVATE | Context.MODE_APPEND)));
This will combine the MODE_PRIVATE flag aswell as the MODE_APPEND flag.
P.S. You should get away from opening and closing a stream everytime you write a line. This produces a lot of overhead and rather should you try to keep the stream opened until all your data has been processed.
I'm working on a FTP-project to send a picture taken by camera to a FTP-Server.
Now it's possible, that my picuture will be saved in folder: /sdcard/ftp/
How I have to change the code from my FTPActivity, that the files in the folder will be send?
Hope somebody can give me an example. Or post the changed code. That would be very helpful for me.
Here my FTP-Client-Code:
package de.android.datenuebertragung;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import org.apache.commons.net.ftp.FTPClient;
import android.app.Activity;
import android.util.Log;
public class FTPManager extends Activity{
FTPClient con = new FTPClient();{
try
{
con.connect("host");
if (con.login("user", "password"))
{
con.enterLocalPassiveMode(); // important!
String data = "Test 09.06.2012";
ByteArrayInputStream in = new ByteArrayInputStream(data.getBytes());
boolean result = con.storeFile("/FTPTest.txt", in);
in.close();
if (result) Log.v("upload result", "succeeded");
System.out.println("Test ok ...");
}
}
catch (Exception e)
{
e.printStackTrace();
}
try
{
con.logout();
con.disconnect();
}
catch (IOException e)
{
e.printStackTrace();
}
}}
This is pseudo code. I have not tested for syntax or any errors for that matter.
// in application never use hardcoded paths
File folder = new File("/sdcard/ftp/");
File tempFile = null;
FTPFile[] tempFTPFile = null;
//get all files in folder
for(String fileInDir : folder.list()){
tempFile = new File(fileInDir);
tempFTPFile = ftpConnection.listNames(tempFile.getName);
if(tempFTPFile!=null || tempFTPFile.length<=0){
ftpConnection.upload(fileInDir);
}
}
here is my entire code (ps Im a noobie);
package xom.aaa.aaa;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class FilewritertestActivity extends Activity {
TextView textout1, textout2, textout3;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b1 = (Button) findViewById(R.id.button1);
textout1 = (TextView) findViewById(R.id.textView1);
textout2 = (TextView) findViewById(R.id.textView2);
textout3 = (TextView) findViewById(R.id.textView3);
b1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//--------- OutputStreamWriter ------------
try {
FileOutputStreamfOut=openFileOutput("settings1.dat", MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write( "using fileoutput stream to write this to a file");
osw.flush();
osw.close();
}catch(Exception e){
e.printStackTrace(System.err);
}
String datax = "";
StringBuffer buffer = new StringBuffer();
//--------- InputStreamReader -------------------
try {
FileInputStream fIn = openFileInput("settings1.dat");
Reader reader = new InputStreamReader(fIn);
int data = reader.read(); // reads the next char
while(data != -1){
buffer.append((char)data);
data = reader.read();
}
reader.close();
} catch ( Exception e) {
e.printStackTrace();
}
textout1.setText( buffer.toString());
//--------------- FileWriter ---------------
try {
FileWriter fw = new FileWriter("settings1.dat");
BufferedWriter out = new BufferedWriter(fw);
//BufferedWriter out = new BufferedWriter(new FileWriter("settings1.dat"));
out.write("a String");
out.close();
} catch (Exception e){
e.printStackTrace();
textout2.setText(e.toString());
}
}
});
}
}
Problem is FileWriter Not working ( for file "settings1.dat")
but OutputStreamWriter and InputStreamReader does work ( for file "settings1.dat")
the code shows writing then reading to file "settings1.dat" Is ok with Stream Witer/Reader...
But FileWriter code get error message Filenotfoundexception "read-only file system"
So why does one technique work on the same File and the other doesn´t
Can you please tell what Iam missing -- thanks Trevor
I'm guessing your problem is you just aren't getting an IOException. You could try changing
catch(IOException e)
to
catch(Exception e)
This will then catch all exceptions which extend the Exception object (it will not catch Errors though). However, I don't have the tools to test out your code so you will have to try it out yourself and post the results.
Best of luck.