I am trying to read the user entered logs using log.i() programmatically as follows,
try {
Log.i("logs", "inside log.java");
String filter = "logcat ";
filter += "-d ";
filter += "logs:I";
// String[] command = new String[] { "logcat", "-s" , "logs:"+filter
// };
Process process = Runtime.getRuntime().exec(filter);
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
log = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
log.append(line);
log.append("\n");
}
clear = (Button) findViewById(R.id.clear);
clear.setOnClickListener(onCleared);
tv = (TextView) findViewById(R.id.logview);
tv.setText(log.toString());
} catch (IOException ex) {
Log.e("Logging", ex.toString());
}
// 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();
}
but it simply shows a black screen . but when i try to run the command in adb shell it works . my adb code is,
adb logcat -s logs:I
I was facing a similar problem while trying to log files to text programmatically. I think what's happening here is that the log reading process is blocking the UI (main) thread, resulting in the black screen.
Try putting the entire log reading process into an ASyncTask. That made it work for me!
Did you add this to your manifest file?
<uses-permission android:name="android.permission.READ_LOGS" />
Related
Reading logcat continuously and write into the internal storage for this i tried the below code.
public class LogCatTask extends AsyncTask<Void, String, Void> {
public AtomicBoolean run = new AtomicBoolean(true);
#Override
protected Void doInBackground(Void... params) {
try {
//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");
Runtime.getRuntime().exec("logcat -c");
Process process = Runtime.getRuntime().exec("logcat -f "+file);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
StringBuilder log = new StringBuilder();
String line = "";
Log.e("log cat task...","while...run.get()."+run.get());
while (run.get()) {
line = bufferedReader.readLine();
//Log.e("log cat task...","while...out.");
if (line != null) {
Log.e("log cat task...","while....");
log.append(line);
//publishProgress(log.toString());
//to write logcat in text file
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
// Write the string to the file
osw.write(log.toString());
osw.flush();
osw.close();
}
line = null;
Thread.sleep(10);
//Log.e("log cat task...","while...out.");
}
//Log.e("log cat task...","ouet....while....");
}
catch(Exception ex){
}
return null;
}
}
once the above code runs,it read the logcat and write into storage but upto some part of the log only it reads.it is not reading the continuos.How to read the logcat continuous?
Here's a working code snippet
try {
Process process = Runtime.getRuntime().exec("logcat");
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
StringBuilder log=new StringBuilder();
String line = "";
while ((line = bufferedReader.readLine()) != null) {
// do what you want with the line you just read
// you're in an infinite loop continuously reading the log,
// you might want to add some mechanism to break out of it
}
}
catch (IOException e) {
fail("failed to get log");
}
Your code is overly complicated and prone to race conditions. For example, is the logcat -c guaranteed to complete before the logcat -f command. The -f command redirects output to a file, and your logic is also trying to write to that same file; that's very problematic. I've noticed that some of the logcat options such as "-T" doesn't work programmatically. Maybe the "-f" option also has problems. If you only want to read the log file up to the current time use "logcat -d".
I am trying to read a file i download from Dropbox (using Dropbox CORE API).
private void downloadropboxfile(final String filename)
{
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
try {
File file = new File(getCacheDir(),filename);
if(!file.exists())
file.createNewFile();
FileOutputStream outputStream = new FileOutputStream(file);
DropboxAPI.DropboxFileInfo info=mDBApi.getFile("/" + filename, null, outputStream, null);
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
Then in another function i call the downloaddropbox function and try to read the file content on Onclick event.
String filename = "info.txt";
downloadropboxfile(filename);
String strLine = "";
try {
InputStream instream = new FileInputStream(new File(getCacheDir(),filename));
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader bReader = new BufferedReader(inputreader);
/** Reading the contents of the file , line by line */
while ((strLine = bReader.readLine()) != null) {
mTestOutput.setText(strLine);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
My problem is that i don't get the file content immediately. I need to click the button 3-4 times in order to read the file content. What's the problem with my code?
You're calling downloaddropboxfile, which starts a new thread to download the file. But then you're immediately trying to read the local file (before it's downloaded).
If you haven't worked with threading before, the important thing to understand is that downloaddropboxfile returns almost immediately, but the thread it starts keeps running in the background. You'll need to wait for it to finish before trying to do something with the downloaded file.
I am trying to open the sdcard's .txt file in my EditText to change the text in it and
save the changes using button click but its not going in right way .May I know what is the correct way to achieve my objective?
try this one..
you must set permission in the manifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "followed by ur file dir");
File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "sdcard.txt");
for (File wavfile : f.listFiles())
{
String str = wavfile.getName().toString();
StringBuffer stringBuffer = new StringBuffer();
String aDataRow = "";
String aBuffer = "";
try {
File myFile = new File("/sdcard/"+filename);
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
myReader.close();
edtitext.setText(aBuffer.tostring());
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext
(),aBuffer,Toast.LENGTH_LONG).show();
}
}
again btnclick you have to write that edited string right..
use this one for write in that file..
FileOutputStream fos;
try {
File myFile = new File("/sdcard/"+sdcard.txt);
myFile.createNewFile();
FileOutputStream fOut = new
FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new
OutputStreamWriter(fOut);
myOutWriter.append(data);
myOutWriter.close();
fOut.close();
Toast.makeText(getApplicationContext(),filename + "
saved",Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {e.printStackTrace();}
catch (IOException e) {e.printStackTrace();}
}
thank you...
more detalis ref this link'
http://www.javatpoint.com/android-external-storage-example
----------------------------------------------------------
Some manufacturers (mainly Samsung) give write permissions only to the internal storage mounted at /storage/sdcard.
Also you should enable your app to write to external storage by adding this permission in the manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
First try to read the complete text file and save the text in a string.
For that you can refer this link
When you read the complete text file and get the text in a string, set the string to the editText by
edtitext.setText(your string);
I tried to find this but couldn't find and results. Apologies if this is a duplicate.
I would like to have android logs written to a file. But i do not wish them to be written to the file in the end, rather as the log statement is executed, it should be written into this file.
But i do not wish them to be written to the file in the end, rather as the log statement is executed, it should be written into this file.
Then write one or more methods that log to a file, possibly in addition to logging to LogCat.
Logging to files has been done in Java development for ~15 years, and there is plenty of code available to demonstrate it.
You can try this code!
public static void printLog(Context context){
String filename = context.getExternalFilesDir(null).getPath() + File.separator + "my_app.log";
String command = "logcat -d *:V";
Log.d(TAG, "command: " + command);
try{
Process process = Runtime.getRuntime().exec(command);
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
try{
File file = new File(filename);
file.createNewFile();
FileWriter writer = new FileWriter(file);
while((line = in.readLine()) != null){
writer.write(line + "\n");
}
writer.flush();
writer.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
catch(IOException e)
{
e.printStackTrace();
}
}
Ref: How to keep on appending logs while writing into File in SDCard?
i use this:
Logger logger=Logger.getLogger("myLoggerName");
logger.setLevel(Level.ALL);
File logFileDirectory=new File(getExternalFilesDir(null),"myLogDirectory");
addFileHandler(logger,logFileDirectory,"myLogFile");
So the Title pretty much sums up my problem, but I'm not sure what I'm doing wrong as far as code goes.
Here's the snipbit where I write to the file:
try {
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
OutputStreamWriter osw = new OutputStreamWriter(fos);
osw.append(assignmentTitle + "\n" + assignmentDate + "\n");
osw.flush();
osw.close();
} catch (FileNotFoundException e) {
//catch errors opening file
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Edit: This is where I read from the file every time the activity is called
private void readDataFromFile() {
try {
//Opens a file based on the file name stored in FILENAME.
FileInputStream myIn = openFileInput(FILENAME);
//Initializes readers to read the file.
InputStreamReader inputReader = new InputStreamReader(myIn);
BufferedReader BR = new BufferedReader(inputReader);
//Holds a line from the text file.
String line;
//currentAssignment to add to the list
Assignment currentAssignment = new Assignment();
while ((line = BR.readLine()) != null) {
switch (index) {
case 0:
//Toast.makeText(this, line, Toast.LENGTH_LONG).show();
currentAssignment.setTitle(line);
index++;
break;
case 1:
//Toast.makeText(this, Integer.toString(assignmentListIndex), Toast.LENGTH_LONG).show();
currentAssignment.setDate_due(line);
Statics.assignmentList.add(assignmentListIndex, currentAssignment);
index = 0;
assignmentListIndex++;
currentAssignment = new Assignment();
break;
default:
Toast.makeText(this, "error has occured", Toast.LENGTH_SHORT).show();
break;
}
}
BR.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Thats in a function when the user clicks on create a new assignment. When they click the save button on the assignment, it's supposed to save that assignment to a file and then I read it later and display it in a listView. What it's doing is displaying the first item in the listView and when I create a new assignment, it's overwriting the previous text in save file and replacing it in the listView. If you guys need me to post more code Let me know. I'm so confused as to why this isn't working :(
Instead of Context.MODE_PRIVATE, use Context.MODE_APPEND. This mode appends to an existing file instead of erasing it. (More detail on those in the openFileOutput docs.)
Instead of using OutputStreamWriter Class i suggest you to use BufferedWriter Class just as follows,
private File myFile = null;
private BufferedWriter buff = null;
myFile = new File ( "abc.txt" );
buff = new BufferedWriter ( new FileWriter ( myFile,true ) );
buff.append ( assignmentTitle );
buff.newLine ( );
buff.append ( assignmentDate );
buff.newLine ( );
buff.close();
myFile.close();