For my application I want to create a class where I can log data into a file. Within my app there’s the ability to email me if they’re experiencing a problem and data from this file could potentially help me dissect the issue. Firstly, am I going about this the wrong way? Is there a better way to log exceptions that occur?
The problem is if I attempt to use the log method from another class using:
Logger.log(0,"","","");
It fails to find the file or indeed create the file if it isn’t already created. The code is attached below.
package com.example.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.text.format.Time;
import android.util.Log;
public class Logger extends Activity {
final static String FileName = "Log";
static FileOutputStream fos;
static FileInputStream fis;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("logger", "oncreate");
try {
File f = getFileStreamPath(FileName);
if (!f.exists()) {
Log.d("logger", "file doesn't exist");
fos = openFileOutput(FileName, Context.MODE_APPEND);
fos.write(("Created on " + Build.TIME + "\nDevice name: "
+ Build.MODEL + " \nAndroid Version" + Build.VERSION.SDK_INT)
.getBytes());
fos.close();
}
fos = openFileOutput(FileName, Context.MODE_APPEND);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void log(int type, String TAG, String msg) {
Log.d("logger", "file being written");
Log.println(type, TAG, msg);
Time now = new Time();
now.setToNow();
try {
fos = new FileOutputStream(FileName);
fos.write(("\n" + now.toString() + " " + type + " " + TAG + " " + msg).getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The file name is not suffice to write a file. You need to give a directory when using FileOutputStream unlike when using openFileOutput. Thus if you change this line:
To
This will fix the issue. Finally oncreate is not called when accessing a method within a class. You have to combine the two as follows: