retriving stock quote with yahoo finance - java

i have this form with a button upon submit i retrieve stock info from yahoo finance api, and use it to display onto three textviews
the url i use
http://download.finance.yahoo.com/d/quotes.csv?s=goog&f=sl1p2
and my button event handler is
URL url;
try {
url = new URL("http://download.finance.yahoo.com/d/quotes.csv?s=goog&f=sl1p2");
InputStream stream = url.openStream();
BufferedInputStream bis = new BufferedInputStream(stream);
ByteArrayBuffer bab = new ByteArrayBuffer(50);
int current = 0;
while((current = bis.read()) != -1){
bab.append((byte) current);
}
String stockTxt = new String(bab.toByteArray());
String[] tokens = stockTxt.split(",");
String stockSymbol = tokens[0];
String stockPrice = tokens[1];
String stockChange = tokens[2];
String fstockSymbol = stockSymbol.substring(1, stockSymbol.length() -1);
String fstockChange = stockChange.substring(1, stockChange.length()-3);
symbolOut.setText(fstockSymbol);
priceOut.setText(stockPrice);
changeOut.setText(fstockChange);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
so what i noticed till the first line there seems to be no problem i.e url = new URL...,(even the bare http request done through browser, does return the info i need )
and my manifest entry looks like
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
below is the logcat output
05-02 18:36:32.804: D/AndroidRuntime(902): Shutting down VM
05-02 18:36:32.804: W/dalvikvm(902): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
05-02 18:36:33.113: E/AndroidRuntime(902): FATAL EXCEPTION: main
05-02 18:36:33.113: E/AndroidRuntime(902): android.os.NetworkOnMainThreadException
05-02 18:36:33.113: E/AndroidRuntime(902): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
05-02 18:36:33.113: E/AndroidRuntime(902): at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
05-02 18:36:33.113: E/AndroidRuntime(902): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
05-02 18:36:33.113: E/AndroidRuntime(902): at java.net.InetAddress.getAllByName(InetAddress.java:220)
05-02 18:36:33.113: E/AndroidRuntime(902): at libcore.net.http.HttpConnection.<init>(HttpConnection.java:71)
so anybody knows where im going wrong

This is the key error in your LogCat message --> android.os.NetworkOnMainThreadException. You should move your network access to a background thread. You can use either an IntentService, AsynchTask, Handler, etc. to accomplish this.
Check out http://developer.android.com/training/articles/perf-anr.html for more information about why it is important to do network ops on a separate thread.

Related

Geocoder.isPresent() causes NullPointerException?

I got the following error message from Google Play Developer Console.
Besides the try/catch I cannot find anything that could give a null pointer, was it the
Geocoder.isPresent() which is not available in API 8?
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.xxxxxxxx.SearchActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2100)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2125)
at android.app.ActivityThread.access$600(ActivityThread.java:140)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1227)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4898)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.xxxxxxxx.SearchActivity.updateUserLocationNameBasedOnNewCoordinates(SearchActivity.java:367)
at com.xxxxxxxx.SearchActivity.useDeviceLocation(SearchActivity.java:338)
at com.xxxxxxxx.SearchActivity.start(SearchActivity.java:495)
at com.xxxxxxxx.SearchActivity.onCreate(SearchActivity.java:253)
at android.app.Activity.performCreate(Activity.java:5206)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1083)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2064)
... 11 more
ACTIVITY:
public void updateUserLocationNameBasedOnNewCoordinates() {
String city = null;
String country = null;
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> list;
if (Geocoder.isPresent()) {
try {
list = geocoder.getFromLocation(userLocation.getLatitude(),
userLocation.getLongitude(), 1);
Address address = list.get(0);
city = address.getLocality();
country = address.getCountryName();
} catch (IOException e) {
e.printStackTrace();
}
}
if (city == null || country == null)
locationDescription = "Map location";
else
locationDescription = city + " " + country;
}
MANIFEST:
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
If you see the documentation of Geocoder.isPresent(), it says: Lack of network connectivity may still cause these methods to return null or empty lists. So make sure you are connected.
Other important thing is that the document says that it was added in API level 9 but you have stated android:minSdkVersion=8 in the manifest. Try to mention android:minSdkVersion=9 or above. Hope this helps.

