Google Maps Geocoding API request issue in Android Studio with okHTTP - android

I am trying to get JSON from Google Maps Geocoding API using okHTTP (http://square.github.io/okhttp/) in Android Studio and my program crashes with the following error log:
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:4020)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4015)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at com.squareup.okhttp.Dns$1.lookup(Dns.java:39)
at com.squareup.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:184)
at com.squareup.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:153)
at com.squareup.okhttp.internal.http.RouteSelector.next(RouteSelector.java:95)
at com.squareup.okhttp.internal.http.HttpEngine.createNextConnection(HttpEngine.java:345)
at com.squareup.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:328)
at com.squareup.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:246)
at com.squareup.okhttp.Call.getResponse(Call.java:276)
at com.squareup.okhttp.Call$ApplicationInterceptorChain.proceed(Call.java:234)
at com.squareup.okhttp.Call.getResponseWithInterceptorChain(Call.java:196)
at com.squareup.okhttp.Call.execute(Call.java:79)
...
The last error log's Caused by gives a hint that the issue might be in okHTTP security communication. I did not set it up because I can not figure out whether I need to do it at all and how to do it then. This page might be relevant, but I am not sure: https://github.com/square/okhttp/wiki/HTTPS
Communication with Google Geocoding API happens through https.
Here is the code I am trying to use:
OkHttpClient client = new OkHttpClient();
String strAddress = "Winnetka";
String googleMapsAPIKey = this.getString(R.string.google_maps_api_key);
String url = null;
try {
url = "https://maps.googleapis.com/maps/api/geocode/json" +
"?address=" + URLEncoder.encode(strAddress, "UTF-8") + "&key=" + googleMapsAPIKey;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
Request request = new Request.Builder()
.url(url)
.build();
try {
Response response = client.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
return null;
}
It fails on the line Response response = client.newCall(request).execute();
I logged out the url that I formed and it looks identical to the one that is used in the examples on the API's website (https://developers.google.com/maps/documentation/geocoding/intro):
https://maps.googleapis.com/maps/api/geocode/json?address=Winnetka&key=...
Could anyone, please, help?

Your issue: Caused by: android.os.NetworkOnMainThreadException
You should use OkHttps async method:
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException throwable) {
throwable.printStackTrace();
}
#Override
public void onResponse(Response response) throws IOException {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
}
// Do Stuff
});

Related

SOAP call from Android with KSoap2 to .net WebServer

Good day everyone.
I'm trying to do a SOAP call to a .net WebServer running locally, but I think I'm missing something. The Android code seems fine to me. Maybe the SOAP request is wrong...
This is what the webserver gives for the method I'm trying to call:
POST /WebAvanza/WebAvanzaInterface.asmx HTTP/1.1
Host: localhost
Content-Type: application/soap+xml; charset=utf-8
Content-Length: length
<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
<soap12:Body>
<InitTransazione xmlns="http://tempuri.org/">
<ip>string</ip>
<codice>string</codice>
</InitTransazione>
</soap12:Body>
</soap12:Envelope>
and this is what i wrote so far:
private String InitTransaction(String command){
String NAMESPACE = "http://tempuri.org/";
String METHOD_NAME = "InitTransazione";
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("ip", ipAddress);
request.addProperty("codice", command);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE httpTransport = new HttpTransportSE(URL);
httpTransport.debug = true;
String SOAP_ACTION = NAMESPACE + METHOD_NAME;
Object result = null;
try {
httpTransport.call(SOAP_ACTION, envelope);
result = envelope.getResponse();
}
catch(Exception e)
{
e.printStackTrace();
}
return String.valueOf(result);
}
URL is http://192.168.168.24/WebAvanza/WebAvanzaInterface.asmx, the address refers to the machine where the server is running.
I only get an exception after executing httpTransport.call.
This is the StackTrace (if anybosy needs it)
W/System.err: android.os.NetworkOnMainThreadException
W/System.err: at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1528)
W/System.err: at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:389)
W/System.err: at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:230)
W/System.err: at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:212)
W/System.err: at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:436)
W/System.err: at java.net.Socket.connect(Socket.java:621)
W/System.err: at com.android.okhttp.internal.Platform.connectSocket(Platform.java:145)
W/System.err: at com.android.okhttp.internal.io.RealConnection.connectSocket(RealConnection.java:141)
W/System.err: at com.android.okhttp.internal.io.RealConnection.connect(RealConnection.java:112)
W/System.err: at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:184)
W/System.err: at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:126)
W/System.err: at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:95)
W/System.err: at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:281)
W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:224)
W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:461)
W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:127)
W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:258)
W/System.err: at org.ksoap2.transport.ServiceConnectionSE.openOutputStream(ServiceConnectionSE.java:130)
W/System.err: at org.ksoap2.transport.HttpTransportSE.sendData(HttpTransportSE.java:295)
W/System.err: at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:184)
W/System.err: at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:118)
W/System.err: at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:113)
W/System.err: at com.infovision.elcam_02.Operations$override.InitTransaction(Operations.java:64)
W/System.err: at com.infovision.elcam_02.Operations$override.InitOperation(Operations.java:40)
W/System.err: at com.infovision.elcam_02.Operations$override.access$dispatch(Unknown Source:49)
W/System.err: at com.infovision.elcam_02.Operations.InitOperation(Unknown Source:15)
I found out that the problem was in the server and the code was fine...
Goddamn I spent almost 5 hours behind this .__.
Checking your code I think the main problem is because you are not executing Okhttpclient in async thread.
I think the problem should be solved if you run the code using enqueue method of the Okhttpclient.
client.newCall(request).enqueue(new Callback() {
#Override public void onFailure(Call call, IOException e) {
//Exception here
}
#Override public void onResponse(Call call, Response response) throws IOException {
try (ResponseBody responseBody = response.body()) {
/*
* Handle your response here :
* Do whatever you want if the response.isSuccesful or not
*/
}
});
I hope it helps you.

