android http conection using json keeps crashing app - java

hey guys i keep getting this error in my app when i try to get data from a server and read it as json and i am stuck because it doesnt happen all the time hear is the code
private class statusUpdateTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... urls) {
if(testServe("http://www.gogodis.comxa.com/getData.php")) {
HttpURLConnection conn = null;
BufferedReader reader = null;
try {
URL url = new URL(urls[0]);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
reader = new BufferedReader(new InputStreamReader(is));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line);
}
return sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}else{
retry(0);
}
return null;
}
#Override
protected void onPostExecute(String result) {
if(isJSONValid(result)) {
try {
JSONObject results = new JSONObject(result);
JSONArray jr = results.getJSONArray("results");
JSONObject set = jr.getJSONObject(0);
JSONObject info = set.getJSONArray("info").getJSONObject(0);
if (info.getString("state").equals("ok")) {
if (info.getInt("inbox") == 1) {
inbox.setImageResource(R.drawable.camr);
} else inbox.setImageResource(R.drawable.cam);
if (info.getInt("chat") == 1) {
chat.setImageResource(R.drawable.msgr);
} else chat.setImageResource(R.drawable.msg);
if(info.getInt("match") == 1){
new newMatchUpdateTask().execute("http://www.gogodis.comxa.com/getData.php?type=new_match&&user=" + my_user_id);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}else{
retry(0);
}
}
}
and hear is the logcast
05-30 15:05:11.205 5071-5394/com.reallyChat W/System.err: java.net.SocketTimeoutException
05-30 15:05:11.676 5071-5394/com.reallyChat W/System.err: at java.net.PlainSocketImpl.read(PlainSocketImpl.java:491)
05-30 15:05:11.676 5071-5394/com.reallyChat W/System.err: at java.net.PlainSocketImpl.access$000(PlainSocketImpl.java:46)
05-30 15:05:11.686 5071-5394/com.reallyChat W/System.err: at java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:240)
05-30 15:05:11.686 5071-5394/com.reallyChat W/System.err: at java.io.InputStream.read(InputStream.java:163)
05-30 15:05:11.686 5071-5394/com.reallyChat W/System.err: at java.io.BufferedInputStream.fillbuf(BufferedInputStream.java:142)
05-30 15:05:11.686 5071-5394/com.reallyChat W/System.err: at java.io.BufferedInputStream.read(BufferedInputStream.java:227)
05-30 15:05:11.686 5071-5394/com.reallyChat W/System.err: at libcore.io.Streams.readAsciiLine(Streams.java:201)
05-30 15:05:11.686 5071-5394/com.reallyChat W/System.err: at libcore.net.http.HttpEngine.readResponseHeaders(HttpEngine.java:573)
05-30 15:05:11.686 5071-5394/com.reallyChat W/System.err: at libcore.net.http.HttpEngine.readResponse(HttpEngine.java:821)
05-30 15:05:11.686 5071-5394/com.reallyChat W/System.err: at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:283)
05-30 15:05:11.686 5071-5394/com.reallyChat W/System.err: at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:177)
05-30 15:05:11.686 5071-5394/com.reallyChat W/System.err: at com.really_chat.results$statusUpdateTask.doInBackground(results.java:968)
05-30 15:05:11.686 5071-5394/com.reallyChat W/System.err: at com.really_chat.results$statusUpdateTask.doInBackground(results.java:953)
05-30 15:05:11.686 5071-5394/com.reallyChat W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:287)
05-30 15:05:11.686 5071-5394/com.reallyChat W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:234)
05-30 15:05:11.686 5071-5394/com.reallyChat W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
05-30 15:05:11.686 5071-5394/com.reallyChat W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
05-30 15:05:11.686 5071-5394/com.reallyChat W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
05-30 15:05:11.686 5071-5394/com.reallyChat W/System.err: at java.lang.Thread.run(Thread.java:856)
05-30 15:05:11.696 5071-5071/com.reallyChat D/AndroidRuntime: Shutting down VM
05-30 15:05:11.706 5071-5071/com.reallyChat W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x411cd930)
05-30 15:05:11.726 5071-5071/com.reallyChat E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
at org.json.JSONTokener.nextValue(JSONTokener.java:94)
at org.json.JSONObject.<init>(JSONObject.java:154)
at org.json.JSONObject.<init>(JSONObject.java:171)
at com.really_chat.results.isJSONValid(results.java:1158)
at com.really_chat.results$statusUpdateTask.onPostExecute(results.java:989)
at com.really_chat.results$statusUpdateTask.onPostExecute(results.java:953)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5283)
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:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
iv'e even tried to put in code that confirms its json but still no luck
public boolean isJSONValid(String test) {
try{
new JSONObject(test);
}catch(JSONException ex){
try{
new JSONArray(test);
}catch(JSONException ex1){
return false;
}
}
return true;
}
private boolean testServe(String url) {
try{
URL myUrl = new URL(url);
URLConnection connection = myUrl.openConnection();
connection.setConnectTimeout(15000);
connection.connect();
return true;
} catch (Exception e) {
// Handle your exceptions
return false;
}
}

