OnClickListener [Eclipse] - android

I am wanting to pass the data added into these fields to a .txt file stored on the device.

Try to do something as I show below:
Button btn11 = (Button) this.findViewById(R.id.buttonformdata);
btn11.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try{
FileOutputStream fos = openFileOutput("yourFile", Context.MODE_PRIVATE);
String string1 = editText1.getText().toString();
String string2 = editText2.getText().toString();
String string3 = editText3.getText().toString();
fos.write(string1.getBytes());
fos.write(string2.getBytes());
fos.write(string3.getBytes());
fos.close();
}catch(Exception e){
Log.e("Exception", e.toString());
}
}
});
Let me know if it works!

In your xml file you can add android:onClick="bSomething" to the properties of the button you want to click. Then on your activity class (or where you have your code that you posted) you can do something like:
public void bSomething(View view){
try{
FileOutputStream fout = openFileOutput(“yourfile.txt”,MODE_PRIVATE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write(editText1.getText().toString()+" ");
osw.write(editText2.getText().toString()+" ");
osw.write(editText3.getText().toString()+" ");
osw.close();
fout.close();
}catch(Exception e){
//do the exception handling
}
}
Hope that helps.

Related

Android save to file.txt appending

I admittedly am still learning and would consider myself a novice (at best) regarding programming. I am having trouble with appending a file in android. Whenever I save, it will rewrite over the file, and I am having trouble understanding how to keep the file that is already there and only add a new line. Hoping for some clarity/advice. Here is how I am saving to the file (which rewrites the file each time I save).
public void saveText(View view){
try {
//open file for writing
OutputStreamWriter out = new OutputStreamWriter(openFileOutput("save.txt", MODE_PRIVATE));
//write information to file
EditText text = (EditText)findViewById(R.id.editText1);
String text2 = text.getText().toString();
out.write(text2);
out.write('\n');
//close file
out.close();
Toast.makeText(this,"Text Saved",Toast.LENGTH_LONG).show();
} catch (java.io.IOException e) {
//if caught
Toast.makeText(this, "Text Could not be added",Toast.LENGTH_LONG).show();
}
}
Change this,
OutputStreamWriter out = new OutputStreamWriter(openFileOutput("save.txt", MODE_PRIVATE));
to,
OutputStreamWriter out = new OutputStreamWriter(openFileOutput("save.txt", Context.MODE_APPEND));
This will append your new contents to the already existing file.
I Hope it helps!
Use this method, pass filename and the value to be added in the file
public void writeFile(String mValue) {
try {
String filename = Environment.getExternalStorageDirectory()
.getAbsolutePath() + mFileName;
FileWriter fw = new FileWriter("ENTER_YOUR_FILENAME", true);
fw.write(mValue + "\n\n");
fw.close();
} catch (IOException ioe) {
}
}
To display the content of the saved file with the line breaks with a button click use:
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
FileInputStream fin = openFileInput(fileTitle);
int c;
String temp = "";
while ((c = fin.read()) != -1) {
temp = temp + Character.toString((char) c);
}
tv.setText(temp);
Toast.makeText(getBaseContext(), "file read", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
}
}
});
To Delete content of existing file whist retaining the filename you can use:
deleteOrder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
FileOutputStream fOut = openFileOutput(fileTitle,MODE_PRIVATE);
// fOut.write(data.getBytes());
dataTitle = "";
fOut.write(data.getBytes());
fOut.close();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
This worked for me. Takes content of a TextEdit called textTitle. Writes it to file called dataTitle. Then writes a new line with fOut.write("\n"). The next text entered into TextEdit is added to the file with a line break.
try {
FileOutputStream fOut = openFileOutput(fileTitle,MODE_APPEND);
fOut.write(dataTitle.getBytes());
fOut.write('\n');
fOut.close();
Toast.makeText(getBaseContext(),"file saved",Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});

Overwriting data using files