How can I connect between android client and python-Flask server, using REST API, without localhost communication?

I want to build a simple android mobile app, that will communicate through REST API with a python-Flask server -
So the android client will run on my Sumsung Galaxy J7 Prime phone (using USB connection through an android-studio script which runs on my computer), and the python-Flask server will run on my computer (using running python-Flask file through PyCharm workspace).
All i want to do is to pass a simple message between those client and server, with a regular connection (not localhost).
This is the simple server code:
from flask import Flask
app = Flask(__name__)
#app.route("/RESTfulExample/json/product/get")
def hello():
return "Hello World !!"
if __name__ == "__main__":
app.run(host='0.0.0.0', debug=True)
This code works well when i run this server, and enter the URL address with google chrome URL: http://127.0.0.1:5000/RESTfulExample/json/product/get
It works fine also when I run a script in Jave which sends this URL to the server (with localhost communication):
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class firstJava {
public static void main(String[] args) {
try {
URL url = new URL("http://localhost:5000/RESTfulExample/json/product/get");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The output is:
Output from Server ....
Hello World !!
The problem comes when i use the exact same code in the my andriod-studio project, except of changing the IP address from localhost(127.0.0.1) to the IP of my computer (10.0.0.54):
public void buttonClicked (View view){
EditText editText = (EditText) findViewById(R.id.passwordEditText);
try {
URL url = new URL("http://10.0.0.54:5000/RESTfulExample/json/product/get");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
System.out.println(conn.getResponseCode());
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
editText.setText(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
When I run this script in android studio, the application in my phone collapses, and in the console in the android-studio, the error lines are those:
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.owner.firstapp, PID: 25703
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:5721)
at android.widget.TextView.performClick(TextView.java:10931)
at android.view.View$PerformClick.run(View.java:22620)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7409)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5721) 
at android.widget.TextView.performClick(TextView.java:10931) 
at android.view.View$PerformClick.run(View.java:22620) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:7409) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) 
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273)
at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:110)
at libcore.io.IoBridge.connectErrno(IoBridge.java:137)
at libcore.io.IoBridge.connect(IoBridge.java:122)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:452)
at java.net.Socket.connect(Socket.java:884)
at com.android.okhttp.internal.Platform.connectSocket(Platform.java:117)
at com.android.okhttp.internal.http.SocketConnector.connectRawSocket(SocketConnector.java:438)
at com.android.okhttp.internal.http.SocketConnector.connectCleartext(SocketConnector.java:105)
at com.android.okhttp.Connection.connect(Connection.java:1333)
at com.android.okhttp.Connection.connectAndSetOwner(Connection.java:1412)
at com.android.okhttp.OkHttpClient$1.connectAndSetOwner(OkHttpClient.java:131)
at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:485)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:466)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:372)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:476)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:418)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:540)
at com.example.owner.firstapp.MainActivity.buttonClicked(MainActivity.java:44)
at java.lang.reflect.Method.invoke(Native Method) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
at android.view.View.performClick(View.java:5721) 
at android.widget.TextView.performClick(TextView.java:10931) 
at android.view.View$PerformClick.run(View.java:22620) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:7409) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) 
I/Process: Sending signal. PID: 25703 SIG: 9
Application terminated.
As the separated line above tells, the problem is with line 44 - System.out.println(conn.getResponseCode());
which means, that for some reason, the conn.getResponseCode() isn't work.
So i understand that the problem occures when i stop use the localhost connection and move to a regular connection between 2 devices. I just don't know how to fix it.
I didn't know i will stuck so much time with a simple server-client communication.. I will glad if someone here will help me solve this simple problem.
Thank you very much in advance, and sorry for my bad english :)
I know you posted this few months ago, but have you thought enabling internet permissions in your manifest file ?