Try to change like this
conn.setReadTimeout(0 /* milliseconds */);//Infinite timeout
conn.setConnectTimeout(25000 /* milliseconds */);

Related

File Writer Android

I am using the following code to write an onPostExecute process to file from my FileWriter.class, it was working fine but am updating my application and I have to use the Environment.getExternalStorageDirectory().getPath(); instead of this, i tried following. I know doing something slightly wrong. Any Help or direction would be helpful.
Thanks.
public class FileWriter {
public void appendData( String text) {
try {
File myFile = new File("/sdcard/latencyOP.csv");
// myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
if (myFile.createNewFile()) {
myOutWriter.append("TimeStamp,ExecutionTime,OperationType;");
}
myOutWriter.append(text);
myOutWriter.close();
fOut.close();
/**
* Toast.makeText(getBaseContext(),
* "Done writing SD 'mysdfile.txt'",
Toast.LENGTH_SHORT).show();
*/
} catch (Exception e) {
/**
* Toast.makeText(getBaseContext(), e.getMessage(),
* Toast.LENGTH_SHORT).show();
*/
}
}
}
EDIT
I forgot to add that I am attempting to do some background operations and publish results on the **FILE.csv** thread without having to manipulate threads.
UPDATED CODE #Leonardo Acevedo
try {
File myFile = new File(
Environment.getExternalStorageDirectory(),
"latencyOP.csv"
);
boolean needToCreateFile = !myFile.exists();
if (needToCreateFile) {
myFile.createNewFile();
}
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
// At this point your file is guaranteed to exist
if (needToCreateFile) {
myOutWriter.append("TimeStamp,ExecutionTime,OperationType;");
}
myOutWriter.append(text);
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Done writing SD 'mysdfile.txt'",
Toast.LENGTH_SHORT
).show();
} catch (Exception e) {
e.printStackTrace();
displayExceptionMessage(e.getMessage());
//Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
public void displayExceptionMessage(String msg) {
//Toast.makeText(this, "Some Error Occured", Toast.LENGTH_SHORT).show();
}
ASYNCH TASK PROCESS
protected void onPreExecute(){ startTime = Calendar.getInstance().getTime().getTime();
}
protected void onPostExecute(Long result) {
endTime = Calendar.getInstance().getTime().getTime();
long timeDiff = endTime - startTime;
FileWriter fileWriter = new FileWriter();
String data = endTime + "," + timeDiff + "," + "Authentication" + ";";
fileWriter.appendData(data);
}
Is this wrong ?
03-14 20:42:52.062 17192-17192/com.demo.common.recordwritertest W/System.err: java.io.IOException: Permission denied
03-14 20:42:52.063 17192-17192/com.demo.common.recordwritertest W/System.err: at java.io.UnixFileSystem.createFileExclusively0(Native Method)
03-14 20:42:52.063 17192-17192/com.demo.common.recordwritertest W/System.err: at java.io.UnixFileSystem.createFileExclusively(UnixFileSystem.java:280)
03-14 20:42:52.063 17192-17192/com.demo.common.recordwritertest W/System.err: at java.io.File.createNewFile(File.java:948)
03-14 20:42:52.063 17192-17192/com.demo.common.recordwritertest W/System.err: at com.demo.common.recordwritertest.utils.FileWriter.appendData(FileWriter.java:25)
03-14 20:42:52.063 17192-17192/com.demo.common.recordwritertest W/System.err: at com.demo.common.recordwritertest.com.demo.common.recordwritertest.asynctasks.AuthenticationAsyncTask.onPostExecute(AuthenticationAsyncTask.java:119)
03-14 20:42:52.063 17192-17192/com.demo.common.recordwritertest W/System.err: at com.demo.common.recordwritertest.com.demo.common.recordwritertest.asynctasks.AuthenticationAsyncTask.onPostExecute(AuthenticationAsyncTask.java:27)
03-14 20:42:52.063 17192-17192/com.demo.common.recordwritertest W/System.err: at android.os.AsyncTask.finish(AsyncTask.java:667)
03-14 20:42:52.063 17192-17192/com.demo.common.recordwritertest W/System.err: at android.os.AsyncTask.-wrap1(AsyncTask.java)
03-14 20:42:52.063 17192-17192/com.demo.common.recordwritertest W/System.err: at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:684)
03-14 20:42:52.063 17192-17192/com.demo.common.recordwritertest W/System.err: at android.os.Handler.dispatchMessage(Handler.java:102)
03-14 20:42:52.063 17192-17192/com.demo.common.recordwritertest W/System.err: at android.os.Looper.loop(Looper.java:154)
03-14 20:42:52.063 17192-17192/com.demo.common.recordwritertest W/System.err: at android.app.ActivityThread.main(ActivityThread.java:6119)
03-14 20:42:52.063 17192-17192/com.demo.common.recordwritertest W/System.err: at java.lang.reflect.Method.invoke(Native Method)
03-14 20:42:52.063 17192-17192/com.demo.common.recordwritertest W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
03-14 20:42:52.063 17192-17192/com.demo.common.recordwritertest W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