i created a file and when i run the program, the data is been written in to the file but when i run the program again the new data over write on old data.
i need once the program is running and gathers data, these data are writable into the file in cascade next each other without overwriting on previous data in file.
this code running successful but when i run the program again the over writing happens which i don need that, i need to save previous data in side the file and write the new data next it and soon.
after edit this code its looks like:
public class MainActivity extends Activity {
File file;
File sdCard;
FileOutputStream fos;
OutputStreamWriter myOutWriter;
String FileName = "Output3.txt";
String eol;
OutputStream fos1;
FileWriter fw ;
BufferedWriter writer;
BufferedWriter bw ;
PrintWriter out;
EditText txtData;
Button btnWriteSDFile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sdCard =getExternalFilesDir(null);
file = new File(sdCard,FileName);
txtData = (EditText) findViewById(R.id.editText1);
btnWriteSDFile = (Button) findViewById(R.id.button1);
btnWriteSDFile.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
try {
fos = new FileOutputStream(file);
myOutWriter =new OutputStreamWriter(fos);
eol = System.getProperty("line.separator");
writer = new BufferedWriter(myOutWriter);
writer.append(txtData.getText() + eol);// write this text.
writer.flush();
fos.close();
Toast.makeText(v.getContext(),"Done writing SD 'Output.txt'", Toast.LENGTH_SHORT).show();
txtData.setText("");
} catch (Exception e) {
// e.printStackTrace();
Toast.makeText(v.getContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
}
finally{
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
}
please,can any one answer me?
Instead of using OutputStreamWriter use Filewriter FileWriter fileWritter = new FileWriter(file,true); when u pass true it appends the contents.try this
FileWriter myOutWriter = new FileWriter(file.getName(),true);
eol = System.getProperty("line.separator");
writer = new BufferedWriter(myOutWriter);
writer.write(txtData.getText() + eol);// write this text.
writer.close();
fos.close();
Change this line:
fos = new FileOutputStream(file);
To:
fos = new FileOutputStream(file, true);
This opens the file so that data can be appended.
JavaDocs for FileOutputStream
use
FileWriter writer = new FileWriter("yourfilename", true);
second parameter should be passed as true which will append data instead of overwriting
try {
File myFile = new File(Environment.getExternalStorageDirectory() + File.separator + "test.txt");
// this changed bye fos = new FileOutputStream(myFile) to
fos = new FileOutputStream(myFile,true);
//FileWriter writer = new FileWriter("yourfilename", true);
myOutWriter = new OutputStreamWriter(fos);
eol = System.getProperty("line.separator");
writer = new BufferedWriter(myOutWriter);
writer.append("\n");
writer.append(txtData.getText() + eol);// write this text.
writer.flush();
fos.close();
Toast.makeText(v.getContext(),
"Done writing SD 'Output.txt'", Toast.LENGTH_SHORT)
.show();
txtData.setText("");
} catch (Exception e) {
// e.printStackTrace();
Toast.makeText(v.getContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
} finally {
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Enjoye i have tested it is work for me.

Save data to file not working properly

I use the following code to save password in a txt file:
String FILE_NAME="lol.txt";
public void writeData(String password){
FileOutputStream fOut = null;
OutputStreamWriter osw = null;
try{
fOut = openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
osw = new OutputStreamWriter(fOut);
osw.write(password);
osw.close();
fOut.close();
}catch(Exception e){
e.printStackTrace(System.err);
}
}
but When I retrive the password that I just Saved using toast its appears OK, but when I Log it into my LogCat I got Something like the following:
gana???????????????????????????????????? .... and more four lines.
I save the word gana into my file using save method which work as OnClikc method that set value of EditText as password as below:
public void save(View v){
password= txt.getText().toString();
writeData(password);
}
any Way or clue how can I solve this problem?
regards
Use below code to reading file
byte[] b = null;
try
{
//read file data...
FileInputStream myFile = openFileInput("lol.txt");
b = new byte[1024];
myFile.read(b);
Log.i("Pass", "File data is: " + new String(b).trim());
myFile.close();
}
catch (IOException e)
{
}
only difference with your code is that i am using new String(b).trim() to remove blank space.

IO Exception in FileInputStream.read. Android

I'm writting an Android's app. Two activities, one has TextEdit to type 'hello message', and button to save message in Internal Storage. Second is main activity. Hello mesage should appear after app's start.
Second activity:
String s = ((EditText) findViewById(R.id.message_act_editText_hello)).getText().toString();
FileOutputStream fos = openFileOutput(Lab2AndroidActivity.FILENAME, Context.MODE_PRIVATE);
fos.write(s.getBytes());
fos.close();
first (main) activity:
static String FILENAME = "message_file.zip";
FileOutputStream fos;
try {
//piece of code to guarantee that file exists
fos = openFileOutput(Lab2AndroidActivity.FILENAME, Context.MODE_APPEND);
fos.close();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
fis = openFileInput(FILENAME);
messageString = new StringBuffer("");
while ((length = fis.read(buffer)) != -1) {
String temp = new String(buffer, 0,length);
messageString.append(temp);
fis.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Toast t = Toast.makeText(this, messageString, 3000);
t.show();
I'm getting IO Exception in logcat at line:
while ((length = fis.read(buffer)) != -1)
but app seems to work correctly (defined message appears after app's start). I tried to find explanation, I found several topics, but all was according to large files, or files in assets, or compressed files.
I tried to name my file like
static String FILENAME = "message_file.zip",
static String FILENAME = "message_file.txt",
to try different extensions, but always i'm getting the same IO Exception.
Thanks for suggestions.
of course you will get an IO Exception your file doesn't exit and you request to open it
You forget this peice of code
File myFile = new File("/sdcard/mysdfile.txt");
In your first activity you can use this code
public class MainActivity extends Activity {
/** Called when the activity is first created. */
EditText txtData;
Button btnWriteSDFile;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// bind GUI elements with local controls
txtData = (EditText) findViewById(R.id.txtData);
txtData.setHint("Enter some lines of data here...");
btnWriteSDFile = (Button) findViewById(R.id.btnWriteSDFile);
btnWriteSDFile.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// write on SD card file data in the text box
try {
File myFile = new File("/sdcard/mysdfile.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append(txtData.getText());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Done writing SD 'mysdfile.txt'",
Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(),SecondActivity.class);
startActivity(i);
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}// onClick
});
}
}
in the second one you can use this:
public class SecondActivity extends Activity {
private TextView txtData2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
txtData2 = (TextView) findViewById(R.id.textView2);
try {
File myFile = new File("/sdcard/mysdfile.txt");
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
txtData2.setText(aBuffer);
myReader.close();
Toast.makeText(getBaseContext(),
"Done reading SD 'mysdfile.txt'",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
}
The first latout uses a linearlayout that contain an edittext and a button
The second a linearLayout with only a textview
Try it works fine if you find problem let me know!!
Ah i forget you have to add in your manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
I found reason. Problem was in fragment:
while ((length = fis.read(buffer)) != -1) {
String temp = new String(buffer, 0,length);
messageString.append(temp);
fis.close();
}
What's the catch?
fis.close();
should be after while. I didn't notice that yesterday...

"Resolved" Written file with blanks at the end

I'm creating a class to manage text files. I have a method to write and an other to read my file :
public static void writeFiles(Context context, String nomFichier, String content, char mode) {
FileOutputStream fOut = null;
OutputStreamWriter osw = null;
try {
if (mode == 'd') {
context.deleteFile(nomFichier);
} else {
fOut = context.openFileOutput(nomFichier, Context.MODE_APPEND);
osw = new OutputStreamWriter(fOut);
osw.write(content);
osw.flush();
}
} catch (Exception e) {
Toast.makeText(context, "Message not saved",Toast.LENGTH_SHORT).show();
} finally {
try {
osw.close();
fOut.close();
} catch (IOException e) {
Toast.makeText(context, "Message not saved",Toast.LENGTH_SHORT).show();
}
}
}
When I create a file, it is filled with few empty lines. I want to set the content of my file into an EditText, so I don't want the blanks.
How can I create a file without blanks?
Thx, korax.
EDIT :
I use trim(), suggested by appserv and acj, but in the read function instead of write function. It works fine, thx you!
public static String readFile(Context context, String fileName) {
FileInputStream fIn = null;
InputStreamReader isr = null;
char[] inputBuffer = new char[255];
String content = null;
try {
fIn = context.openFileInput(fileName);
isr = new InputStreamReader(fIn);
isr.read(inputBuffer);
content = new String(inputBuffer);
} catch (Exception e) {
//Toast.makeText(context, "Message not read",Toast.LENGTH_SHORT).show();
}
finally {
try {
isr.close();
fIn.close();
} catch (IOException e) {
//Toast.makeText(context, "Message not read",Toast.LENGTH_SHORT).show();
}
}
return content.trim();
}
If you are using a text editor to create the file, the editor may be adding some blank lines to pad the file size. You could call openFileOutput without the MODE_APPEND flag to create the new (empty) file programmatically, thus avoiding the text editor.
Otherwise, appserv's suggestion to use trim() should work nicely to clean up the string.

Categories

Resources