Http client gives Target host must not be null error

My code is as shown below:
public class YActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
try {
Log.d(TAG, "onCreate: page response" + getResponseFromUrl("www.iammjet.in"));
} catch (IOException e) {
e.printStackTrace();
}
}
public String getResponseFromUrl(String url) throws IOException {
HttpClient httpclient = new DefaultHttpClient(); // Create HTTP Client
HttpGet httpget = new HttpGet(URL); // Set the action you want to do
HttpResponse response = httpclient.execute(httpget); // Executeit
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent(); // Create an InputStream with the response
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
sb.append(line);
String resString = sb.toString();
is.close();
return resString;
}
}
Now what happens here is it gives me Target host must not be null, or set in parameters. scheme=null, host=null, path=www.iammjet.in error , what should I insert to make it work?
I am using compileSdkVersion 24. To support HttpClient I have added in my build.gradle as follows:
android {
compileSdkVersion 24
buildToolsVersion "25.0.1"
useLibrary 'org.apache.http.legacy'
}
My error stack trace is as shown below:
java.lang.RuntimeException: Unable to start activity ComponentInfo{demand.inn.com.xyz.staging/demand.inn.com.xyz.activity.YActivity}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:142)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:169)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:124)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:365)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:560)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:492)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:470)
at demand.inn.com.quflip.activity.YActivity.getResponseFromUrl(YActivity.java:328)
at demand.inn.com.quflip.activity.QuFlipActivity.onCreate(QuFlipActivity.java:94)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
at android.app.ActivityThread.access$800(ActivityThread.java:151) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5254) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
--------- beginning of crash
There are three major problems with your code:
Your URL is badly formatted (giving the error)
You are doing networking on the main thread
The client library you are trying to use is being removed from later versions of android. Use an URLConnection if you can.
Formatting your URL
Your browser lies to you. www.iammjet.in is not an URL. It's just a host name. To be an URL you MUST have a scheme, host and path (as the error tells you.
http://www.iammjet.in/ is valid. It has the scheme http, host www.iammjet.in and path /. Because you have given it just the hostname it's misinterpreted it to be just the path and said that the hostname is null.
pass "http://www.iammjet.in" instead of "www.iammjet.in"

Sending POST request to website and recieving results

I need to send a HTTP post request and receive the output but when I run the app the app crashes.
Below is the code I use.
public String getRequest(String url) {
StringBuilder responseOutput = new StringBuilder();
try {
URL uri = new URL(url);
HttpURLConnection connection = (HttpURLConnection)uri.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("USER-AGENT", "Mozilla/5.0");
connection.setRequestProperty("ACCEPT-LANGUAGE", "en-US,en;0.5");
connection.setDoOutput(true);
DataOutputStream dStream = new DataOutputStream(connection.getOutputStream());
dStream.flush();
dStream.close();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = "";
while((line = br.readLine()) != null ) {
responseOutput.append(line);
}
br.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return responseOutput.toString();
}
This is the crash log.
05-18 16:34:50.915 18272-18272/com.prisonvoicemail.appupdater E/AndroidRuntime:
FATAL EXCEPTION: main
Process: com.prisonvoicemail.appupdater, PID: 18272
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.prisonvoicemail.appupdater/com.prisonvoicemail.appupdater.MainActivity}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2426)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1287)
at java.net.InetAddress.lookupHostByName(InetAddress.java:431)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at com.android.okhttp.internal.Network$1.resolveInetAddresses(Network.java:29)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:188)
at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:157)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:100)
at com.android.okhttp.internal.http.HttpEngine.createNextConnection(HttpEngine.java:357)
at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:340)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:330)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:248)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:437)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:114)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:245)
at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getOutputStream(DelegatingHttpsURLConnection.java:218)
at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java)
at com.prisonvoicemail.appupdater.HTTPRequest.getRequest(HTTPRequest.java:72)
at com.prisonvoicemail.appupdater.MainActivity.onCreate(MainActivity.java:79)
at android.app.Activity.performCreate(Activity.java:6259)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1130)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5443) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618) 
Android doens't allow network calls on main thread(which controls the ui) in order to keep him free , you need to do some easy multithreading , you can take a look at Asynctask for that operation , or use an outside library such as Retrofit , Volley , Loopj etc...
You can start with Asynctask for a first lesson:
http://developer.android.com/reference/android/os/AsyncTask.html
put the code of the call in doinbackground ( another thread and not the main thread ) , after getting your result and finishing the doinbackground you'll get to OnPost method (is on the main thread , you can make ui changes here)
Hope it helps.
You are having NetworkOnMainThreadException, this is because you are calling this method from application main thread.
You should not do any network operation (blocking operation) in the main thread, this will stuck your application until the operation is finished. Besides, wrap the function call inside an AsyncTask then call AsyncTask.execute() this will fix your issue. e.g
AsyncTask task = new AsyncTask() {
#Override
protected Object doInBackground(Object[] params) {
//do your stuff here
return null;
}
};
task.execute();
Hope that helps. cheers :)