Caused by: android.system.ErrnoException: isConnected failed: ECONNREFUSED (Connection refused)

I'm using Android asyntask with Pycharm(python with flask) server and it will return an array. When i tried to connect with server it will show connection refused.
i need the solution why it shows the error like connection refused.
Android code:
public static String ip = "http://192.168.43.221:3000/";
private class BackTask extends AsyncTask<String, String, String> {
private String result = null,name,batch,id,dept,dob,phno,add,credits;
#Override
protected String doInBackground(String... params) {
try {
String data = URLEncoder.encode("device", "UTF-8") + "=" +
URLEncoder.encode(device, "UTF-8") + "&" +
URLEncoder.encode("ID", "UTF-8") + "=" +
URLEncoder.encode(regno1, "UTF-8") + "&" +
URLEncoder.encode("Password", "UTF-8") + "=" +
URLEncoder.encode(password1, "UTF-8");
BufferedReader reader = null;
Log.d("checking", data);
try {
URL url = new URL(ip + "login/");
URLConnection con = url.openConnection();
con.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
writer.write(data);
writer.flush();
//getting response back
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
Toast.makeText(getBaseContext(),reader.readLine(),Toast.LENGTH_LONG).show();
StringBuilder s = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
s.append(line + "\n");
}
result = s.toString();
} catch (Exception e) {
// Toast.makeText(getBaseContext(),"Connection error",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
Toast.makeText(getBaseContext(),"Connection error",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show();
SharedPreferences.Editor e = sp1.edit();
if(!sp1.equals(null))
{
e.putString("uname", regno1);
e.putString("pass", password1);
e.apply();
}
// progress.dismiss();
//notification.setText(result);
if (result != null) {
Toast.makeText(getBaseContext(), result, Toast.LENGTH_SHORT).show();
result = result.trim();
name= setDetails(result);
if (name.equals("success")) {
Intent intent1 = new Intent(LoginActivity.this, HrActivity.class);
//intent.putExtra("json",result);
startActivity(intent);
} else {
errormsg.setText("*Check id / password");
}
}
}
#Override
protected void onPreExecute() {
progress.show();
}
#Override
protected void onProgressUpdate(String... text) {
// progress. For example updating ProgessDialog
}
Logcat:
03-12 13:52:48.194 23394-23527/com.example.dinesh.eis W/System.err: at libcore.io.IoBridge.isConnected(IoBridge.java:267)
03-12 13:52:48.194 23394-23527/com.example.dinesh.eis W/System.err: at libcore.io.IoBridge.connectErrno(IoBridge.java:191)
03-12 13:52:48.194 23394-23527/com.example.dinesh.eis W/System.err: at libcore.io.IoBridge.connect(IoBridge.java:127)
03-12 13:52:48.194 23394-23527/com.example.dinesh.eis W/System.err: at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:188)
03-12 13:52:48.194 23394-23527/com.example.dinesh.eis W/System.err: at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:461)
03-12 13:52:48.194 23394-23527/com.example.dinesh.eis W/System.err: at java.net.Socket.connect(Socket.java:918)
03-12 13:52:48.195 23394-23527/com.example.dinesh.eis W/System.err: at com.android.okhttp.internal.Platform.connectSocket(Platform.java:174)
03-12 13:52:48.195 23394-23527/com.example.dinesh.eis W/System.err: at com.android.okhttp.Connection.connect(Connection.java:152)
03-12 13:52:48.195 23394-23527/com.example.dinesh.eis W/System.err: at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:282)
03-12 13:52:48.195 23394-23527/com.example.dinesh.eis W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:216)
03-12 13:52:48.195 23394-23527/com.example.dinesh.eis W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:391)
03-12 13:52:48.195 23394-23527/com.example.dinesh.eis W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:106)
03-12 13:52:48.195 23394-23527/com.example.dinesh.eis W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:217)
03-12 13:52:48.195 23394-23527/com.example.dinesh.eis W/System.err: at com.example.dinesh.eis.LoginActivity$BackTask.doInBackground(LoginActivity.java:121)
03-12 13:52:48.195 23394-23527/com.example.dinesh.eis W/System.err: at com.example.dinesh.eis.LoginActivity$BackTask.doInBackground(LoginActivity.java:101)
03-12 13:52:48.195 23394-23527/com.example.dinesh.eis W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:292)
03-12 13:52:48.195 23394-23527/com.example.dinesh.eis W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
03-12 13:52:48.195 23394-23527/com.example.dinesh.eis W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
03-12 13:52:48.195 23394-23527/com.example.dinesh.eis W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
03-12 13:52:48.195 23394-23527/com.example.dinesh.eis W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
03-12 13:52:48.197 23394-23527/com.example.dinesh.eis W/System.err: at java.lang.Thread.run(Thread.java:818)
03-12 13:52:48.197 23394-23527/com.example.dinesh.eis W/System.err: Caused by: android.system.ErrnoException: isConnected failed: ECONNREFUSED (Connection refused)
03-12 13:52:48.198 23394-23527/com.example.dinesh.eis W/System.err: at libcore.io.IoBridge.isConnected(IoBridge.java:252)
03-12 13:52:48.198 23394-23527/com.example.dinesh.eis W/System.err: ... 20 more
ECONNREFUSED is to mean a connection is attempted to a remote server,However the remote host is not answering back. This is much like knocking into someone's door and no one is replying back. There is no direct answer for your scnerio as many things can cause this along the way. Please have a look in this and this threads. They might give you some insight into the core issue, and from that you can start analyzing and debugging your code.

