Only the first item is displayed from the ArrayList - java

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, ",");

Related

Read/Write and compare android external storage

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.

Writing file into the data dir of another app (root)

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.

Save EditText to file with Button - Android, Java

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();
}

Android Show Internal Data in to textviews

I am working on an app where I need to save/read my files from Internal storage.
But it read all my data in the same TextView.
Can someone show me show,how to show the data in 2 textviews, or to show me how put the one data under the other data.
Here is my code for saving data:
private void SaveMode() {
String FILENAME ;
String Strin1= textview1.getText().toString();
String String2= textview2.getText().toString();
EditText filename1 = (EditText) findViewById(R.id.filename);
FILENAME = filename1.getText().toString();
if (FILENAME.contentEquals("")){
FILENAME = "UNTITLED";
}
String1 = textview1.getText().toString();
String2= textview2.getText().toString();
FileOutputStream fos = null;
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
fos.write("Strin1.getBytes());
fos.write(String2.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
And here is my code for read my data:
private void getFilenames() {
String[] filenames = getApplicationContext().fileList();
List<String> list = new ArrayList<String>();
for(int i = 0; i<filenames.length; i++){
//Log.d("Filename", filenames[i]);
list.add(filenames[i]);
}
ArrayAdapter<String> filenameAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, list);
spinner.setAdapter(filenameAdapter);
}
public void SpinnerClick(View v) {
String selectFile = String.valueOf(spinner.getSelectedItem());
openFile(selectFile);
}
private void openFile(String selectFile) {
showData = (TextView) findViewById(R.id.show_data);
TextView showData1 = (TextView) findViewById(R.id.show_data1);
String value = "";
FileInputStream fis;
try {
fis = openFileInput(selectFile);
byte[] input = new byte[fis.available()];
while(fis.read(input) != -1){
value += new String(input);
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
showData.setText(value);
}
EDIT
I tried to edit my read code like this, but with no luck
private void openFile(String selectFile) {
TextView showData = (TextView) findViewById(R.id.show_data);
TextView showData2 = (TextView) findViewById(R.id.show_data2);
String value = "";
String[] strArray = value.split(";");
try {
FileInputStream fis = openFileInput(selectFile);
byte[] input = new byte[fis.available()];
while(fis.read(input) != -1){
value += new String(input);
}
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
showData.setText(value);
showData.setText(strArray[0]);
showData2.setText(strArray[1]);
}
Edit 2
Got it to work with Shobhit Puri codes
First while saving your data you might insert a delimiter in between those two string. Make sure that delimiter is not the one expected in your textViews.
While saving:
String string3 = ";";
try {
fos.write("Strin1.getBytes());
fos.write("String3.getBytes());
fos.write(String2.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
Then when you are trying to read it into value string, then split is using .split function. Eg:
String[] strArray = value.split(";");
strArray[0] will give first textview's sting and strArray[1] will give the second.
Update
private void openFile(String selectFile) {
TextView showData = (TextView) findViewById(R.id.show_data);
TextView showData2 = (TextView) findViewById(R.id.show_data2);
String value = "";
try {
FileInputStream fis = openFileInput(selectFile);
byte[] input = new byte[fis.available()];
while(fis.read(input) != -1){
value += new String(input);
}
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String[] strArray = value.split(";");
showData.setText(strArray[0]);
showData2.setText(strArray[1]);
}
try
{
FileInputStream fis = new FileInputStream(myInternalFile);
DataInputStream in = new DataInputStream(fis);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
myData = myData + strLine;
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
myInputText.setText(myData);

Reading/Writing database error

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.

Categories