I have created a file with an asynctask. Afterwards scheduled an executor to write information to said file once every second. Once I touch a button the executor is shut down and the file closed but more often than not nothing is written in the file.
Code:
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
preferences.edit().putBoolean(GlobalConstants.stopPreference,false).commit();
loc_thr = new LocationThread(preferences, getApplicationContext());
loc_thr.run();
startButton.setVisibility(View.INVISIBLE);
startButton.setClickable(false);
stopButton.setVisibility(View.VISIBLE);
stopButton.setClickable(true);
currentDateAndTime = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
fileName = getString(R.string.loc_log_path) + currentDateAndTime + ".txt";
new CreateFileTask(fileName).execute();
loc_file = new File(fileName);
try {
FOS = new FileOutputStream(loc_file.getAbsolutePath());
OSW = new OutputStreamWriter(FOS);
OSW.write(GlobalConstants.fileHeader + '\n');
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
scheduledTaskExecutor = Executors.newScheduledThreadPool(5);
scheduledTaskExecutor.scheduleAtFixedRate(new Runnable() {
public void run() {
if(loc_thr.getLocationStatus() & loc_thr.newLocation() & !preferences.getBoolean(GlobalConstants.stopPreference,false)){
SensorBundle SB = new SensorBundle(loc_thr.getCurrentLocation(),loc_thr.getCurrentGPSStatus());
try {
OSW.write(new SimpleDateFormat("yyyy/MM/dd;hh:mm:ss").format(new Date()) + ";");
OSW.write(SB.getLatitude() + ";");
OSW.write(SB.getLongitude() + ";");
OSW.write(SB.getAltitude() + ";");
OSW.write(SB.getAccuracy() + ";");
OSW.write(SB.getProvider() + ";");
OSW.write('\n');
} catch (IOException e) {
e.printStackTrace();
}
} else{
if(preferences.getBoolean(GlobalConstants.stopPreference,false)){
try {
OSW.close();
FOS.close();
scheduledTaskExecutor.shutdown();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}, 0, 1, TimeUnit.SECONDS);
}
});
Whenever the stop button is pressed the SharedPreference queried earlier is set to true.
I think your problem may be here
new CreateFileTask(fileName).execute();
loc_file = new File(fileName);
I assume this task creates the file and you're expecting that when you can new File(fileName) the file is already created. Whether this is true or not is indeterminate. If the AsyncTask CreateFileTask is scheduled to run and completes before the next statement is executed then the file will be there, otherwise it won't be. Are you seeing stack traces in logcat from the IOException or FileNoteFoundExceptions?
Related
I am currently making a journal app, so the users type their entry into an EditText and it saves in their phone and they can load it up later. At first I used just getFilesDir() but recently there is this weird rList file that shows up every time I open the app and I couldn't figure it out(I wrote a question about it). So now I want to save these files in this specific directory called TextEntries
Here is the code for my save funcction:
public void save(View v) {
textFile = inputTitle.getText().toString();
String text = inputFeelings.getText().toString();
FileOutputStream fos = null;
try {
String rootPath = getFilesDir().getAbsolutePath() + "/TextEntries/";
File root = new File(rootPath);
if (!root.exists()) {
root.mkdirs();
}
fos = openFileOutput(textFile, MODE_PRIVATE);
fos.write(text.getBytes());
inputFeelings.getText().clear();
Toast.makeText(this, "Saved to " + getFilesDir() + "/TextEntries/" + textFile,
Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
All help is welcome and thank you in advance.
replace
openFileOutput(textFile, MODE_PRIVATE);
with
new FileOutputStream(rootPath + textFile)
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();
}
}
});
What I am trying to do is store a JSON file as a string in internal storage to access it later. The reasoning behind this is to not have to access the server on every request, as this data is constant. Once it is stored once, it doesn't have to be retrieved again unless there is some sort of update. File storage isn't something I've done before, and I was hoping someone could give me a hand. My current code is throwing a null pointer exception at this line:
File file = new File(getFilesDir(), fileName);
My code:
protected String doInBackground(String[] runeId) {
String url = "https://prod.api.pvp.net/api/lol/static-data/" + region + "/v1.2/rune/" + runeId[0] + "?api_key=" + api_key;
JSONParser jsonParser = new JSONParser();
JSONObject runeInfo = jsonParser.getJSONFromUrl(url);
String jsonString = runeInfo.toString();
String fileName = "runeInfo";
File file = new File(getFilesDir(), fileName);
String readJson = null;
if(!runesCached) {
Log.d("Cache", "Caching File");
try {
FileOutputStream os = new FileOutputStream(file);
os.write(jsonString.getBytes());
os.close();
Log.d("Cache", "Cache Complete");
runesCached = true;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String name = null;
try {
FileInputStream fis;
File storedRuneInfo = new File(getFilesDir(), fileName);
fis = new FileInputStream(storedRuneInfo);
fis.read(readJson.getBytes());
JSONObject storedJson = new JSONObject(readJson);
try {
name = storedJson.getString("name");
} catch (JSONException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return name;
}
}
Try this, instead:
File file = new File(getFilesDir().toString(), fileName);
getFilesDir() returns a File, not a String, which the File class constructor takes as a parameter.
getFilesDir()toString() should return something like /data/data/com.your.app/
EDIT:
This gives the same error. How about:
try {
FileWriter fstream;
BufferedWriter out;
fstream = new FileWriter(getFilesDir() + "/" + "filename");
out = new BufferedWriter(fstream);
out.write(jsonString.getBytes());
out.close();
} catch (Exception e){}
I'm trying to write log statements to the sdcard. The way i have decided to do it is create a file on the sdcard through the Application Object. This way i can call a static method logToSdcard() from anywhere in the app.
The containing folder "/RR3log/" is created but every statement that i log is in its own file called "rr3LogFile.txt". So i have multiple rr3LogFile files containing one staement in each.
How can i write all statement to one rr3LogFile file? Thanks in advance Matt.
public class NfcScannerApplication extends Application{
#Override
public void onCreate() {
super.onCreate();
File storageDir = new File(Environment
.getExternalStorageDirectory(), "/RR3log/");
storageDir.mkdir();
try {
if(outfile == null){
outfile=File.createTempFile("rr3LogFile", ".txt",storageDir);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void logToSdcard(String tag, String statement){
Log.e(TAG, "inside logtosdcard$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
String state = android.os.Environment.getExternalStorageState();
if(!state.equals(android.os.Environment.MEDIA_MOUNTED)) {
try {
throw new IOException("SD Card is not mounted. It is " + state + ".");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
DateTime now = new DateTime();
DateTimeFormatter fmt = DateTimeFormat.forPattern("d-MMM-Y H:mm");
String dateStr = fmt.print(now);
try{
FileOutputStream fOut = new FileOutputStream(outfile);
OutputStreamWriter myOutWriter =new OutputStreamWriter(fOut);
myOutWriter.append(dateStr + " " + tag + " ");
myOutWriter.append(statement);
myOutWriter.append("\n");
myOutWriter.flush();
myOutWriter.close();
fOut.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
.
Then in an Activity anywhere in the app.
#Override
protected void onResume() {
super.onResume();
Log.e(TAG, "inside entryactivity onResume");
NfcScannerApplication.logToSdcard(TAG, "inside entryactivity onResume" );
In your logToSdcard Method create the FileOutputStream with an additional parameter:
FileOutputStream fOut = new FileOutputStream(outfile, true);
The true paramters says that contents will be appended to the file. See also FileOutputStream
Try that:
public static void printLog(Context context){
String filename = context.getExternalFilesDir(null).getPath() + File.separator + "my_app.log";
String command = "logcat -f "+ filename + " -v time -d *:V";
Log.d(TAG, "command: " + command);
try{
Runtime.getRuntime().exec(command);
}
catch(IOException e){
e.printStackTrace();
}
}
The logs will be saved continuously until the application is exited.
I have a problem creating a text file on SD card to be attached to an email to be sent with gmail application.
When attached to an email in the gmail app, the email stalls in the red "Sending..." state forever. The file is created using createCSVfile() below.
Debugging my code, launching my app different times, csv_file.exists() always returns false, as if the file is not found and to be created each time the app is run.
However, using a file manager I can see file is there between and during runs.
Any help please?
Thanks
File csv_file = null;
String createCSVfile() {
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
csv_file = new File( getExternalFilesDir(null) + File.separator + "InOutStats.txt");
if (csv_file != null ) {
if( csv_file.exists() ){
Log.v("CSV_FILE", "Stat file " + csv_file.toString() +" already there!");
}else{
csv_file.getParentFile().mkdirs();
try {
boolean bool = csv_file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
FileWriter fWriter = null;
try {
fWriter = new FileWriter(csv_file);
} catch (IOException e) {
e.printStackTrace();
}
BufferedWriter writer = new BufferedWriter(fWriter);
try {
writer.write("Some text here!!! " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis()));
writer.newLine();
} catch (IOException e) {
e.printStackTrace();
}
try {
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}else{
Log.v("CSV_FILE", "NO SD CARD HERE???");
}
return csv_file.toString();
}
The error is:
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis())
which should be
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())
I saw only two very minor "errors":
[Style issue]
csv_file = new File( getExternalFilesDir(null) + File.separator + "InOutStats.txt");
should be
csv_file = new File( getExternalFilesDir(null), "InOutStats.txt");
because otherwise you are using File.toString().
[Smallest code]
Removed should be:
csv_file.createNewFile();
Second attempt
Try replacing
if (csv_file != null ) {
if( csv_file.exists() ){
Log.v("CSV_FILE", "Stat file " + csv_file.toString() +" already there!");
}else{
csv_file.getParentFile().mkdirs();
try {
boolean bool = csv_file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
with
{
This removes the existence test, mkdirs and unneeded separate file creation.
Done to try restrict the error area.
Furthermore you are using the default platform encoding for the text; you could make it explicit:
new FileWriter(csv_file, "UTF-8")