Android write the whole logcat message in file - android

I have a function which writes exception logs in a file on SD CARD.But the problem is that it's writing only the first line of it, without any information about on which line is thrown that exception and etc. Any ideas how to get the whole Log?
Save to file :
public static void writeLogs(String text){
File logFile = new File("sdcard/Documents/Public/Log/crash_logs.file");
if (!logFile.exists())
{
try
{
logFile.createNewFile();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try
{
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append("---START---");
buf.newLine();
buf.append(text);
buf.newLine();
buf.append("---END---");
buf.newLine();
buf.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Invoke :
catch (Exception e) {
e.printStackTrace();
rpc.writeLogs(e.toString());
}
Any ideas?

e.toString doesn't provide the stack, try printStackTrace(writer or stream)

I had this problem too. I ended up splitting e.toString() by \n and then wrote each line individually to my log.

use println() instead of append.
PrintWriter p = new PrintWriter(new FileWriter("your text file.txt"));
p.println(text);

Related

Not able to create file for writing in "Lenovo IdeaTab"

The app is to write some data every second on file. This is working in other tabs & phones but in "Lenovo IdeaTab" (4.1) is able to create directory but not able to create file to write in it.
Below is the code, I am using to write in file:
public void writeDataInFile(String dataString)
{ File logFile = null;
try {
File folder = new File(Environment.getExternalStorageDirectory() + "/file_name_xyz");
boolean success = true;
if (!folder.exists()) {
success = folder.mkdir();
}
if (success) {
// Do something on success
String file_path = folder+"/"+currentFileName+".txt";
logFile = new File(file_path);
if (!logFile.exists())
{
try
{
logFile.createNewFile();
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append("\nxyz: \n");
buf.newLine();
buf.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} else {
// Do something else on failure
Toast.makeText(getApplicationContext(), "Failed to write", Toast.LENGTH_SHORT).show();
}
try
{
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(dataString);
buf.newLine();
buf.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
//Write internal storage -- data/data/xyzzz
try {
FileOutputStream fos = openFileOutput(currentFileName, Context.MODE_APPEND);
fos.write(dataString.getBytes());
fos.close();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
Verify which version of Android is installed on the Tablet and then lookup file IO API in the Android Docs for that version of Android. I'm pretty sure they changed some things when it comes to accessing files in some of the later versions of the API.

Writing data inside Android

How can I write data to text file inside an Android device?
As of now I am sending that data to server which writes it in json format. However, I want my program to write my data inside Android directly.
I want to record sensor values every time when sensors change their values. I have the following code:
What should I put instead of comment?
public void onSensorChanged(SensorEvent event)
{
switch(event.sensor.getType())
{
case Sensor.TYPE_LINEAR_ACCELERATION:
//writing event.values[0], event.values[1] and event.values[2] to result.txt
break;
..........
}
}
String strContent = "Write File using Java FileOutputStream example !";
FileOutputStream fileOut = openFileOutput(outputFile, MODE_APPEND);
OutputStreamWriter osw = new OutputStreamWriter(fileOut);
osw.writeBytes(strContent.getBytes());
osw.flush();
Other code:
File logFile = new File("sdcard/log.file");
if (!logFile.exists())
{
try
{
logFile.createNewFile();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try
{
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(text);
buf.newLine();
buf.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
I would not write the file everytime sensot is changed, but rather would build a String with only relevant data and write it to the file at the end of the process.

Android External Storage BufferedWriter doesn't accept NewLine

i have problem with file writing. I want to create OnClick method of button that add line to file on sdcard but instead it delete previous line and put all content in place of current one. In result i got only the Text i put at the last click of Button, here is my code:
if (txtFile.createNewFile() || txtFile.isFile()) {
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(txtFile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
BufferedWriter bwriter = new BufferedWriter(myOutWriter);
EditText desc__ = (EditText)findViewById(R.id.descriptionEditTExt);
try {
bwriter.newLine();
bwriter.write(lat+"|"+lng+"|"+desc__.getText().toString()+"|"+f+"|"+position);
bwriter.close();
myOutWriter.close();
fOut.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
/* handle directory here */
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Please rewrite your FileOutputStream constructor as
FileOutputStream fos = new FileOutputStream(file, true);
here is suggests that your file will be opened in the append mode which will solve your first problem..
secondly if you want to add new line to the file use "\r\n" string
e.g. fos.write("\r\n".getBytes());
Hope this helps..

How to write to a textfile in one Activity & read that file in another Activity?

I am able to write and then read a text file in the SAME activity, but I am unable to read a text file after writing to it from another Activity.
Ex: Activity A creates and writes to a text file. Activity B reads that text file.
I use this code to write to the text file in Activity A:
FileOutputStream fos = null;
OutputStreamWriter osw = null;
try
{
fos = openFileOutput("user_info.txt", Context.MODE_WORLD_WRITEABLE);
osw = new OutputStreamWriter(fos);
osw.write("text here");
osw.close();
fos.close();
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
And then I use this code to try and read the same text file created by Activity A, but I get a FileNotFoundException:
try
{
FileInputStream fis = openFileInput("user_info.txt");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader buff = new BufferedReader(isr);
String line;
while((line = buff.readLine()) != null)
{
Toast.makeText(this, line, Toast.LENGTH_LONG).show();
}
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
Does anyone know why I am getting the FileNotFoundException?
Is it a path issue?
Don't really know how is built your application, but, the error you get does seem like a path issue, are you sure both Activities are in the same folder ?
If not, you'll need to set either an abolute path (like : "/home/user/text.txt") for the text file or a relative path (like : "../text.txt").
If you're not sure, try to print the current path for the Activity using some command like
new File(".").getAbsolutePath();
And, although I can't say I'm expert with Android, are you sure you need the Context.MODE_WORLD_WRITEABLE for your file ? If no other application than yours is reading or writing from/to it, it should not be necessary, right ?
it is surealy a path issue.
you can write like this
fpath=Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+"yourdirectory";
File custdir=new File(fpath);
if(!custdir.exists())
{
custdir.mkdirs();
}
File savedir=new File(custdir.getAbsolutePath());
File file = new File(savedir, filename);
if(file.exists())
{
file.delete();
}
FileOutputStream fos;
byte[] data = texttosave.getBytes();
try {
fos = new FileOutputStream(file);
fos.write(data);
fos.flush();
fos.close();
Toast.makeText(getBaseContext(), "File Saved", Toast.LENGTH_LONG).show();
finish();
} catch (FileNotFoundException e) {
Toast.makeText(getBaseContext(), "Error File Not Found", Toast.LENGTH_LONG).show();
Log.e("fnf", ""+e.getMessage());
// handle exception
} catch (IOException e) {
// handle exception
Toast.makeText(getBaseContext(), "Error IO Exception", Toast.LENGTH_LONG).show();
}
and you can read like
String locatefile=Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+"yourdirectory"+"/filename";
try {
br=new BufferedReader(new FileReader(locatefile));
while((text=br.readLine())!=null)
{
body.append(text);
body.append("\n");
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

save more than one pic with different names in sdcard

Im doing a program where u can draw your signature on the phone. Right now it saves one image but I would like to save more than one image since there are more than one customer that needs to sign their package. very thankful for any kind of help.
public void save() {
File sdImageMainDirectory = new File("/sdcard/mySignatures");
sdImageMainDirectory.mkdirs();
String nameFile = "newpic";
FileOutputStream out = null;
try {
out = new FileOutputStream(sdImageMainDirectory.toString() +"/" + nameFile + ".jpg");
mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out=null;
}
Rather obviously, you need to change the filename to something unique for each one. Numbering them sequentially would work. Or you let the user enter a name, and validate it for legality.

Categories

Resources