I have an app that can take a text file from the devices internal storage and reads the contents of the file to which it places it into an arraylist for me to compare against some other data.
Some example data in the text file is:
1.10
1.11
1.12
My app displays the last element of the array list, so in this example it would be '1.12' that is displayed.
The issue I am having is that if I change '1.12' to '1.13', it only updates to the new value when I run the app for the second time.
I can't figure out why this is. I have tested to make sure the file does update using adb and thats all updated but it appears as if the app is still reading the contents of the old version of the file rather than the new overwritten file on the first run. My code is below for reading the files contents.
public void readVersionList(){
download = (TextView) findViewById(R.id.download_version_path);
try {
Scanner scan = new Scanner(new File("/sdcard/version-nums.txt"));
ArrayList<String> list = new ArrayList<String>();
while (scan.hasNext()){
list.add(s.next());
}
scan.close();
updateVersionNum = list.get(list.size()-1);
download.setText(updateVersionNum);
Log.i("VERSIONNUM", updateVersionNum);
}catch (FileNotFoundException e){
e.printStackTrace();
}
catch (IOException e){
e.printStackTrace();
}
}
Related
I have an android application that collects data from a sensor via Bluetooth.
When trying to save the data to a .csv-file on the device, the data.csv-file gets created but no text is saved in the file.
The function in question:
private void writeData(boolean writeError) {
try {
File traceFile = new File(Environment.getExternalStorageDirectory(), writeError ? "error.csv" : "data.csv");
if (!traceFile.exists())
traceFile.createNewFile();
BufferedWriter writer = new BufferedWriter(new FileWriter(traceFile, true /*append*/));
writer.write("Test string");
} catch (Exception e) {
e.printStackTrace();
}
}
No error is thrown and I've made sure that each part of the code gets executed. Any ideas as to why this doesn't work?
Solution by Hurundi V. Bakshi
Added
writer.flush();
after
writer.write("Test string");
Documentation on flush():
Flushes this writer. Implementations of this method should ensure that all buffered characters are written to the target.
I am currently writing an android app that logs the accelerometer. (its a test app at the moment so i can prototype an algorithm.
To write out a list of SensorEventStore's (which is just a way of storing the data from a SensorEvent) to the SD card from a 30 minute recording, locks up the GUI for about 20 - 30 seconds while writing the file.
I am using the following code to write out the file to the SD card.
#Override
public void onMessage(Messages message, Object param[]) {
if(message == IDigest.Messages.SaveData) {
File folder = (File) param[0];
File accFileAll = new File(folder, startTime + "_all.acc");
FileWriter accFileWriterAll;
try {
accFileWriterAll = new FileWriter(accFileAll);
} catch (IOException e) {
accFileWriterAll = null;
}
for(Iterator<SensorEventStore> i=eventList.iterator(); i.hasNext();) {
SensorEventStore e = i.next();
if(accFileWriterAll != null) {
try {
accFileWriterAll.write(
String.format(
"%d,%d,%f,%f,%f\r\n",
e.timestamp,
e.accuracy,
e.values[0],
e.values[1],
e.values[2]
)
);
accFileWriterAll.flush();
} catch (IOException ex) {
}
}
}
new SingleMediaScanner(RunBuddyApplication.Context, accFileAll);
}
}
Can anyone give me any pointers to make this not lock up the UI, or not have to take the amount of time it currently takes to write out the file.
Firstly you should try to do this in the background. The AsyncTask is fairly well suited for the task.
Other than that, you should remove the flush() statement, and probperly close() your file writer. The flush causes the data to be written to disk in rather small portions, which is really slow. If you leave the filewriter to its own flushing, it will determine a buffer size on its own. When you properly close the FileWriter, the remaining data should be written to disk as well.
Also, you could take a look at "Try with resources" for your filewriter, but that is optional.
i did an application to collects light sensor data, such that these data are stored in text file in the external sdcard, the data is stored correctly and file are created successfully but the problem is when then application running on the my device for x period (e.g 1 min)the data is stored but when is close the application and re running it on from the device for the same period also the new collected data are append stored to the previous stored data from previous running and i noted that when the sizes of the text files is increases with each running.
i need for each running ,the collected data is stored totally (for the whole period of the running i.e 1 min ) in the text file and when i re- running the application again the new collected data of the new running to be overwriting on previous stored data.
i attempted to do that using arraylist, i .e when then app starts running i put all gathered reading in array list and when the running is stopped the arraylist will out all gathered data to the text file but when i re-running app the array list also gathered data and append out it into the text file next to the previous running stored data, where this is the problem which need to solve,i need to overwrite new running gathered data on the previous running stored data.
the code of collecting light sensor data looks like:
#Override
public void onSensorChanged(SensorEvent event) {
if(event.sensor.getType()==Sensor.TYPE_LIGHT){
max = msensorManager.getDefaultSensor(Sensor.TYPE_LIGHT).getMaximumRange();
//getMaximumRange() is the maximum range of the sensor in the sensor's unit.
//tv1.setText("Max Reading: " + String.valueOf(max));
tv1.setText(msg +"Max Reading: " + String.valueOf(max) );
tv1.invalidate();
lightMeter.setMax((int)max);
//setMax is the max of the upper range of this progress bar
currentReading = event.values[0];
//timestamp = event.timestamp;
lightMeter.setProgress((int)currentReading);
Toast.makeText(MainActivity.this,"Event Happend '", Toast.LENGTH_SHORT).show();
tv2.setText("Current Reading: " + String.valueOf(currentReading));
current_reading_list.add((double) currentReading);
}
the code of writing from array list into file looks like :
public void writing_in_file_1(){
try{
fw = new FileWriter(file_1, true);
bw = new BufferedWriter(fw);
out = new PrintWriter(bw);
//out.append( String.valueOf(currentReading + " \t"));
//out.append(String.valueOf(current_reading_list));
out.print(String.valueOf(current_reading_list));
out.flush();
Toast.makeText(this,"Done writing SD 'specific text file'", Toast.LENGTH_SHORT).show();
}
catch (IOException e)
{
e.printStackTrace();
}
finally{
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
the writing is done when the stop button is pressed:
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bt1:
counter_function();
//onResume();
break;
case R.id.bt2:
onPause();
writing_in_file_1();
tv1.setText("");
tv2.setText("");
break;
default:
break;
}
}
can any one help me?
thank you in advance.
You are using the constructor FileWriter(File file, boolean append) with append = true
Replace
fw = new FileWriter(file_1, true);
with
fw = new FileWriter(file_1, false);
I try to write string to file in my class, extends AsyncTask:
protected void onPostExecute(String result) {
super.onPostExecute(result);
DataOutputStream out = null;
try {
out = new DataOutputStream(openFileOutput("1xdf.xml", Context.MODE_PRIVATE));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
for (int i=0; i<20; i++) {
try {
out.writeUTF(Integer.toString(i));
} catch (IOException e) {
e.printStackTrace();
}
}
try {
out.close();
Log.e(DEBUG_TAG, "6x");
} catch (IOException e) {
e.printStackTrace();
}
}
Where can I finde this file in DDMs? When I try search->file 1xdf.xml, I get
Problems encountered during text search. File
'MainActivity/bin/jarlist.cache' has been skipped, problem while
reading: ('Resource is out of sync with the file system:
'/MainActivity/bin/jarlist.cache'.'). Resource is out of sync with the
file system: '/MainActivity/bin/jarlist.cache'.
When you use context.openFileOutput(), the files are written into the app's data. To check what this path is, you can call getFilesDir().
In the DDMS perspective in Eclipse, select the 'File Explorer' tab and then open the following path:
data/data/com.your.package.name.here/files/1xdf.xml
Where 'com.your.package.name.here' is the name of your project's package / application name. If you want to move the file to your file system, select the 'Pull a file from the device' button on the top right (looks like a floppy disk with a pink arrow pointing to the left) and select the directory on your computer where you want to save the file.
If you want to manually load a file onto your virtual device, use the button to the right of the one above (that looks like a right facing arrow pointing to a phone).
I am having a hard time figuring out how to write to and read from files on an Android device. The file will be formatted as XML and I already have parsers and data structures built that can format the XML into objects and objects into XML, but the last hurdle is reading the XML from a non-resource file (I know the data structures work because I it works when reading from a resource file) and also writing to a non-resource file. I am terrible at using tools to debug (not sure how to print a stack trace) but I know for a fact the problem is that I cannot read from or write to this files. I have no experience writing to files in Java which may be why I am having a rough time with this.
Write code:
File scoresFile = new File(getExternalFilesDir(null), "scores.xml");
if (!scoresFile.exists())
{
scoresFile.createNewFile();
}
OutputStream os = new FileOutputStream(scoresFile);
os.write(writer.toString().getBytes());
os.flush();
os.close();
Read Code:
XmlPullParserFactory xmlFac = XmlPullParserFactory.newInstance();
XmlPullParser qXML = xmlFac.newPullParser();
InputStream is = null;
File scoresFile = new File(c.getExternalFilesDir(null), "scores.xml");
if (!scoresFile.exists())
{
try {
scoresFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
is = new FileInputStream(scoresFile);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (is != null)
qXML.setInput(is,null);
else
qXML = c.getResources().getXml(R.xml.scores);
UPDATE: The last if clause in the read section always evaluates to false. So, the InputStream is null... that appears to be the root of my problem.
I would take a look at these two links: Using Internal Storage and Using External Storage
Both link to the same page, just different portions. Really, it depends on whether or not you want to save this file to the devices memory, or to an external medium (such as an SDcard).
Internal - Sandboxed, so that only your app can access it.
External - Anyone can access it.