Error being thrown when load a map from a KML

I am loading a map in my app from kml files (with a different kml file on each day of the week being loaded). It was working until just recently and I'm really confused as to why I am getting this error as I haven't touched this part of my code since I got it working basically and now I am getting a XmlPullParserException: expected: /META read: HEAD (position:END_TAG #1:355 in java.io.InputStreamReader#426ba9d0)
Here is my code:
// set kml layers
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
InputStream inputStream = null;
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
int value = preferences.getInt("DateStarted", 1);
Log.d(TAG, String.valueOf(value));
System.out.println("In Maps start day is " + String.valueOf(value));
try {
// get different maps on different days of the week
switch(value) {
case Calendar.MONDAY:
inputStream = new URL("http://www.inf.ed.ac.uk/teaching/courses/selp/coursework/monday.kml").openStream();
break;
case Calendar.TUESDAY:
inputStream = new URL("http://www.inf.ed.ac.uk/teaching/courses/selp/coursework/tuesday.kml").openStream();
break;
case Calendar.WEDNESDAY:
inputStream = new URL("http://www.inf.ed.ac.uk/teaching/courses/selp/coursework/wednesday.kml").openStream();
break;
case Calendar.THURSDAY:
inputStream = new URL("http://www.inf.ed.ac.uk/teaching/courses/selp/coursework/thursday.kml").openStream();
break;
case Calendar.FRIDAY:
inputStream = new URL("http://www.inf.ed.ac.uk/teaching/courses/selp/coursework/thursday.kml").openStream();
break;
case Calendar.SATURDAY:
inputStream = new URL("http://www.inf.ed.ac.uk/teaching/courses/selp/coursework/saturday.kml").openStream();
break;
case Calendar.SUNDAY:
inputStream = new URL("http://www.inf.ed.ac.uk/teaching/courses/selp/coursework/sunday.kml").openStream();
break;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
try {
layer = new KmlLayer(mMap, inputStream, getApplicationContext());
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
layer.addLayerToMap();
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
and the full error message that I'm getting is :
> W/System.err: org.xmlpull.v1.XmlPullParserException: expected: /META read: HEAD (position:END_TAG </HEAD>#1:355 in java.io.InputStreamReader#426ba9d0)
W/System.err: at org.kxml2.io.KXmlParser.readEndTag(KXmlParser.java:970)
W/System.err: at org.kxml2.io.KXmlParser.next(KXmlParser.java:372)
W/System.err: at org.kxml2.io.KXmlParser.next(KXmlParser.java:310)
W/System.err: at com.google.maps.android.kml.KmlParser.parseKml(KmlParser.java:90)
W/System.err: at com.google.maps.android.kml.KmlLayer.<init>(KmlLayer.java:49)
W/System.err: at com.example.veronika.grabble.MapsActivity.onMapReady(MapsActivity.java:169)
W/System.err: at com.google.android.gms.maps.SupportMapFragment$zza$1.zza(Unknown Source)
W/System.err: at com.google.android.gms.maps.internal.zzt$zza.onTransact(Unknown Source)
W/System.err: at android.os.Binder.transact(Binder.java:347)
W/System.err: at aai.a(:com.google.android.gms.DynamiteModulesB:82)
W/System.err: at maps.ad.t$5.run(Unknown Source)
W/System.err: at android.os.Handler.handleCallback(Handler.java:730)
W/System.err: at android.os.Handler.dispatchMessage(Handler.java:92)
W/System.err: at android.os.Looper.loop(Looper.java:213)
W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5225)
W/System.err: at java.lang.reflect.Method.invokeNative(Native Method)
W/System.err: at java.lang.reflect.Method.invoke(Method.java:525)
W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:741)
W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
W/System.err: at dalvik.system.NativeStart.main(Native Method)
D/AndroidRuntime: Shutting down VM
W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x420218b0)
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.veronika.grabble.MapsActivity.onMapReady(MapsActivity.java:176)
at com.google.android.gms.maps.SupportMapFragment$zza$1.zza(Unknown Source)
at com.google.android.gms.maps.internal.zzt$zza.onTransact(Unknown Source)
at android.os.Binder.transact(Binder.java:347)
at aai.a(:com.google.android.gms.DynamiteModulesB:82)
at maps.ad.t$5.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:5225)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:741)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
at dalvik.system.NativeStart.main(Native Method)
Does anyone have an idea of how I should go about fixing this? Because I don't understand where does the null pointer exception comes from...
PS: the log.d shows that value has a value in one of the cases, and so that should put a different inputStream than null ....

