android writing log statements to sdcard - android

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.

Related

Android Studio : How to save text files from EditText into a specific directory

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)

Error in adding text to existing txt file

Firstly, i know there are same questions in this web site but i couldn't add text to my existing txt file. maybe i miss out something but where ? anyway here are my codes.
i have translate.txt file. it is /raw folder.and When i click the button, the words which are written in the editTexts(w1,w2) must be added to the existing translate.txt file.But it is not working..
public class Add extends Activity {
EditText w1,w2;
Button save;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.add);
w1=(EditText)findViewById(R.id.idText1);
w2=(EditText)findViewById(R.id.idText2);
save=(Button) findViewById(R.id.idSave);
save.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
String word1=w1.getText().toString();
String word2=w2.getText().toString();
writefile(word1,word2);
}
});
}
public void writefile(String word1,String word2)
{
try
{
String finalstring=new String(word1 + " " + word2);
FileOutputStream fOut = openFileOutput("translate.txt",MODE_APPEND);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write(finalstring);
osw.flush();
osw.close();
Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show();
} catch(Exception e)
{
Toast.makeText(this, "ERROR!!!", Toast.LENGTH_SHORT).show();
}
}
}
A) Code to write APPEND file in Android
public void writefile(String word1,String word2)
try {
String path = sdCard.getAbsolutePath() + "/";
File logFile = new File(path + "translate.txt");
if (!logFile.exists()) {
logFile.createNewFile();
}
// BufferedWriter for performance, true to set append to file
FileWriter fw = new FileWriter(logFile, true);
BufferedWriter buf = new BufferedWriter(fw);
buf.append(word1 + " " + word2);
buf.newLine();
buf.flush();
}
buf.close();
} catch (IOException e) {
e.printStackTrace();
}
B) Rule/ Permission
AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
EDIT For user
You cannot write a file to raw folder. Its read-only. Precisely you can't modify anything contained within "Res" folder on the fly.
Check this out, https://stackoverflow.com/a/3374149
Just in case you don't want to store the data in sd card and want to use the previous method
the way you was creating a file and stroing data to it was not actually editing the file in res/ raw folder ( because it can not be edited )
but the data you was writing was actually stored in a private file associated with this Context's application package for reading.
hence it was there and the file can be read as follow:
private void readFile() {
// TODO Auto-generated method stub
try {
FileInputStream fin = openFileInput("translate.txt");
InputStreamReader isr = new InputStreamReader(fin);
BufferedReader br = new BufferedReader(isr);
String str;
StringBuilder str2 = new StringBuilder();
while ((str = br.readLine()) != null) {
str2 = str2.append(str);
}
isr.close();
editText.setText(str2.toString());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
you can follow this method incase you dont want to store file in sd card because files in sd crad can be read by anyone.

extend Android.util.Log to write to file

I would like to extend the android.util.Log class to also write to a log file in internal storage of the device, preferrably also for specific TAGS.
I currently have an implementation:
public class CustomLogger{
private final static Logger fileLog = Logger.getLogger(MainActivity.class);
private Context context;
public CustomLogger(Context c){
this.context = c;
final LogConfigurator logConfigurator = new LogConfigurator();
logConfigurator.setFileName(context.getFilesDir() + File.separator + "myApp.log");
logConfigurator.setRootLevel(Level.DEBUG);
logConfigurator.setLevel("org.apache", Level.ERROR);
logConfigurator.configure();
}
public void i(String TAG, String message){
// Printing the message to LogCat console
Log.i(TAG, message);
// Write the log message to the file
fileLog.info(TAG+": "+message);
}
public void d(String TAG, String message){
Log.d(TAG, message);
fileLog.debug(TAG+": "+message);
}
}
As you can see this custom logger logs both to a log file on the internal storage (using the android-logging-log4j library) and through the android.util.Log class.
However i would like the standard log entries from the android.util.Log class in my log file, and if possible only certain (custom) TAGS.
Anybody has an example or any good tips on how to reach this?
Thanks in advance
You can read log cat programmatically and store into text file or you send it wherever you want.
Below is the detailed article I have written for same:
Read & Store Log-cat Programmatically in Android
And for reading the logcat here is sample code:
public class LogTest extends Activity {
private StringBuilder log;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
Process process = Runtime.getRuntime().exec("logcat -d");
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
log=new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
log.append(line);
}
TextView tv = (TextView)findViewById(R.id.textView1);
tv.setText(log.toString());
} catch (IOException e) {
}
//convert log to string
final String logString = new String(log.toString());
//create text file in SDCard
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/myLogcat");
dir.mkdirs();
File file = new File(dir, "logcat.txt");
try {
//to write logcat in text file
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
// Write the string to the file
osw.write(logString);
osw.flush();
osw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
So there is much shorter variant
try {
final File path = new File(
Environment.getExternalStorageDirectory(), "DBO_logs5");
if (!path.exists()) {
path.mkdir();
}
Runtime.getRuntime().exec(
"logcat -d -f " + path + File.separator
+ "dbo_logcat"
+ ".txt");
} catch (IOException e) {
e.printStackTrace();
}

I can create file but can't write to it

Could someone look at this snippet of code please and let me know what I'm doing wrong? It's a simple function that takes a string as parameter which it uses as a file name, adding ".txt" to the end of it.
The function checks if the file exists, creating it if it doesn't and then writes two lines of text to the file. Everything appears to be working and the file is created successfully on the sd card. However, after everything is done, the file is empty (and has a size of 0 bytes).
I suspect it's something obvious that I'm overlooking.
public void writeFile(String fileName) {
String myPath = new File(Environment.getExternalStorageDirectory(), "SubFolderName");
myPath.mkdirs();
File file = new File(myPath, fileName+".txt");
try {
if (!file.exists()) {
if (!file.createNewFile()) {
Toast.makeText(this, "Error Creating File", Toast.LENGTH_LONG).show();
return;
}
}
OutputStreamWriter writer = new OutputStreamWriter(openFileOutput(file.getName(), Context.MODE_PRIVATE));
writer.append("First line").append('\n');
writer.append("Second line").append('\n');
writer.close();
}
catch (IOException e) {
// Do whatever
}
}
Hi I will show you the full code I use, works perfect.
I don't use
new OutputStreamWriter()
i use
new BufferedWriter()
here is my Snippet
public void writeToFile(Context context, String fileName, String data) {
Writer mwriter;
File root = Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + File.separator + "myFolder");
if (!dir.isDirectory()) {
dir.mkdir();
}
try {
if (!dir.isDirectory()) {
throw new IOException(
"Unable to create directory myFolder. SD card mounted?");
}
File outputFile = new File(dir, fileName);
mwriter = new BufferedWriter(new FileWriter(outputFile));
mwriter.write(data); // DATA WRITE TO FILE
Toast.makeText(context.getApplicationContext(),
"successfully saved to: " + outputFile.getAbsolutePath(), Toast.LENGTH_LONG).show();
mwriter.close();
} catch (IOException e) {
Log.w("write log", e.getMessage(), e);
Toast.makeText(context, e.getMessage() + " Unable to write to external storage.",Toast.LENGTH_LONG).show();
}
}
-- Original Code --
That one took a while to find out. The javadocs
here brought me on the right track.
It says:
Parameters
name The name of the file to open; can not contain path separators.
mode Operating mode. Use 0 or MODE_PRIVATE for the default operation, MODE_APPEND to append to an existing file, MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE to control permissions.
The file is created, if it does not exist, but it is created in the private app space. You create the file somewhere on the sd card using File.createNewFile() but when you do context.openFileOutput() it creates always a private file in the private App space.
EDIT: Here's my code. I've expanded your method by writing and reading the lines and print what I got to logcat.
<pre>
public void writeFile(String fileName) {
try {
OutputStreamWriter writer = new OutputStreamWriter(
getContext().openFileOutput(fileName + ".txt", Context.MODE_PRIVATE));
writer.append("First line").append('\n');
writer.append("Second line").append('\n');
writer.close();
}
catch (IOException e) {
Log.e("STACKOVERFLOW", e.getMessage(), e);
return;
// Do whatever
}
// Now read the file
try {
BufferedReader is = new BufferedReader(
new InputStreamReader(
getContext().openFileInput(fileName + ".txt")));
for(String line = is.readLine(); line != null; line = is.readLine())
Log.d("STACKOVERFLOW", line);
is.close();
} catch (IOException e) {
Log.e("STACKOVERFLOW", e.getMessage(), e);
return;
// Do whatever
}
}
Change the mode from Context.MODE_PRIVATE to Context.MODE_APPEND in openFileOutput()
MODE_APPEND
MODE_PRIVATE
Instead of
OutputStreamWriter writer = new OutputStreamWriter(openFileOutput(file.getName(), Context.MODE_PRIVATE));
Use
OutputStreamWriter writer = new OutputStreamWriter(openFileOutput(file.getName(), Context.MODE_APPEND));
UPDATE :
1.
FileOutputStream osr = new FileOutputStream(file.getName(), true); // this will set append flag to true
OutputStreamWriter writer = new OutputStreamWriter(osr);
BufferedWriter fbw = new BufferedWriter(writer);
fbw.write("First line");
fbw.newLine();
fbw.write("Second line");
fbw.newLine();
fbw.close();
Or 2.
private void writeFileToInternalStorage() {
FileOutputStream osr = new FileOutputStream(file.getName(), true); // this will set append flag to true
String eol = System.getProperty("line.separator");
BufferedWriter fbw = null;
try {
OutputStreamWriter writer = new OutputStreamWriter(osr);
fbw = new BufferedWriter(writer);
fbw.write("First line" + eol);
fbw.write("Second line" + eol);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fbw != null) {
try {
fbw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

OutputStreamWriter not writing

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?

Categories

Resources