json parse error inside a Asyntask in android

I get this error "Sometimes" in my App, I use a Asyntask:
03-19 08:10:05.768: E/AndroidRuntime(280): FATAL EXCEPTION: main
03-19 08:10:05.768: E/AndroidRuntime(280): java.lang.NumberFormatException: unable to parse 'null' as integer
03-19 08:10:05.768: E/AndroidRuntime(280): at java.lang.Integer.parseInt(Integer.java:406)
03-19 08:10:05.768: E/AndroidRuntime(280): at java.lang.Integer.parseInt(Integer.java:382)
03-19 08:10:05.768: E/AndroidRuntime(280): at java.lang.Integer.valueOf(Integer.java:682)
03-19 08:10:05.768: E/AndroidRuntime(280): at Dic.proj.pkg.notifService$1$1$1$1.onPostExecute(notifService.java:76)
03-19 08:10:05.768: E/AndroidRuntime(280): at Dic.proj.pkg.notifService$1$1$1$1.onPostExecute(notifService.java:1)
03-19 08:10:05.768: E/AndroidRuntime(280): at android.os.AsyncTask.finish(AsyncTask.java:417)
03-19 08:10:05.768: E/AndroidRuntime(280): at android.os.AsyncTask.access$300(AsyncTask.java:127)
03-19 08:10:05.768: E/AndroidRuntime(280): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
03-19 08:10:05.768: E/AndroidRuntime(280): at android.os.Handler.dispatchMessage(Handler.java:99)
03-19 08:10:05.768: E/AndroidRuntime(280): at android.os.Looper.loop(Looper.java:123)
03-19 08:10:05.768: E/AndroidRuntime(280): at android.app.ActivityThread.main(ActivityThread.java:4627)
03-19 08:10:05.768: E/AndroidRuntime(280): at java.lang.reflect.Method.invokeNative(Native Method)
03-19 08:10:05.768: E/AndroidRuntime(280): at java.lang.reflect.Method.invoke(Method.java:521)
03-19 08:10:05.768: E/AndroidRuntime(280): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
03-19 08:10:05.768: E/AndroidRuntime(280): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
03-19 08:10:05.768: E/AndroidRuntime(280): at dalvik.system.NativeStart.main(Native Method)
i call my Asyntask inside a timer. this is my my Asyntask:
// fetch new notifications
class fetch_last_asyn extends AsyncTask<Void, Integer, Boolean> {
#Override
protected Boolean doInBackground(Void... arg0) {
RestClient client = new RestClient(
"http://myaddress.org/api/get_last.php");
client.AddParam("last", String.valueOf(last_notif_no));
try {
client.Execute(RequestMethod.GET);
} catch (Exception e) {
e.printStackTrace();
}
String response = client.getResponse();
last_notifs = response.toString();
return true;
}
}
Inside my app I send my Asyntask result to parse to a code (parse_get_update), this is it:
public static String[][] parse_get_update(String jsonResponse) {
String[][] notifs = new String[3000][10];
try {
JSONArray jsonArray = new JSONArray(jsonResponse);
for (int index = 0; index < jsonArray.length(); index++) {
JSONObject json = jsonArray.getJSONObject(index);
// get name & id here
String id = json.getString("id");
String notifno = json.getString("notifno");
String title = json.getString("title");
String description = json.getString("description");
notifs[index][0] = id;
notifs[index][1] = notifno;
notifs[index][2] = title;
notifs[index][3] = description;
// notif_count++;
}
cnt2 = jsonArray.length();
} catch (JSONException e) {
e.printStackTrace();
}
return notifs;
}
Why do I get this error? What is NULL? I cant understand this.
I use ResClient for parse JSON. This error occures sometimes only, about 10% of times...
Thanks for your answers
In your postExecute() method, somewhere, you're parsing a String to Integer using this - Integer.parseInt(str);
Most of the times that str is a valid number, hence, its working. But those 10% of times, that str is probably missing or coming as an emtpy String from the JSON and hence, a null is passed to the Integer.parseInt(null), which is causing the java.lang.NumberFormatException.
Identify that piece of code, and put a null check for that, before parsing it to Integer.
The error means that you are trying to parse a string which has nothing in it. To demonstrate you have are doing like below.
String s = "";
int i = Integer.parseInt(s);
You need to have a condition like below so that it doesn't parse if the string is empty. You can even use try catch block as well.
if(s is not null) {
then do parse here
}
else {
assign a default value
}
This is happening due to you're parsing a String to Integer see this answer.