RXJava Android - Network exception when trying to pull RSS feed

I currently am trying to pull down an RSS Feed as an XML file and I'm trying to use RXJava instead of an AsyncTask to parse and download the file.
I'm getting a network on the main thread error though while I'm trying to pull the feed down.
Here is the relevant code with observable which is in the main activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.rv_test_items);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
final ArrayList<TestItem> testItems = new ArrayList<>();
//testItems.add(new TestItem("Title here", "Content here"));
RssReader reader = new RssReader("http://www.feedforall.com/sample.xml");
// Subscribe on a new background thread, while returning the result on the UI thread.
// Using the RSS Classes we will pull the rss items from the rss feed and then create our
// own TestItem from them.
try {
Observable
.from(reader.getItems())
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<RssItem>() {
#Override
public void call(RssItem item) {
TestItem newItem = new TestItem(item.getTitle(), item.getDescription());
testItems.add(newItem);
}
});
} catch (Exception e) {
e.printStackTrace();
Log.e("App", "Failed to download RSS Items");
}
TestItemAdapter testItemAdapter = new TestItemAdapter(testItems);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(testItemAdapter);
And here is my RSSReader class
public class RssReader {
private String rssUrl;
public RssReader(String url) {
rssUrl = url;
}
public List<RssItem> getItems() throws Exception {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
//Creates a new RssHandler which will do all the parsing.
RssHandler handler = new RssHandler();
//Pass SaxParser the RssHandler that was created.
saxParser.parse(rssUrl, handler);
return handler.getRssItemList();
}
}
And my RSSHandler class
public class RssHandler extends DefaultHandler {
private List<RssItem> rssItemList;
private RssItem currentItem;
private boolean parsingTitle;
private boolean parsingLink;
private boolean parsingDescription;
public RssHandler() {
//Initializes a new ArrayList that will hold all the generated RSS items.
rssItemList = new ArrayList<RssItem>();
}
public List<RssItem> getRssItemList() {
return rssItemList;
}
//Called when an opening tag is reached, such as <item> or <title>
#Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (qName.equals("item"))
currentItem = new RssItem();
else if (qName.equals("title"))
parsingTitle = true;
else if (qName.equals("link"))
parsingLink = true;
else if (qName.equals("description"))
parsingDescription = true;
else if (qName.equals("media:thumbnail") || qName.equals("media:content") || qName.equals("image")) {
if (attributes.getValue("url") != null)
currentItem.setImageUrl(attributes.getValue("url"));
}
}
//Called when a closing tag is reached, such as </item> or </title>
#Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (qName.equals("item")) {
//End of an item so add the currentItem to the list of items.
rssItemList.add(currentItem);
currentItem = null;
} else if (qName.equals("title"))
parsingTitle = false;
else if (qName.equals("link"))
parsingLink = false;
else if (qName.equals("description"))
parsingDescription = false;
}
//Goes through character by character when parsing whats inside of a tag.
#Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (currentItem != null) {
//If parsingTitle is true, then that means we are inside a <title> tag so the text is the title of an item.
if (parsingTitle)
currentItem.setTitle(new String(ch, start, length));
//If parsingLink is true, then that means we are inside a <link> tag so the text is the link of an item.
else if (parsingLink)
currentItem.setLink(new String(ch, start, length));
//If parsingDescription is true, then that means we are inside a <description> tag so the text is the description of an item.
else if (parsingDescription)
currentItem.setDescription(new String(ch, start, length));
}
}
}
Stack trace
10-07 11:39:15.040 1959-1959/? I/art: Late-enabling -Xcheck:jni
10-07 11:39:15.208 1959-1959/? W/System.err: java.io.IOException: Couldn't open http://www.feedforall.com/sample.xml
10-07 11:39:15.208 1959-1959/? W/System.err: at org.apache.harmony.xml.ExpatParser.openUrl(ExpatParser.java:755)
10-07 11:39:15.208 1959-1959/? W/System.err: at org.apache.harmony.xml.ExpatReader.parse(ExpatReader.java:292)
10-07 11:39:15.208 1959-1959/? W/System.err: at javax.xml.parsers.SAXParser.parse(SAXParser.java:390)
10-07 11:39:15.208 1959-1959/? W/System.err: at javax.xml.parsers.SAXParser.parse(SAXParser.java:266)
10-07 11:39:15.208 1959-1959/? W/System.err: at com.polymorphicinc.retrofitsample.rss.RssReader.getItems(RssReader.java:36)
10-07 11:39:15.208 1959-1959/? W/System.err: at com.polymorphicinc.retrofitsample.ui.MainActivity.onCreate(MainActivity.java:47)
10-07 11:39:15.208 1959-1959/? W/System.err: at android.app.Activity.performCreate(Activity.java:5990)
10-07 11:39:15.208 1959-1959/? W/System.err: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
10-07 11:39:15.208 1959-1959/? W/System.err: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
10-07 11:39:15.208 1959-1959/? W/System.err: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
10-07 11:39:15.208 1959-1959/? W/System.err: at android.app.ActivityThread.access$800(ActivityThread.java:151)
10-07 11:39:15.208 1959-1959/? W/System.err: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
10-07 11:39:15.208 1959-1959/? W/System.err: at android.os.Handler.dispatchMessage(Handler.java:102)
10-07 11:39:15.208 1959-1959/? W/System.err: at android.os.Looper.loop(Looper.java:135)
10-07 11:39:15.208 1959-1959/? W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5254)
10-07 11:39:15.208 1959-1959/? W/System.err: at java.lang.reflect.Method.invoke(Native Method)
10-07 11:39:15.209 1959-1959/? W/System.err: at java.lang.reflect.Method.invoke(Method.java:372)
10-07 11:39:15.209 1959-1959/? W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
10-07 11:39:15.209 1959-1959/? W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
10-07 11:39:15.209 1959-1959/? W/System.err: Caused by: android.os.NetworkOnMainThreadException
10-07 11:39:15.209 1959-1959/? W/System.err: at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
10-07 11:39:15.209 1959-1959/? W/System.err: at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
10-07 11:39:15.209 1959-1959/? W/System.err: at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
10-07 11:39:15.209 1959-1959/? W/System.err: at java.net.InetAddress.getAllByName(InetAddress.java:215)
10-07 11:39:15.209 1959-1959/? W/System.err: at com.android.okhttp.HostResolver$1.getAllByName(HostResolver.java:29)
10-07 11:39:15.209 1959-1959/? W/System.err: at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:232)
10-07 11:39:15.209 1959-1959/? W/System.err: at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:124)
10-07 11:39:15.209 1959-1959/? W/System.err: at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:272)
10-07 11:39:15.209 1959-1959/? W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
10-07 11:39:15.209 1959-1959/? W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:382)
10-07 11:39:15.209 1959-1959/? W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:332)
10-07 11:39:15.209 1959-1959/? W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:199)
10-07 11:39:15.209 1959-1959/? W/System.err: at org.apache.harmony.xml.ExpatParser.openUrl(ExpatParser.java:753)
10-07 11:39:15.209 1959-1959/? W/System.err: ... 18 more
10-07 11:39:15.209 1959-1959/? E/App: Failed to download RSS Items
10-07 11:39:15.215 1959-1978/? D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
10-07 11:39:15.216 1959-1959/? D/: HostConnection::get() New Host Connection established 0xb42d9a00, tid 1959
10-07 11:39:15.219 1959-1959/? D/Atlas: Validating map...
10-07 11:39:15.281 1959-1978/? D/libEGL: loaded /system/lib/egl/libEGL_emulation.so
10-07 11:39:15.282 1959-1978/? D/libEGL: loaded /system/lib/egl/libGLESv1_CM_emulation.so
10-07 11:39:15.286 1959-1978/? D/libEGL: loaded /system/lib/egl/libGLESv2_emulation.so
10-07 11:39:15.295 1959-1978/? D/: HostConnection::get() New Host Connection established 0xb42d9b90, tid 1978
10-07 11:39:15.311 1959-1978/? I/OpenGLRenderer: Initialized EGL, version 1.4
10-07 11:39:15.360 1959-1978/? D/OpenGLRenderer: Enabling debug mode 0
10-07 11:39:15.381 1959-1978/? W/EGL_emulation: eglSurfaceAttrib not implemented
10-07 11:39:15.381 1959-1978/? W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xb424bb40, error=EGL_SUCCESS
Take a look at this to get an idea how to do it:
public class RssReader {
private String rssUrl;
public RssReader(String url) {
rssUrl = url;
}
public Observable<List<RssItem>> getItems() {
return Observable.create(new Observable.OnSubscribe<List<RssItem>>() {
#Override
public void call(Subscriber<? super List<RssItem>> subscriber) {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
//Creates a new RssHandler which will do all the parsing.
RssHandler handler = new RssHandler();
//Pass SaxParser the RssHandler that was created.
saxParser.parse(rssUrl, handler);
subscriber.onNext(handler.getRssItemList());
subscriber.onCompleted();
} catch (Exception e) {
subscriber.onError(e);
}
}
});
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.rv_test_items);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
RssReader reader = new RssReader("http://www.feedforall.com/sample.xml");
reader.getItems()
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<List<RssItem>>() {
#Override
public void call(List<RssItem> items) {
final ArrayList<TestItem> testItems = new ArrayList<>(items.size());
for (int size = items.size(), i = 0; i < size; i++) {
RssItem item = items.get(i);
testItems.add(new TestItem(item.getTitle(), item.getDescription()));
}
recyclerView.setAdapter(new TestItemAdapter(testItems));
}
}, new Action1<Throwable>() {
#Override
public void call(Throwable e) {
e.printStackTrace();
Log.e("App", "Failed to download RSS Items");
}
});
}
try this
Observable.defer(() -> Observable.from(reader.getItems())
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<RssItem>() {
#Override
public void call(RssItem item) {
TestItem newItem = new TestItem(item.getTitle(), item.getDescription());
testItems.add(newItem);
}
});

