Can logcat results for Log.i be viewed in our activity? - android

I would like to display Log.i results in my application. Is it possible? If so, how can I do it?

Here's a blogpost that does exactly what you need it to do. It has a complete code example on how to display the contents of the Logcat log. Here's the code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
class ReadLogDemo extends Activity {
#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()));
StringBuilder 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) {
}
}
}

Related

how to read json array from internal storage and send http request?

i need a clarification of http connection.i can read my json object from internal memory.how to send http request ?
i have to send send request in background simultaniously once send the data after that it will be going to empty till when next data will come to that file .
here my code is
package example.json.com.jsonarray;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class MainActivity extends Activity {
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView)findViewById(R.id.textView);
StringBuilder sb = new StringBuilder();
String data="";
try {
BufferedReader br = new BufferedReader(new FileReader(new File(Environment.getExternalStorageDirectory(),"mservice/database/queue_mgr.txt")));
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
try {
JSONArray jsonArray = new JSONArray(sb.toString());
//Iterate the jsonArray and print the info of JSONObjects
for(int i=0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
data+=jsonObject.toString();
}
Toast.makeText(this, data, Toast.LENGTH_LONG).show();
textView.setText("");
textView.append("\n\n-----START CONTENT-----\n\n");
textView.append(data);
} catch (JSONException e) {e.printStackTrace();}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

I can only read one line of code out of my text file

So I'm trying to make a todo list on Android where I can add items which then dynamically show in the list. So when I enter text in a text field and then press the add button, the list is expanded with the item I just created. This all goes well, but not if I completely get the application out of my memory stack and then restart it. When I reopen the application the list only consists of one item, the last item I added to the list before I closed the app. This is my code:
package be.oefeningen.filestorage;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.view.View.OnClickListener;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.io.InputStreamReader;
public class FileStorageActivity extends ListActivity implements OnClickListener {
private ArrayList<String> values=new ArrayList<String>();
InputStream inputStream;
String line;
#Override
public void onClick(View v) {
EditText editText=(EditText) findViewById(R.id.editText);
String tekst=editText.getText().toString()+"\n";
FileOutputStream outputStream;
try {
outputStream=openFileOutput("todoitems",MODE_PRIVATE);
outputStream.write(tekst.getBytes());
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
inputStream = openFileInput("todoitems");
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
line = reader.readLine();
if (line != null){
values.add(line);
} else {
inputStream.close();
}
}catch (Exception e)
{
e.printStackTrace();
}
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,values);
setListAdapter(adapter);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
inputStream = openFileInput("todoitems");
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
line = reader.readLine();
while (line != null){
values.add(line);
line = reader.readLine();
}
inputStream.close();
}catch (Exception e)
{
e.printStackTrace();
}
setContentView(R.layout.activity_file_storage);
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,values);
setListAdapter(adapter);
}
}
Probable reason is, everytime you write to the file, you are losing the old data.
Replace this line
outputStream=openFileOutput("todoitems",MODE_PRIVATE);
with this line
outputStream=openFileOutput("todoitems", MODE_PRIVATE | MODE_APPEND);

Android app doesn't want do HttpClient request

I'm trying to launch first app that handles Http requests. The following code is from a tutorial book and it doesn't work:
package com.example.httpgetdemo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
public class Main extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BufferedReader in = null;
System.out.println("Before");
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://google.com/");
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String page = sb.toString();
System.out.println(page);
} catch (Exception e) {
e.printStackTrace();
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
What do I mean by saying it doesn't work - I run in it on a phone and LogCat shows the first System.out.println but not the second one, there is error saying:
E/(1755): Can't open file for reading
I read some threads over here about making it in asynchronous way, but if so, then the app would crash and, what-more, it's a book example so it should work, shouldn't it? The aim phone runs the ICS
What's wrong?
Thanks

Blank Screen and only pop up "Not Responding" dialog.

I am unable to figure out why I am stuck at this point although there is no error is my coding. My problem is actually, it doesn't print out my epub, as well as it just hangs there, till the not responding dialog comes up.
My code is as below:
package com.epub;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import nl.siegmann.epublib.domain.Book;
import nl.siegmann.epublib.domain.Resource;
import nl.siegmann.epublib.domain.Spine;
import nl.siegmann.epublib.domain.SpineReference;
import nl.siegmann.epublib.epub.EpubReader;
import android.app.Activity;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;
import android.widget.TextView;
public class EpubReaderActivity extends Activity {
WebView webView;
Book book;
TextView tv;
String line;
String linez;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = new TextView(this);
webView = (WebView)findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
AssetManager am = getAssets();
try {
InputStream epubInputStream = am.open("testbook.epub");
book = (new EpubReader()).readEpub(epubInputStream);
} catch (IOException e) {
Log.e("epublib", e.getMessage());
}
Spine spine = book.getSpine();
List<SpineReference> spineList = spine.getSpineReferences() ;
int count = spineList.size();
tv.setText(Integer.toString(count));
StringBuilder string = new StringBuilder();
for (int i = 0; count > i; i++) {
Resource res = spine.getResource(i);
try {
InputStream is = res.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
try {
while ((line = reader.readLine()) != null) {
linez = string.append(line + "\n").toString();
}
} catch (IOException e) {e.printStackTrace();}
//do something with stream
} catch (IOException e) {
e.printStackTrace();
}
}
webView.loadData(linez, "text/html", "utf-8");
}
}
Mind helping me out on this point?
An ANR(Application Not Responding) happens generally when you do a heavy job. In Android, if the OS can't execute one code line within about 5 seconds, the ANR dialog wil pop up. From your codes, it seems that you are reading and parsing an .epub file from your asset folder. I am not familiar with epub files, but I suspect this is a heavy task which blocks your app.
How about start a Thread or AsyncTask to read the file so the main thread would not be blocked?
Pu this code inside a thread as this takes time to write the data and load a web view
Thread is a different part of execution and you will have to wait for few sconds if yor file is large
you can also put a progress dialog to show loading of webview
new Thread(){
public void run() {
for (int i = 0; count > i; i++) {
Resource res = spine.getResource(i);
try {
InputStream is = res.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
try {
while ((line = reader.readLine()) != null) {
linez = string.append(line + "\n").toString();
}
} catch (IOException e) {e.printStackTrace();}
//do something with stream
} catch (IOException e) {
e.printStackTrace();
}
}
};
}.start();
More your file reading code form onCreaate() to onResume(). As data will be read once the UI show to user

how do i load remote text from a text file into android textview?

I have gone through all the examples and I can not seem to get this to work.
This is my current code:
package hello.android;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class HelloAndroidActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = (TextView) findViewById(R.id.textView1);
try {
// Create a URL for the desired page
URL url = new URL("http://xlradioaustin.com/song/CurrentSong.txt");
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {
// str is one line of text; readLine() strips the newline character(s)
}
in.close();
tv.setText(str);
} catch (MalformedURLException e) {
tv.setText("mal");
} catch (IOException e) {
tv.setText("io");
}
}
}
Assuming your Android device is online and you've granted your app the INTERNET permission, try this:
try {
// Create a URL for the desired page
URL url = new URL("http://xlradioaustin.com/song/CurrentSong.txt");
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
StringBuilder sb = new StringBuilder(100);
while ((str = in.readLine()) != null) {
sb.append(str);
// str is one line of text; readLine() strips the newline character(s)
}
in.close();
tv.setText(sb.toString());
} catch (MalformedURLException e) {
tv.setText("mal");
} catch (IOException e) {
tv.setText("io");
}
Let me know if that works: you are currently looping until str is null, then using that null value.
A follow up on the answer, it worked after adding
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}

Categories

Resources