I searched like the whole internet but no answer could help me.
I'm trying to get a data string out of an MySQL database but just get this 'andoid.os.NetworkOnMainThreadException' error. Could anyone help me?
Here is my Code:
public String getInformationForBarcode(String barcode) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://www.example.com"); // Yes, i changed this in live code to my url with data in it
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpClient.execute(httpPost,
responseHandler);
return response.trim();
} catch (Exception e) {
System.out.println("ERROR : " + e.toString());
return "error";
}
}
Yes, I set the
<uses-permission android:name="android.permission.INTERNET" />.
All i get is the error message in LogCat :(
Hope one of you can help me!
Thanks for answering.
When you try to make connections to database it's better to do that in another thread to avoid app crash because such actions can take long time. You can use AsyncTask to perform those actions in the background. Check out the developers site for more information about the task http://developer.android.com/reference/android/os/AsyncTask.html
Related
Ok so I created a method in a new class and called it from my activity in try catch block, and when I call it and pass my string value my issue appeared...
My issue started after executing the below method after:
HttpResponse httpresponse = httpclient.execute(httppostreq);
It went to the catch (IOException e) in my activity and when I tried to print the response string it gave me the a response from the server !!!!
So the issue is when I try to pass value to the POST it should return some data but it failed and it's returning the empty message from the server
Hint :
The empty message will appear if there were no values
jsonobj.put("screenType", requestString);
So did i passed the value or not ??? and why it's causing exception ??
public void postData(String requestString) throws JSONException, ClientProtocolException, IOException {
// Create a new HttpClient and Post Header
DefaultHttpClient httpclient = new DefaultHttpClient();
JSONObject jsonobj = new JSONObject();
jsonobj.put("screenType", requestString);
//jsonobj.put("old_passw", "306");
HttpPost httppostreq = new HttpPost("mysite.org");
StringEntity se = new StringEntity(jsonobj.toString());
se.setContentType("application/json;charset=UTF-8");
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
httppostreq.setEntity(se);
HttpResponse httpresponse = httpclient.execute(httppostreq);
Log.i("in try", httpresponse.toString());
String responseText=null;
try {
responseText=EntityUtils.toString(httpresponse.getEntity());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
Log.i("in Exception",e.toString());
Log.i("arse exception", httpresponse.toString());
}
}
i also added the internet permisssion
<uses-permission android:name="android.permission.INTERNET" />
You can't make network requests on the main thread. You'll get the error you are seeing now. You need to use either AsyncTask or you need to create a new thread. Personally, I'd use AsyncTask. When you use AsyncTask you can use the onPostExecute method to return the value to the main thread.
See : NetworkOnMainThreadException
As vincent said you can't execute network requests in the UI thread, it will give you a weird exception, but rather than using an AsyncTask which will be destroyed if your activity rotates as this Infographic shows, I can recommend you to use Robospice its the best network framework I have used and it's very easy to use, Good Luck.
I am trying to get HTML source code from a Url ... I added up permission of INTERNET as well but still I couldnot get the HTML code in string ... my application just crash ... am using this on Android 4.2 ...i have also loaded same page in webview and webview is displaying the page ...Please help me ...
I am using following code
public String getXml(String url) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
ResponseHandler<String> resHandler = new BasicResponseHandler();
String page = httpClient.execute(httpGet, resHandler);
return page;
} catch (ClientProtocolException e) {
e.printStackTrace();
return "";
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
I want to ask another question as well
what if I have to get the HTML source code of a webpage which is already downloaded ?
Do what #TGMCians said, and put this in an AsyncTask. But to get the returned HTML in a string, do:
String responseEntity = EntityUtils.toString(page.getEntity);
and that should have your HTML in it.
I think you are doing network operation on main Thread that result to exception.
NetworkOnMainThreadException.
So use AsyncTask to do network operation on android version >= 3.0.
EDIT
To learn about How to perform operation in AsyncTask.
Look Android developer docs.
I have no idea about how to call a web service from Android application . I also want to use trulia web service to get data from it .
So please help me.
I dont know what trulia is, If you want to use a SOAP webservice, you should use KSOAP2. Google it and you will find alot of tutorials how to use it.
There are alot of pepol explain it good.
Are KSOAP2 not for you?
Check out HTTPClient for android. here is a good one for that http://lukencode.com/2010/04/27/calling-web-services-in-android-using-httpclient/
Now, google and u find ur answer!
GL !
You can use HttpClient to connect with the webservice/webpage/remote-data.
Here is a sample code using that you can connect webservice from Android application
try {
HttpClient client = new DefaultHttpClient();
HttpGet method = new HttpGet(Url);
HttpResponse response = client.execute(method);
StatusLine status = response.getStatusLine();
if (status.getStatusCode() == HttpStatus.SC_OK) {
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = responseHandler.handleResponse(response);
return responseBody;
}
return null;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
I need to display message and name using URL in Text view in android application. How can i do that. Please guide me a sample code/link.
Thanks.
You should use an AsyncTask to get the data you need from the specified URL and then parse it and show it.
Read about it here: http://developer.android.com/reference/android/os/AsyncTask.html
//do u want like this
if(!url_text.getText().toString().trim().equalsIgnoreCase("")){
textView.setText("");
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url_text.getText().toString());
// Get the response
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response_str = client.execute(request, responseHandler);
textView.setText(response_str);
}else{
Toast.makeText(getApplicationContext(), "URL String empty.", Toast.LENGTH_LONG).show();
}
How would one go about sending data back to server, from an android application?
I've already tried using HttpPost and posted back to a RESTful WCF service, but I couldnt get that to work (I've already created a SO question about this, without finding the solution..) - No matter what I do I keep getting 405 Method not allowed or the 400 Bad Request.. :(
I'm not asking for full code example necessarily.. just a pointer in a direction, which can enable me to send data back to a server.
It is important that the user should not have to allow or dismiss the transfer.. it should happen under the covers, so to speak
Thanks in advance
Services is the way to go. REST (I recommend this one on Android), or SOAP based. There're loads of tutorials on getting an android app communicate a service, even with .net / wcf ones.
Tho you can always just open raw sockets and send data with some custom protocol.
Edit:
Here's the doInBackground part of my asynctask handling http post communication, maybe that'll help:
protected String doInBackground(String... req) {
Log.d(TAG, "Message to send: "+req[0]);
HttpPost p = new HttpPost(url);
try{
p.setEntity(new StringEntity(req[0], "UTF8"));
}catch(Exception e){
e.printStackTrace();
}
p.setHeader("Content-type", "application/json");
String response = "";
try{
HttpResponse resp = hc.execute(p, localContext);
InputStream is = resp.getEntity().getContent();
response = convertStreamToString(is);
Log.d("Response", "Response is " + response);
} catch (Exception e){
e.printStackTrace();
}
return response;
}