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();
}
Related
public class PaymentActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_payment);
String FILENAME = "paid";
String data = "yes";
File folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
try {
File myFile = new File(folder, FILENAME);
FileOutputStream fstream = new FileOutputStream(myFile);
fstream.write(data.getBytes());
fstream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
File myFile = new File(folder, FILENAME);
FileInputStream fstream = new FileInputStream(myFile);
StringBuilder sbuffer = new StringBuilder();
int i;
while ((i = fstream.read())!= -1){
sbuffer.append((char)i);
}
String haspaid = sbuffer.toString();
System.out.println("Help!"+haspaid.equals("yes"));
if (haspaid.equals("yes")) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
fstream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I have a file write that inputs "yes" and a file read the reads that "yes" on external storage. I have System.out.println printed it out, and the file read/write seems to work. And yet somehow, when I compare the string resulted, it cannot be checked if it is a value.
What am I doing wrong?
use equals to check the equality of string instead of "!=" or "==".
equals checks the value, and "!=" or "==" checks the reference.
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 have made an EditText and a Button. The click of the button should save the text from the EditTextinto the ArrayList. The ArrayList is then persisted to a file. Further clicks append the text from the EditText to the ArrayList and then the file. However, after saving the file, I can only retrieve the first item entered from the file. I want to retrieve the whole list in a comma-separated format.
Button Click code:
String filename =“abc.text”;
List arrlist = new ArrayList();
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String listtext = a1.getText().toString();
// a1 is edittext
if (listtext.equals("")) {
Toast.makeText(getApplicationContext(), "Enter product", Toast.LENGTH_SHORT).show();
} else {
arrlist.add(listtext);
a1.setText("");
try {
FileOutputStream fos = openFileOutput(filename, Context.MODE_APPEND);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(arrlist);
oos.close();
fos.close();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
}
});
Retrieval of ArrayList from file:
List newarrList = new ArrayList();
FileInputStream fis = openFileInput(filename);
ObjectInputStream restore = new ObjectInputStream(fis);
newarrList= (ArrayList)restore.readObject();
restore.close();
String joined = TextUtils.join(", ", newarrList);
Toast.makeText(getApplicationContext(),joined,Toast.LENGTH_LONG).show();
// only the first item is displayed, not sure why
You keep adding ArrayList objects to the file using the ObjectInputStream. But you only read a single one out. I think you want to keep around a single ArrayList that you add the data to and then save that single ArrayList to the file whenever a click occurs instead of appending multiple ArrayLists for each entry.
List arrist = new ArrayList();
arrlist.add(listtext);
a1.setText("");
try {
FileOutputStream fos = openFileOutput(filename, Context.MODE_APPEND);
ObjectOutputStream oos = new ObjectOutputStream(fos);
appending an ArrayList object with only one entry each time an onclick occurs
oos.writeObject(arrlist);
oos.close();
fos.close();
}...
If you want to keep your original code and the state is only held for a single Activity and no persistence between Activity changes/App restarts etc.. then this should work.
final String filename = "abc.text";
File file = new File(filename);
// moved out of onClickListener
final List arrlist = new ArrayList();
try {
// load the previous contents if it exists
FileInputStream fis = openFileInput(filename);
ObjectInputStream restore = new ObjectInputStream(fis);
ArrayList newArrList = (ArrayList) restore.readObject();
arrlist.addAll(newArrList);
restore.close();
fis.close();
} catch (FileNotFoundException e) {
// ignore, maybe log
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (OptionalDataException e) {
e.printStackTrace();
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (IOException e)
e.printStackTrace()
}
b2.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v
) {
String listtext = a1.getText().toString(); //a1 is edittext
if (listtext.equals("")) {
Toast.makeText(getApplicationContext(), "Enter product", Toast.LENGTH_SHORT).show();
} else {
arrlist.add(listtext);
a1.setText("");
try {
Change Context.MODE_APPEND to Context.MODE_PRIVATE otherwise we keep inflating the file with junk
FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(arrlist);
oos.close();
fos.close();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
);
The other alternative is to not use the ObjectInputStream but just a straight FileOutputStream and append the String contents on each click.
You store(write) string into file, end the string with comma, and After reading__(read) split the result with "," which returns a String array. Make sure you are appending the string into file. ArrayList variable as global variable.
//global variable
List arrlist = new ArrayList();
......
//write to file
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String listtext = a1.getText().toString();
.....
arrlist.add(listtext);
.....
listtext = listtext + ",";
FileOutputStream fOut = openFileOutput("file name here", Context.MODE_APPEND);
fOut.write(listtext .getBytes());
fOut.close();
....
}
//reading from file
String fileContent = readFile();
String[] items = TextUtils.split(fileContent, ",");
I'm trying to write a file (FlappyBird2.xml in this example) into the data directory of another app (/data/data/com.dotgears.flappybird/shared_prefs.xml in this example). But the code does literally nothing. I request superuser rights in another activity in the onCreate event. Here's my code:
Button btncheat = (Button) findViewById(R.id.button1);
btncheat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String path = "/data/data/com.dotgears.flappybird/shared_prefs/";
File file = new File(path);
file.mkdirs();
path += "FlappyBird2.xml";
OutputStream myOutput;
try {
myOutput = new BufferedOutputStream(new FileOutputStream(path,true));
myOutput.write(new String("test").getBytes());
myOutput.flush();
myOutput.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
/edit: I'm trying it like this now:
Button btncheat = (Button) findViewById(R.id.button1);
btncheat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String path = "/data/data/com.dotgears.flappybird/shared_prefs/";
String filename = "FlappyBird2.xml";
String string = "test";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
final Runtime runtime = Runtime.getRuntime();
try {
runtime.exec("su");
runtime.exec("mv " + Environment.getDataDirectory().toString() + filename + " " + path + filename);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
But this doesn't do anything either. It creates the file in /data/data/my.app/files successfully, but the mv command does not do anything. I see that it requested SU successfully before trying to move the file, so this can't be the problem. Logcat says nothing in red, I debugged it.
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.