Android with websocket communication (Node Websocket server and Android Java Client). Dosen't work on Android 4

I tried to use as a Android client Websocket - weberknecht with a thread to send every second a message to a Nodejs Websocket (js): Node WebSocket Server
It work fine on android 2 or 2.3.3, but when i trie on android 4 i get an error on websocket.connect();
Do you know why or what i am doing wrong?
My code is:
public class MainThread extends Thread {
private boolean is_running;
private URI url = null;
private de.roderick.weberknecht.WebSocket websocket = null;
public MainThread() {
this.is_running = false;
try {
url = new URI("ws://192.168.1.88:8088/");
websocket = new WebSocketConnection(url);
websocket.setEventHandler(new WebSocketEventHandler() {
public void onOpen(){
System.out.println("--open");
}
public void onMessage(WebSocketMessage message){
System.out.println("--received message: " + message.getText());
}
public void onClose(){
System.out.println("--close");
}
});
} catch (WebSocketException wse) {
wse.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (URISyntaxException use) {
use.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
#Override
public void run() {
while(is_running){
try {
websocket.send("hello world");
Thread.sleep(10000);
}
catch (WebSocketException wse) {
wse.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void set_running(boolean is_running) {
if(is_running == true)
try {
websocket.connect();
this.is_running = is_running;
} catch (WebSocketException e) {
System.out.println(e.toString());
//e.printStackTrace();
}
}
}
and the error I get on android 4:
ERROR/AndroidRuntime(562): FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.biskis.test.websocket/com.biskis.test.websocket.GameActivity}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
at libcore.io.IoBridge.connect(IoBridge.java:112)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.Socket.startupSocket(Socket.java:566)
at java.net.Socket.tryAllAddresses(Socket.java:127)
at java.net.Socket.<init>(Socket.java:177)
at java.net.Socket.<init>(Socket.java:149)
at de.roderick.weberknecht.WebSocketConnection.createSocket(WebSocketConnection.java:238)
at de.roderick.weberknecht.WebSocketConnection.connect(WebSocketConnection.java:83)
at com.biskis.test.websocket.MainThread.set_running(MainThread.java:76)
at com.biskis.test.websocket.GameActivity.onCreate(GameActivity.java:20)
at android.app.Activity.performCreate(Activity.java:4465)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
... 11 more
Or do you know how to implement this in a better way to comunicate a client (java, android) to a server (nodejs, websocket) ?
Thank you.
Don't connect to the Websocket on the main Thread (i.e. in GameActivity.onCreate) and the error will go away. You could use an AsyncTask to connect to the Websocket in the background.
Blocking the main thread by I/O operations (and network access is ultimately a I/O operation) will lead (in the worst case) to a sluggish user interface or Android killing your application because it didn't react timely. See the designing for responsiveness document.

HttpResponse using android issue: execute always causes exception?

I've been working on an Android project and I'm at a point where I want to ask some API for information. Seems like this should be very basic!
Here's the general gist of my code:
private InputStream retrieveStream2(String url)
{
DefaultHttpClient client = new DefaultHttpClient();
HttpGet getRequest = new HttpGet(url);
System.out.println("getRequest == " + getRequest);
try {
HttpResponse getResponse = client.execute(getRequest);//here is teh problem
final int statusCode = getResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK)
{
Log.w(getClass().getSimpleName(),
"Error " + statusCode + " for URL " + url);
return null;
}
HttpEntity getResponseEntity = getResponse.getEntity();
return getResponseEntity.getContent();
}
catch (Exception e)
{
getRequest.abort();
Log.w(getClass().getSimpleName(), "Error for URL, YO " + url, e);
}
return null;
}
where url variable is the string "http://search.twitter.com/search.json?q=javacodegeeks".
As you can see there is some nice JSON info at that site; My problem is that every time ''client.execute(getRequest);'' is called, the program throws and catches an exception. Not useful!
I've heard two things:
1) You have to set permission for the emulator/device to use the internet!
-- I think I covered this, but maybe I did it wrong!
In the androidmanifest.xml I added
< uses-permission android:name="android.permission.INTERNET" >< /uses-permission>
So there's that.
2) (which I'm not so certain about) you cannot start a 'networking' thread within a 'ui' thread. I'm not entirely sure what this means, but i went ahead and followed some tutorial on Android Threads, Handlers and AsyncTasks. Here: Please check out the code under the AsyncTask tutorial, which I followed:
http://www.vogella.de/articles/AndroidPerformance/article.html
After following along with the AsyncTask tutorial, I found that I still had the same problem--
the line:
HttpGet httpGet = new HttpGet(url)
always threw an exception, like before.
Here is the logcat from my attempt with the threading tutorial above:
02-27 20:43:28.565: I/ActivityManager(92): START {cmp=com.Prometheus.R1/.JsonParsingActivity} from pid 574
02-27 20:43:28.565: W/WindowManager(92): Failure taking screenshot for (180x300) to layer 21010
02-27 20:43:28.896: I/System.out(574): pre execute
02-27 20:43:29.236: I/ActivityManager(92): Displayed com.Prometheus.R1/.JsonParsingActivity: +638ms
02-27 20:43:29.329: I/ARMAssembler(35): generated scanline__00000077:03010104_00008001_00000000 [ 89 ipp] (110 ins) at [0x40fad6a8:0x40fad860] in 7204915 ns
02-27 20:43:30.016: W/System.err(574): java.net.UnknownHostException: Unable to resolve host "search.twitter.com": No address associated with hostname
02-27 20:43:30.016: W/System.err(574): at java.net.InetAddress.lookupHostByName(InetAddress.java:426)
02-27 20:43:30.026: W/System.err(574): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
02-27 20:43:30.026: W/System.err(574): at java.net.InetAddress.getAllByName(InetAddress.java:220)
02-27 20:43:30.026: W/System.err(574): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
02-27 20:43:30.036: W/System.err(574): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
02-27 20:43:30.036: W/System.err(574): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
02-27 20:43:30.046: W/System.err(574): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
02-27 20:43:30.046: W/System.err(574): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
02-27 20:43:30.046: W/System.err(574): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
02-27 20:43:30.055: W/System.err(574): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
02-27 20:43:30.055: W/System.err(574): at com.Prometheus.R1.JsonParsingActivity$DownloadWebPageTask.doInBackground(JsonParsingActivity.java:88)
02-27 20:43:30.055: W/System.err(574): at com.Prometheus.R1.JsonParsingActivity$DownloadWebPageTask.doInBackground(JsonParsingActivity.java:1)
02-27 20:43:30.055: W/System.err(574): at android.os.AsyncTask$2.call(AsyncTask.java:264)<br/>
02-27 20:43:30.066: W/System.err(574): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
02-27 20:43:30.066: W/System.err(574): at java.util.concurrent.FutureTask.run(FutureTask.java:137)<br/>
02-27 20:43:30.066: W/System.err(574): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
02-27 20:43:30.076: W/System.err(574): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
02-27 20:43:30.076: W/System.err(574): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
02-27 20:43:30.087: W/System.err(574): at java.lang.Thread.run(Thread.java:856)
02-27 20:43:30.108: W/System.err(574): Caused by: libcore.io.GaiException: getaddrinfo failed: EAI_NODATA (No address associated with hostname)
02-27 20:43:30.116: W/System.err(574): at libcore.io.Posix.getaddrinfo(Native Method)
02-27 20:43:30.116: W/System.err(574): at libcore.io.ForwardingOs.getaddrinfo(ForwardingOs.java:55)
02-27 20:43:30.126: W/System.err(574): at java.net.InetAddress.lookupHostByName(InetAddress.java:411)
02-27 20:43:30.126: W/System.err(574): ... 18 more
02-27 20:43:30.136: I/System.out(574): Except thrown by url http://search.twitter.com/search.json?q=javacodegeeks, ....
02-27 20:43:30.136: I/System.out(574): response =
The exception is an UnknownHostException as you can see:
"ava.net.UnknownHostException: Unable to resolve host "search.twitter.com": No address associated with hostname"
But I don't think the site is unacceptable...
Can anyone tell me what's going on + what I need to do to get through it?
Check the permissions of your manifest, make sure you have added this:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
Figured it out. Apparently I turned my AVD off of "airplane mode".
For anybody having the same problem as me, you're probably using wireless. For some reason the android looks at your LAN card, so go to your Network Connections and right click on the LAN card-- DISABLE THAT THING! Problem solved.
I ran into this problem as well. In my case, I am using HttpURLConnection to load JSON. The issue was fixed when I enabled "follow redirects." Here is a code-snippet that works:
HttpURLConnection connection = null;
BufferedReader reader = null;
String JSON_data = null;
try {
final int half_hour = 30 * 60;
URL fetch = new URL(requestUrl);
connection = (HttpURLConnection) fetch.openConnection();
// FIXED: request to follow redirects - this seems to solve networking issues on older devices < API 21
connection.setInstanceFollowRedirects(true);
connection.setUseCaches(true);
connection.setDefaultUseCaches(true);
connection.setRequestMethod("GET");
connection.addRequestProperty("Cache-Control", "max-age="+half_hour);
connection.addRequestProperty("X-Auth-Token", getString(R.string.api_key));
boolean redirect = false;
int status = connection.getResponseCode();
if (status != HttpURLConnection.HTTP_OK) {
if (status == HttpURLConnection.HTTP_MOVED_TEMP
|| status == HttpURLConnection.HTTP_MOVED_PERM
|| status == HttpURLConnection.HTTP_SEE_OTHER)
redirect = true;
}
Log.d(TAG, "===> HTTP STATUS CODE: " + status + ", redirect=" + redirect);
connection.connect();
// Read the input stream into a String
InputStream inputStream = connection.getInputStream();
if (inputStream == null) {
return;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder buffer = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
buffer.append("\n");
}
if (buffer.length() == 0) {
return;
}
JSON_data = buffer.toString();
Log.d(TAG, "JSON_data=" + JSON_data);
} catch (Exception e) {
// possible UnknownHostException on older Android device?
Log.e(TAG, "HttpURLConnection Exception - e=" + e.getMessage());
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
Log.e(TAG, "Error closing stream - e=" + e.getMessage());
}
}
}
I think the problem resides in the url you have given in the http request or the internet connection pls check the below link it will help you Link
It doesn't mean you have problem with the app, its because you are using wi-fi internet,
so to solve this, keep your laptop connected to wi-fi and restart the emulator
It worked for me
In my case I just restarted the Android Studio including the emulator, and it became error free.
Sometimes I see similar logs in analytics system. I think, there is a problem in a server. Sometimes it doesn't respond (for a short time). Or, maybe, a user connection is weak (for instance, under ground or inside buildings).
you can allow network access in the main thread via the following snippet. at the beginning of your onCreate() method of your activity.
StrictMode.ThreadPolicy policy = new StrictMode.
ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

After HTTP GET request, the resulting string is cut-off - content has been consumed

I'm making a http get request like this:
try {
HttpClient client = new DefaultHttpClient();
String getURL = "http://busspur02.aseag.de/bs.exe?SID=5FC39&ScreenX=1440&ScreenY=900&CMD=CR&Karten=true&DatumT="+day+"&DatumM="+month+"&DatumJ="+year+"&ZeitH="+hour+"&ZeitM="+min+"&Intervall=60&Suchen=(S)uchen&GT0=Aachen&T0=H&HT0="+start_from+"&GT1=Aachen&T0=H&HT1="+destination+"";
HttpGet get = new HttpGet(getURL);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
//do something with the response
Log.i("GET RESPONSE",EntityUtils.toString(resEntityGet));
}
...
} catch (...) {
...
}
It all works well... the only problem: the output from Log.i is cut-off... It's not the complete html page. If I make the same request in a browser, I get 3x the output in opposition to making the request in the emulator and using the above code.... what's wrong?
ERROR:
04-30 14:01:01.287: WARN/System.err(1088): java.lang.IllegalStateException: Content has been consumed
04-30 14:01:01.297: WARN/System.err(1088): at org.apache.http.entity.BasicHttpEntity.getContent(BasicHttpEntity.java:84)
04-30 14:01:01.297: WARN/System.err(1088): at org.apache.http.conn.BasicManagedEntity.getContent(BasicManagedEntity.java:100)
04-30 14:01:01.307: WARN/System.err(1088): at org.apache.http.util.EntityUtils.toString(EntityUtils.java:112)
04-30 14:01:01.307: WARN/System.err(1088): at org.apache.http.util.EntityUtils.toString(EntityUtils.java:146)
04-30 14:01:01.307: WARN/System.err(1088): at mjb.project.AVV.ParseHTML.start(ParseHTML.java:177)
04-30 14:01:01.307: WARN/System.err(1088): at mjb.project.AVV.ParseHTML.onCreate(ParseHTML.java:139)
04-30 14:01:01.307: WARN/System.err(1088): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-30 14:01:01.327: WARN/System.err(1088): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459)
04-30 14:01:01.327: WARN/System.err(1088): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
04-30 14:01:01.327: WARN/System.err(1088): at android.app.ActivityThread.access$2200(ActivityThread.java:119)
04-30 14:01:01.347: WARN/System.err(1088): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
04-30 14:01:01.347: WARN/System.err(1088): at android.os.Handler.dispatchMessage(Handler.java:99)
04-30 14:01:01.347: WARN/System.err(1088): at android.os.Looper.loop(Looper.java:123)
04-30 14:01:01.347: WARN/System.err(1088): at android.app.ActivityThread.main(ActivityThread.java:4363)
04-30 14:01:01.347: WARN/System.err(1088): at java.lang.reflect.Method.invokeNative(Native Method)
04-30 14:01:01.357: WARN/System.err(1088): at java.lang.reflect.Method.invoke(Method.java:521)
04-30 14:01:01.357: WARN/System.err(1088): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
04-30 14:01:01.357: WARN/System.err(1088): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
04-30 14:01:01.357: WARN/System.err(1088): at dalvik.system.NativeStart.main(Native Method)
OK I solved it.
As I understand, the content of the entity gets consumed if it's not "used". So I created a new String object with the content of the Entity, so to say a copy instead of a reference to the entity's content.
try {
HttpClient client = new DefaultHttpClient();
String getURL = "http://busspur02.aseag.de/bs.exe?SID=5FC39&ScreenX=1440&ScreenY=900&CMD=CR&DatumT="+day+"&DatumM="+month+"&DatumJ="+year+"&ZeitH="+hour+"&ZeitM="+min+"&Intervall=120&Suchen=(S)uchen&GT0=Aachen&T0=H&HT0="+start_from+"&GT1=Aachen&T0=H&HT1="+destination+"";
HttpGet get = new HttpGet(getURL);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
String sourceString = "";
if (resEntityGet != null) {
try {
dismissDialog();
sourceString= new String(EntityUtils.toString(resEntityGet));
Log.i("GET RESPONSE", sourceString);
} catch (ParseException exc) {
// TODO Auto-generated catch block
exc.printStackTrace();
} catch (IllegalStateException exc) {
// TODO Auto-generated catch block
exc.printStackTrace();
}
...
}
...
} catch(...) {
...
}
DixieFlatline is correct.
With this I get partial output:
Log.v(TAG, "RESPONSE: " + response);
With this I get full output:
for(String line : response.split("\n"))
Log.v(TAG, "LINE: " + line);
I think that Log limits the number of chars to 4070. I tried to display a long string in ddms locgat and i got only 4070 chars.
Great!
By the way, if you are using Eclipse with Debug perspective, at the "Variables" view:
(Window -> Show View -> Variables)
you can right-click on the window, select "Max Length" and insert "0".
This way you can see all the chars (the complete html) in the Variables view.

Categories