Android, threadid=1: thread exiting with uncaught exception (group=0xb0d4bb20)

So my application makes http request calls to an API and receives a response back. My application turns the response into JSON and I parse through it. The issue I'm having is this?
W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0xb0d4bb20)
E/AndroidRuntime: FATAL EXCEPTION: main
E/AndroidRuntime: Process: com.example.stevefoo.wrestt, PID: 30650
E/AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.stevefoo.wrestt/com.example.stevefoo.wrestt.Admin.AdminUserBrowse}: java.lang.NullPointerException
E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
E/AndroidRuntime: at android.app.ActivityThread.access$800(ActivityThread.java:135)
E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:102)
E/AndroidRuntime: at android.os.Looper.loop(Looper.java:136)
E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5017)
E/AndroidRuntime: at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:515)
E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
E/AndroidRuntime: at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime: Caused by: java.lang.NullPointerException
E/AndroidRuntime: at com.example.stevefoo.wrestt.Admin.AdminUserBrowse.retrieveUsers(AdminUserBrowse.java:70)
E/AndroidRuntime: at com.example.stevefoo.wrestt.Admin.AdminUserBrowse.onCreate(AdminUserBrowse.java:42)
E/AndroidRuntime: at android.app.Activity.performCreate(Activity.java:5231)
E/AndroidRuntime: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245) 
E/AndroidRuntime: at android.app.ActivityThread.access$800(ActivityThread.java:135) 
E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 
E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:102) 
E/AndroidRuntime: at android.os.Looper.loop(Looper.java:136) 
E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5017) 
E/AndroidRuntime: at java.lang.reflect.Method.invokeNative(Native Method) 
E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:515) 
E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 
E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
E/AndroidRuntime: at dalvik.system.NativeStart.main(Native Method) 
I realized I'm getting a null pointer exception on the retrieveUser method. When I carefully inspected the JSON response being used by retrieveUser I realized that I'm not getting a full JSON response back. It's only giving me a partial JSON response back. If I use http pie to retrieve the JSON response from the server I get the full thing so the problem isn't the server. It's the call I'm making. The method being used to make the call is inside the CustomThread Callable, executeHttpGet:
/** The time it takes for our client to timeout */
public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds
/** Single instance of our HttpClient */
private static HttpClient mHttpClient;
/**
* Get our single instance of our HttpClient object
* #return an HttpClient object with connection parameters set
*/
private static HttpClient getHttpClient() {
if (mHttpClient == null) {
mHttpClient = new DefaultHttpClient();
final HttpParams params = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpClient;
}
public static String CustomThreadHttpGet(final String url, final String token){
String result = null;
ExecutorService service = Executors.newCachedThreadPool();
Future<String> future = service.submit(new Callable<String>() {
#Override
public String call() throws Exception {
String response = CustomHttpClient.executeHttpGet(url, token);
response = response.replaceAll("\\s+", "");
return response;
}
});
try {
// get() waits for the task to finish and then gets the result
result = future.get();
} catch (InterruptedException e) {
// thrown if task was interrupted before completion
e.printStackTrace();
} catch (ExecutionException e) {
// thrown if the task threw an execption while executing
e.printStackTrace();
}
return result;
}
public static String executeHttpGet(String url, String token) throws Exception {
BufferedReader in = null;
try {
//creates http client to make request
HttpClient client = getHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
request.setHeader("Accept", "application/json; charset=UTF-8");
request.addHeader("Authorization", "Bearer " + token);
HttpResponse response = client.execute(request);
//Stream reader deciphers the response
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
System.out.println(result);
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
For some reason this call is making the thread exit early before it can get the full JSON response, or at least I think that's what happening. The method actually works fine as long the JSON response is under 4000 characters, however if it goes over that it begins to only give me partial JSON responses back. Any insight for my dilemma would be appreciated.

Categories

Resources