Android VerifyError crash using jackson parser

Here is my log cat. Unfortunately I am not a pro in reading errors from logcat so please help me :)
05-30 12:12:16.510: I/System.out(838): We made it this far 1
05-30 12:12:17.230: I/System.out(838): We made it this far 2
05-30 12:12:17.240: W/dalvikvm(838): VFY: unable to resolve exception class 748 (Lcom/fasterxml/jackson/core/JsonParseException;)
05-30 12:12:17.240: W/dalvikvm(838): VFY: unable to find exception handler at addr 0x2a
05-30 12:12:17.240: W/dalvikvm(838): VFY: rejected Lcom/example/bitmapdisplay/MainActivity$URLArray;.doInBackground ([Ljava/lang/Void;)Ljava/lang/Void;
05-30 12:12:17.240: W/dalvikvm(838): VFY: rejecting opcode 0x0d at 0x002a
05-30 12:12:17.250: W/dalvikvm(838): VFY: rejected Lcom/example/bitmapdisplay/MainActivity$URLArray;.doInBackground ([Ljava/lang/Void;)Ljava/lang/Void;
05-30 12:12:17.250: W/dalvikvm(838): Verifier rejected class Lcom/example/bitmapdisplay/MainActivity$URLArray;
05-30 12:12:17.250: D/AndroidRuntime(838): Shutting down VM
05-30 12:12:17.250: W/dalvikvm(838): threadid=1: thread exiting with uncaught exception (group=0xb1adaba8)
05-30 12:12:17.270: E/AndroidRuntime(838): FATAL EXCEPTION: main
05-30 12:12:17.270: E/AndroidRuntime(838): Process: com.example.bitmapdisplay, PID: 838
05-30 12:12:17.270: E/AndroidRuntime(838): java.lang.VerifyError: com/example/bitmapdisplay/MainActivity$URLArray
05-30 12:12:17.270: E/AndroidRuntime(838): at com.example.bitmapdisplay.MainActivity.onCreate(MainActivity.java:72)
05-30 12:12:17.270: E/AndroidRuntime(838): at android.app.Activity.performCreate(Activity.java:5231)
05-30 12:12:17.270: E/AndroidRuntime(838): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
05-30 12:12:17.270: E/AndroidRuntime(838): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
05-30 12:12:17.270: E/AndroidRuntime(838): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
05-30 12:12:17.270: E/AndroidRuntime(838): at android.app.ActivityThread.access$800(ActivityThread.java:135)
05-30 12:12:17.270: E/AndroidRuntime(838): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
05-30 12:12:17.270: E/AndroidRuntime(838): at android.os.Handler.dispatchMessage(Handler.java:102)
05-30 12:12:17.270: E/AndroidRuntime(838): at android.os.Looper.loop(Looper.java:136)
05-30 12:12:17.270: E/AndroidRuntime(838): at android.app.ActivityThread.main(ActivityThread.java:5017)
05-30 12:12:17.270: E/AndroidRuntime(838): at java.lang.reflect.Method.invokeNative(Native Method)
05-30 12:12:17.270: E/AndroidRuntime(838): at java.lang.reflect.Method.invoke(Method.java:515)
05-30 12:12:17.270: E/AndroidRuntime(838): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
05-30 12:12:17.270: E/AndroidRuntime(838): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
05-30 12:12:17.270: E/AndroidRuntime(838): at dalvik.system.NativeStart.main(Native Method)
05-30 12:12:30.390: I/Process(838): Sending signal. PID: 838 SIG: 9
Here is the logcat code and here is my Java code. It seems like the problems are coming from the thread URLArray because, as seen in the logcat, the system doesn't even print the third "we made it this far":
package com.example.bitmapdisplay;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import com.fasterxml.jackson.core.JsonParseException;
import android.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
public class MainActivity extends Activity {
/**
* Bitmap items na dimage displaying
*/
Bitmap image;
BitmapDrawable bd;
ImageView temp;
ProgressDialog pd;
/**
* JSON URL
*/
URL url;
/**
* Data from JSON file
*/
ArrayList<String> urls;
ArrayList<ImageView> images;
JsonParsing obj;
String json_link_str = "http://api.tumblr.com/v2/blog/humansofnewyork.com/posts?api_key=7ag2CJXOuxuW3vlVS5wQG6pYA6a2ZQcSCjzZsAp2pDbVwf3xEk&notes_info=true&filter=text";
int counter;
#Override
protected void onCreate(Bundle savedInstanceState) {
System.out.println(" We made it this far 1");
super.onCreate(savedInstanceState);
setContentView(com.example.bitmapdisplay.R.layout.image_container);
counter = 0;
images = new ArrayList<ImageView>();
urls = new ArrayList<String>();
System.out.println(" We made it this far 2");
new URLArray().execute();
}
/**
* Fills the ListView
*/
private void fillGridView() {
ArrayAdapter<ImageView> adapter = new ArrayAdapter<ImageView>(this, com.example.bitmapdisplay.R.layout.image_container,images);
GridView grid = (GridView) findViewById(com.example.bitmapdisplay.R.id.gvImages);
grid.setAdapter(adapter);
}
public class URLArray extends AsyncTask<Void, Void, Void > {
public URLArray() {
}
#Override
protected Void doInBackground(Void...params ) {
try {
System.out.println(" We made it this far 3");
URL json_link = new URL(json_link_str);
JsonParsing parse_images = new JsonParsing(json_link);
try {
parse_images.parseFile(3, urls);
System.out.println(" We made it this far 4");
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
obj = parse_images;
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void arg) {
super.onPreExecute();
System.out.println(" We made it this far 5");
urls = obj.getURLs();
new TheTask().execute();
}
}
class TheTask extends AsyncTask<Void,Void,Void>
{
#Override
protected Void doInBackground(Void... params) {
System.out.println(" We made it this far 6");
pd = new ProgressDialog(MainActivity .this);
pd.show();
System.out.println(" We made it this far 7");
try
{
int counter = 0;
for (ImageView temp : images) {
image = downloadBitmap(urls.get(counter));
temp.setImageBitmap(image);
images.add(temp);
counter++;
}
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
System.out.println(" We made it this far 8");
super.onPostExecute(result);
pd.dismiss();
if(image!=null)
{
fillGridView();
}
}
}
private Bitmap downloadBitmap(String url) {
// initilize the default HTTP client object
final DefaultHttpClient client = new DefaultHttpClient();
//forming a HttoGet request
final HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
//check 200 OK for success
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w("ImageDownloader", "Error " + statusCode +
" while retrieving bitmap from " + url);
return null;
}
final HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = null;
try {
// getting contents from the stream
inputStream = entity.getContent();
// decoding stream data back into image Bitmap that android understands
image = BitmapFactory.decodeStream(inputStream);
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
} catch (Exception e) {
// You Could provide a more explicit error message for IOException
getRequest.abort();
Log.e("ImageDownloader", "Something went wrong while" +
" retrieving bitmap from " + url + e.toString());
}
return image;
}
}
The key problem is here
05-30 12:12:17.240: W/dalvikvm(838): VFY: unable to resolve exception class 748 (Lcom/fasterxml/jackson/core/JsonParseException;)
05-30 12:12:17.240: W/dalvikvm(838): VFY: unable to find exception handler at addr 0x2a
05-30 12:12:17.240: W/dalvikvm(838): VFY: rejected Lcom/example/bitmapdisplay/MainActivity$URLArray;.doInBackground ([Ljava/lang/Void;)Ljava/lang/Void;
05-30 12:12:17.240: W/dalvikvm(838): VFY: rejecting opcode 0x0d at 0x002a
05-30 12:12:17.250: W/dalvikvm(838): VFY: rejected Lcom/example/bitmapdisplay/MainActivity$URLArray;.doInBackground ([Ljava/lang/Void;)Ljava/lang/Void;
05-30 12:12:17.250: W/dalvikvm(838): Verifier rejected class Lcom/example/bitmapdisplay/MainActivity$URLArray;
and it all goes downhill from there.
Looks like JsonParseException (and possibly other classes from Jackson) are not being included in your APK. This could happen if they're not being exported by Eclipse.
Instead of adding it as an external library, just place jackson-core-x.x.x.jar in the libs folder of your Android project and it should be enough to ensure this.

Categories

Resources