Opening Assets Files - assetManager.open(file) throws Empty Exception? - android

I'm trying to plug in some Web UI / Javascript code into my app from chrome plugin apps.
Part of what the Javascript does is reading in some translation files (I don't want to change the method it uses to do this too much)
To do this I furnished the Javascript with the ability to read the contents of files in the assets folder for parsing through use of a Javascript interface method which takes a file name and returns the contents of the file as a String.
Unfortunately, this is throwing an exception, whose "message" is the file name I'm passing in. I have no idea therefore why this exception is being thrown:
public String getFileContents(String file) {
String fileContents = "";
try {
AssetManager assetManager = mContext.getAssets();
InputStream inputStream = assetManager.open(file);
BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
fileContents = total.toString();
} catch (IOException e) {
Log.e("IOException", e.getMessage());
Log.e(e);
}
return fileContents;
}
The exception given is below... Can anyone give me a clue as to why this file isn't being opened correctly?
04-11 10:22:12.233: E/Exception(4829): _locales/en/messages.json. android.content.res.AssetManager.openAsset(Native Method)
04-11 10:22:12.233: E/Exception(4829): android.content.res.AssetManager.open(AssetManager.java:316)
04-11 10:22:12.233: E/Exception(4829): android.content.res.AssetManager.open(AssetManager.java:290)
04-11 10:22:12.233: E/Exception(4829): com.test.decatur.object.CoreModInterface.getFileContents(CoreModInterface.java:51)
04-11 10:22:12.233: E/Exception(4829): com.android.org.chromium.base.SystemMessageHandler.nativeDoRunLoopOnce(Native Method)
04-11 10:22:12.233: E/Exception(4829): com.android.org.chromium.base.SystemMessageHandler.handleMessage(SystemMessageHandler.java:27)
04-11 10:22:12.233: E/Exception(4829): android.os.Handler.dispatchMessage(Handler.java:102)
04-11 10:22:12.233: E/Exception(4829): android.os.Looper.loop(Looper.java:136)
04-11 10:22:12.233: E/Exception(4829): android.os.HandlerThread.run(HandlerThread.java:61)

Related

android- Intentional '%' in string throws IllegalArgumentException

I am making a http call to an api for a string response.
The result contains intentional % signs in a sentence like:
"This land is 95% fertail and 5% contaminated"
Android throws IllegalArgumentException: Invalid % sequence at 1756 which corresponds to the "95%" part.
EDIT: StackTrace:
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.IllegalArgumentException: Invalid % sequence at 1756: [{"address":{"addressComponen...
My httpGet method:
public String makeHttpGetRequestUtf8(String urlStr) throws IOException {
String result = "";
try {
URL url = new URL(urlStr);
BufferedReader brIn = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
String line = "";
while ((line = brIn.readLine()) != null)
result += line;
}catch (Exception e){
Log.e("HTT_GET", "Failed to make httpGetRequestUtf8: " + e);
}
String afterDecode = URLDecoder.decode(result, "UTF-8");
return afterDecode;
}
Android throws IllegalArgumentException: Invalid % sequence at 1756 which corresponds to the "95%" part.
Server writes this data with this metod and so I believe the encoding should be fine?
File file = new File(path/filename.txt);
String content = writeMeToFile;
Writer out;
try{
out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(file), "UTF8"));
if(!file.exists()){
file.createNewFile();
}else{
FileUtils.copyFile(file, dest);
out.write(content);
out.close();
}
} catch (IOException e) {
Logger.getLogger(UpdateAds.class.getName()).log(Level.SEVERE, null, e);
}
Side question/note: Somehow characters like 'ä', 'ö', 'ü', 'õ' are fine in the browser but show up as � in android.
I don't understand at which side am I encoding the string wrong. Since the text is fine in the browser I am thinking it's android, but the httpGet method is done by the book.
Thanks!

Out of memory while reading large xml file from server using Post

I am using the below code to fetch xml file from the server and due to heavy and large xml file, it got crashed and showing Out of memory Issue.
public class Connect {
static BufferedReader in=null;
String result=null;
Context context;
//Establish connection with web server
public String HTTPConnect(String uri1,List<NameValuePair> list,Context context)
{
this.context=context;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(uri1);
if(list!=null)
{
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(list);
httpPost.setEntity(formEntity);
}
HttpResponse httpResponse = httpClient.execute(httpPost);
in = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
long heapSize = Runtime.getRuntime().totalMemory();
if(in!=null)
{
while ((line = in.readLine()) != null) {//crasheg here
sb.append(line + NL);
}
in.close();
}
result = sb.toString();
}
catch(UnsupportedEncodingException e)
{
String err = (e.getMessage()==null)?"Cant connect to server":e.getMessage();
ShowDialog();
}
catch (MalformedURLException e) {
String err = (e.getMessage()==null)?"Malformed Exception":e.getMessage();
ShowDialog();
}
catch(Exception ex)
{
String err = (ex.getMessage()==null)?"NetworkConnectionException":ex.getMessage();
ShowDialog();
}
finally {
if (in != null) {
try {
in.close();
} catch (Exception ex) {
String err = (ex.getMessage()==null)?"Excepion":ex.getMessage();
ex.printStackTrace();
}
}
}
return result;
}
I know that that I am copying the whole XML in String and due to heavy file, It gor crashing. It is working fine in small size of XML file, but what are the alternative for large xml file. I am uing SAX parser for parsing this xml file.
[EDIT]
Below is the logcat:
FATAL EXCEPTION: AsyncTask #4
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:200)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
at java.lang.Thread.run(Thread.java:1096)
Caused by: java.lang.OutOfMemoryError
java.lang.AbstractStringBuilder.enlargeBuffer(AbstractStringBuilder.java:97)
java.lang.AbstractStringBuilder.append0(AbstractStringBuilder.java:136)
java.lang.StringBuilder.append(StringBuilder.java:272)
java.io.BufferedReader.readLine(BufferedReader.java:452)
com.kxs.appitize.Connect.HTTPConnect(Connect.java:56)
com.kxs.appitize.ListRestaurants$Asyn_rest.doInBackground(ListRestaurants.java:168)
com.kxs.appitize.ListRestaurants$Asyn_rest.doInBackground(ListRestaurants.java:1)
01-at android.os.AsyncTask$2.call(AsyncTask.java:185)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
Activity com.kxs.appitize.TabsMainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#44f4fb28 that was originally added here
android.view.WindowLeaked: Activity com.kxs.appitize.TabsMainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#44f4fb28 that was originally added here
at android.view.ViewRoot.<init>(ViewRoot.java:247)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
at android.view.Window$LocalWindowManager.addView(Window.java:424)
at android.app.Dialog.show(Dialog.java:241)
at com.kxs.appitize.ListRestaurants$Asyn_rest.onPreExecute(ListRestaurants.java:156)
at android.os.AsyncTask.execute(AsyncTask.java:391)
at com.kxs.appitize.ListRestaurants.onCreate(ListRestaurants.java:133)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
at android.app.ActivityThread.startActivityNow(ActivityThread.java:2503)
at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:127)
at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:339)
at com.kxs.appitize.TabGroupActivity.startChildActivity(TabGroupActivity.java:72)
at com.kxs.appitize.ListCategories$1.onClick(ListCategories.java:109)
at android.view.View.performClick(View.java:2408)
at android.view.View$PerformClick.run(View.java:8816)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4627)
at java.lang.reflect.Method.invokeNative(Native Method)
java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
at dalvik.system.NativeStart.main(Native Method)
copying the whole XML in String and due to heavy file
Bad idea. First you need to cache the xml in a temporary directory. It should never be in the RAM.
Once you do that use SAX to parse the file. During parsing try not to keep the whole structure in the RAM, instead parse in bite sized chunks.
Try to use inputStream to parse XML. The inputStrem does not increase Android stack size and it's prevent possibles OOM with large String. I have the same things with large JSON and now, i use Jackson to parse JSON directly from Stream.
You can find equivalent library for parsing XML.

Using AndroidHttpClient will not work

I am trying to use AndroidHttpClient to download a CSV file. For some reason it fails in the line "HttpResponse response httpClient.execute(httpGet, localContext); and simply goes to "finally".
I've checked the URL in my browser - it is working fine.
I get no information from HttpResponse response - it simply like skips it.
I don't get why. Any ideas?
Thanks
D
private ArrayList<String> retrieveStockFinParamsFromYahooApiUri(String yahooApiCall)
{
ArrayList<String> stockFinParamsFromYahooApiUriRows = new ArrayList<String>();
String resultLine = "";
BufferedReader reader = null;
AndroidHttpClient httpClient = AndroidHttpClient.newInstance("yahooGetStockParams");
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet(yahooApiCall);
try
{
HttpResponse response = httpClient.execute(httpGet, localContext);
reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
while ((resultLine = reader.readLine()) != null)
{
stockFinParamsFromYahooApiUriRows.add(resultLine);
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if (reader != null)
{
try
{
reader.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
return stockFinParamsFromYahooApiUriRows;
}
FURTHER INVESTIGATION (05.22.2012):
#Snicolas - thank you for your comments. After I read your comments I thought the problem might originate from the fact that I used the emulator and not my actual device to debug this. I thought the emulator might suffer some connection problems. When I tested it on my device - I noticed the problem still occurred - so this was NOT the problem.
So I change my code to catch (Throwable e) as you advised and got the following stack snapshot:
05-22 18:17:41.457: W/System.err(24552): android.os.NetworkOnMainThreadException
05-22 18:17:41.461: W/System.err(24552): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
05-22 18:17:41.461: W/System.err(24552): at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
05-22 18:17:41.461: W/System.err(24552): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
05-22 18:17:41.465: W/System.err(24552): at java.net.InetAddress.getAllByName(InetAddress.java:220)
05-22 18:17:41.465: W/System.err(24552): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
05-22 18:17:41.465: W/System.err(24552): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
05-22 18:17:41.468: W/System.err(24552): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
05-22 18:17:41.468: W/System.err(24552): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
05-22 18:17:41.468: W/System.err(24552): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
05-22 18:17:41.472: W/System.err(24552): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
05-22 18:17:41.472: W/System.err(24552): at android.net.http.AndroidHttpClient.execute(AndroidHttpClient.java:257)
05-22 18:17:41.472: W/System.err(24552): at com.bewildering.app.StournamentDbAdapter$YahooStocksParams.retrieveStockFinParamsFromYahooApiUri(StournamentDbAdapter.java:1536)
05-22 18:17:41.476: W/System.err(24552): at com.bewildering.app.StournamentDbAdapter$YahooStocksParams.run(StournamentDbAdapter.java:1709)
05-22 18:17:41.476: W/System.err(24552): at com.bewildering.app.StournamentActivity.onCreate(StournamentActivity.java:65)
05-22 18:17:41.476: W/System.err(24552): at android.app.Activity.performCreate(Activity.java:4465)
05-22 18:17:41.476: W/System.err(24552): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
05-22 18:17:41.480: W/System.err(24552): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
05-22 18:17:41.480: W/System.err(24552): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
05-22 18:17:41.480: W/System.err(24552): at android.app.ActivityThread.access$600(ActivityThread.java:123)
05-22 18:17:41.484: W/System.err(24552): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
05-22 18:17:41.484: W/System.err(24552): at android.os.Handler.dispatchMessage(Handler.java:99)
05-22 18:17:41.484: W/System.err(24552): at android.os.Looper.loop(Looper.java:137)
05-22 18:17:41.484: W/System.err(24552): at android.app.ActivityThread.main(ActivityThread.java:4424)
05-22 18:17:41.488: W/System.err(24552): at java.lang.reflect.Method.invokeNative(Native Method)
05-22 18:17:41.488: W/System.err(24552): at java.lang.reflect.Method.invoke(Method.java:511)
05-22 18:17:41.488: W/System.err(24552): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
05-22 18:17:41.492: W/System.err(24552): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
05-22 18:17:41.492: W/System.err(24552): at dalvik.system.NativeStart.main(Native Method)
While looking for android.os.NetworkOnMainThreadExceptionI found the documentation which states that this is: The exception that is thrown when an application attempts to perform a networking operation on its main thread.
From that I conclude that I should put my call into an AsyncTask.
Can anyone please confirm that I understand this correctly - or am I missing something here? Strange that I hat to catch (Throwable e) in order to get to the bottom of this.
FURTHER INVESTIGATION (05.22.2012):
I can now confirm that this issue comes due to the fact that The exception... is thrown when an application attempts to perform a networking operation on its main thread. As I read this started with honeycomb.
Ths issue now: I get a 301 response from Yahoo (Moved Permanently). This is strange because when I cut paste the URL into the browser it works.
Any idea why this should work in the browser but not in the application? I must mention that this HTTP request receives a CSV file as a response. Could this be an issue?
FURTHER INVESTIGATION (05.23.2012):
For some reason when using (in my code) the Yahoo URI http://finance.yahoo.com/d/quotes.csv?s= the response is a 301 (Moved Permanently). When using http://download.finance.yahoo.com/d/quotes.csv?s= instead the response is 200 (OK). Even that both work fine in the browser. I was lucky enough to find this web page that gave me some clues regarding which URIs Yahoo reacts to. Now I can see the "reader" gets the data and everything is ALMOST fine. I still get some strange exception (still trying to figure it out): after reading all the lines in the response I catch a Throwable (I left it from my previous experiments) and later on in the stack I thus get 05-23 08:52:41.258: W/dalvikvm(933): threadid=11: thread exiting with uncaught exception (group=0x40a721f8) and something about an uncaught exception in doInBackground(Void... params). Still investigating...
Just solved this issue - it was just a mistake in calling the Yahoo API. Had to add &e=.csv to the end of the URI for it to work. Just like that: http://download.finance.yahoo.com/d/quotes.csv?s=KDHIX&f=sl1d1t1c1ohgv&e=.csv
FINAL CODE
private ArrayList<String> retrieveStockFinParamsFromYahooApiUri(String yahooApiCall)
{
ArrayList<String> stockFinParamsFromYahooApiUriRows = new ArrayList<String>();
String resultLine = "";
BufferedReader reader = null;
AndroidHttpClient httpClient = AndroidHttpClient.newInstance("yahooGetStockParams");
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet(yahooApiCall);
try
{
HttpResponse response = httpClient.execute(httpGet, localContext);
reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
while ((resultLine = reader.readLine()) != null)
{
stockFinParamsFromYahooApiUriRows.add(resultLine);
}
if(response != null)
{
try
{
response.getEntity().consumeContent();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if(httpClient != null)
{
httpClient.close();
}
if (reader != null)
{
try
{
reader.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
return stockFinParamsFromYahooApiUriRows;
}
Chances are that you get an Exception in execute that is not an IOException. Then, your catch block never get executed and your finally block is executed before the method throws an exepected exception to the caller of retrieveStockFinParamsFromYahooApiUri.
You have at least 2 options :
don't catch an IOException but a prent class. Try Throwable, print the stack trace and see what happens. Then you can later add other catch blocks to handle the case. (Catching Throwables is a bad programming practice, but you can use temporarily).
place the invocation of retrieveStockFinParamsFromYahooApiUri in a try catch block using the same mechanism as above to determine which exception classes to expect and act accordingly.
But you need to refine your understanding of the problem, catch everything possible, write the stack trace and check the logcat.
Here are some other advices :
You need to check the result code of the request before reading its content.
You could use Apache IOUtils to copy the content of the response input stream and cache it to a file.
You could enable gzipping of the request and the response.
You also need to close properly the HttpConnection in the finally block, you can consume the entity of the response to achieve this.

Android Unit Tests

I am trying to write a AndroidTestCase for one of my classes that make connection to a server and parse the returned JSONObject. When I test the functionality in the UI, the file works fine and the correct information are parsed and displayed. When I input the URL into my browser, I get the correct JSONObject back. However, when I try to get the JSONObject through a AndroidTestCase and simply verifying that it's not null, I get IOException when it tries to get the corresponding JSONObject for an url. I verified that the url it's using is correct. Here's the stack trace.
java.net.UnknownHostException: api.penncoursereview.com
at java.net.InetAddress.lookupHostByName(InetAddress.java:506)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:294)
at java.net.InetAddress.getAllByName(InetAddress.java:256)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:69)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:48)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection$Address.connect(HttpConnection.java:322)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnectionPool.get(HttpConnectionPool.java:89)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getHttpConnection(HttpURLConnectionImpl.java:285)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.makeConnection(HttpURLConnectionImpl.java:267)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.retrieveResponse(HttpURLConnectionImpl.java:1018)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:512)
at edu.upenn.cis.cis350.backend.Parser.retrieveJSONObject(Parser.java:34)
at edu.upenn.cis.cis350.test.ParserTest.test_retrieveJSONObject(ParserTest.java:22)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at junit.framework.TestCase.runTest(TestCase.java:154)
at junit.framework.TestCase.runBare(TestCase.java:127)
at junit.framework.TestResult$1.protect(TestResult.java:106)
at junit.framework.TestResult.runProtected(TestResult.java:124)
at junit.framework.TestResult.run(TestResult.java:109)
at junit.framework.TestCase.run(TestCase.java:118)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:529)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1448)
Any idea why the code works in simulator but not in test?
Thanks in advance for the help!
edit:
Here is the relevant method:
public JSONObject retrieveJSONObject(String path){
try{
URL url = new URL(path);
Log.w("Parser: retrieveJSONObject", "url=" + url);
URLConnection connection = url.openConnection();
String line;
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = reader.readLine()) != null) {
builder.append(line);
}
Log.v("Length",builder.toString());
return new JSONObject(builder.toString());
}
catch(IOException e) {
Log.w("Parser: retrieveJSONObject", "IOException: Bad Url");
e.printStackTrace();
return null;
} catch (JSONException e) {
Log.w("Parser: retrieveJSONObject", "JSONException: mis-formatted JSON");
e.printStackTrace();
return null;
}
}
Line 34 is the line initializing the BufferedReader.
I guess what you are missing is the INTERNET permission.
Considering that your method is defined static in Utils class, the following test works.
public void testRetrieveJSONObjectWithUrl() {
final String url = "http://www.bom.gov.au/fwo/IDV60901/IDV60901.94868.json";
assertNotNull(Utils.retrieveJSONObject(url));
}

NullPointerException with StringBuilder

I get a very common crash below from the code below.
I thought my try, catches will have handled that.
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:200)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
at java.lang.Thread.run(Thread.java:1102)
Caused by: java.lang.NullPointerException
at java.io.Reader.<init>(Reader.java:65)
at java.io.InputStreamReader.<init>(InputStreamReader.java:65)
at com.test.test.FinderMain.grabPlaneRoute(FinderMain.java:759)
at com.test.test.FinderMain.access$7(FinderMain.java:729)
at com.test.test.FinderMain$GetRouteTask.doInBackground(FinderMain.java:684)
at com.test.test.FinderMain$GetRouteTask.doInBackground(FinderMain.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:185)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
Line 759 is within grabPlaneRoute and is the line containing the "StringBuilder total = new StringBuilder();"
Can someone help with this, it is driving me crazy! :-)
private void grabPlaneRoute(String adshex) {
List<GeoPoint> localList = new ArrayList<GeoPoint>();
HttpURLConnection con = null;
URL url;
InputStream is=null;
try {
url = new URL("http://www.testurl.com&test=" + adshex);
con = (HttpURLConnection) url.openConnection();
con.setReadTimeout(20000 /* milliseconds */);
con.setConnectTimeout(60000 /* milliseconds */);
con.setRequestMethod("GET");
con.setDoInput(true);
// Start the query
con.connect();
is = con.getInputStream();
}catch (IOException e) {
//handle the exception !
e.printStackTrace();
return;
}
//localList = decodePoly(convertStreamToString(is));
//Log.i("HTTP DUMP", convertStreamToString(is));
BufferedReader r = new BufferedReader(new InputStreamReader(is),8024);
StringBuilder total = new StringBuilder();
String line;
try {
while ((line = r.readLine()) != null) {
String[] separated = line.split(",");
GeoPoint p = getPoint(Double.valueOf(separated[0]),Double.valueOf(separated[1]));
localList.add(p);
}
}catch (IOException e) {
//handle the exception !
e.printStackTrace();
}
drawPlaneRoute(localList);
}
Line 759 is actually the line that begins with BufferedReader r = new ....
The variable is is null.
What happens when con.GetInputStream returns a null, and doesn't throw an exception? You're not handling that case, and that's likely what's happening here.
In addition, I don't see a need for the either try/catch block at all. Just let the exception percolate up the call stack. You're hiding the IOException now, preventing anyone calling grabPlaneRoute from discovering that an error occurred.
It's fairly impossible for StringBuilder total = new StringBuilder(); to cause a NullPointerException. On the other hand, the nearest cause of the Exception is in the logtrace:
at java.io.Reader.<init>(Reader.java:65)
at java.io.InputStreamReader.<init>(InputStreamReader.java:65)
Which makes me think that it's caused by:
BufferedReader r = new BufferedReader(new InputStreamReader(is),8024);
In that case, the only thing that could be null is is.

Categories

Resources