Android - How to handler timeout - android

I have a problem with request POST/GET in Android.
I am trying to handle the error:
Caused by: java.net.SocketTimeoutException: Read timed out
To prevent the crash on my application, I added a timeout of 40 seconds. That works but sometimes 40 seconds is not enough to avoid the error.
I tried to add the "try and catch" but it seems that the error isn't occurring inside here:
try {
request.setEntity(new UrlEncodedFormEntity(nameValuePairs));
localContext.setAttribute(ClientContext.COOKIE_STORE,
Backend2.cookieStore);
response = HttpManager.execute(request, localContext);
if (response.getEntity() != null) {
final String r = EntityUtils.toString(response.getEntity());
return r;
} else {
return null;
}
} catch (SocketTimeoutException e) {
e.printStackTrace();
return null;
} catch (UnknownHostException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
I am looking for a solution but when I read on stackoverflow and on google, I see only posts like "increase your timeout, add a try, etc.."
I am doing something wrong?

It's hard to tell just looking at your catch statement, but maybe you are getting a different error than a SocketTimeoutException? Try to catch an Exception instead to confirm that.

Related

Error in uploading file in Android by POST

I have written a Android program to upload a file to server by HTTP POST.
Earlier its was working fine but I don't know why it is not working now.
I am testing this with my Android Device.
I Have just checked that It is working fine with emulator.
When I open that link in browser, Then it is still working fine and open correctly.
Do any body can tell me what could be the problem???
I am getting this error: (No Address associated with hostname)
10-07 04:28:14.410: I/System.out(1280): executing request POST http:////path/to/my/server//api/index.php/match HTTP/1.1
10-07 04:28:14.450: W/System.err(1280): java.net.UnknownHostException: Unable to resolve host "//path/to/my/server/": No address associated with hostname
Here is my code...
private class UploadFilesTask extends AsyncTask<File, Void, Void> {
#Override
protected Void doInBackground(File... arg0) {
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
enter code here
// I have not shown my REAL server address due so some restriction, So assume below URL is correct
HttpPost httppost = new HttpPost("http://path/to/my/server/"); //Assume path is correct
//File file = new File("/mnt/sdcard/DCIM/Camera/01.jpg");
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(arg0[0], "image/jpeg");
mpEntity.addPart("userfile", cbFile);
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = null;
try {
response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpEntity resEntity = response.getEntity();
System.out.println(response.getStatusLine());
if (resEntity != null) {
try {
//audioFilename = EntityUtils.toString(resEntity);
System.out.println(EntityUtils.toString(resEntity));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (resEntity != null) {
try {
resEntity.consumeContent();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
httpclient.getConnectionManager().shutdown();
return null;
}
}
Try the following
Delete your AVD
Shut down Eclipse
Created the AVD via the command line (e.g. android create avd -n my_android1.5 -t 2)
Launched it from the command line with the option -dns-server 8.8.8.8 (e.g. emulator -avd my_android1.5 -dns-server 8.8.8.8)
p.s. Make sure you didn't delete the internet permission in your manifest file by accident. Also, while you are it, check and make sure the address work on your android browser.
Try flush DNS. (in windows: ipconfig /flushdns)
Or change DNS provider.
Maybe there is a 2 '/' simbols in url ? "...server//api..." this must be like this "...server/api..."

How to use webview or open URL in AndEngine - Android

I'm utilizing a game engine called AndEngine (which I'm completely new to) in my Android app. I need to load a different URL from the application based on what position an onscreen joystick is in (uploading to a .cgi server). The dilemma is that I cannot open a URL connection! This may seem simple, but I've looked everywhere, tried multiple solutions and nothing's worked. In basic Android, I've always used a WebView (loadUrl() method), and it worked well. However, I have no idea to how to create a webview while also using AndEngine. My preference is that the connection did not show (loaded underneath the AndEngine scene?) because I will need the screen for other things. I've also tried other solutions. I just tried this code, but when I checked the server, nothing was opened:
#Override
public void onLoadResources() {
//methods n/a to this question
try {
URL url = new URL(setUrl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
readStream(con.getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
return scene; // AndEngine return statement
}
private void readStream(InputStream in) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
**I've tried using the HTTPConnection class before (without AndEngine) to open up a URL, but to no avail. So it may be that I was just doing something wrong here. Using AndEngine GLES2. If more info is needed, let me know (this is my first question on SO).
Also tried setting up my .xml layout on AndEngine using
#Override
protected int getLayoutID() {
return R.layout.main;
}
but it says: "The method getLayoutID() of type Control must override or implement a supertype method"
Edit in response to Nicolas Gramlich: Internet permissions were set and compiler was originally at 1.6. Still don't know what the issue is.
xml
<manifest xlmns:android...>
...
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>
Set java compiler compliance to 1.6
I solved my issue. I had to run all network operations on a thread separate from the main one (else it will throw a NetworkOnMainThread exception). I don't know why nothing else worked, but this did the trick! Here I'm creating a new thread with the action I want to perform, and then starting it after exceptions are taken care of. I found my answer here
new Thread(new Runnable() {
public void run() {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("your_url");
try {
HttpResponse response = httpClient.execute(httpGet, localContext);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();

Getting "FATAL EXCEPTION : AsyncTask #2". And I don't know what's causing it

While trying to call a web service and get the corresponding json object I get a fatal exception. I have absolutely no idea where to look and what errors to correct.
EDIT:
private class CallServiceTask extends AsyncTask<Object, Void, JSONObject>
{
protected JSONObject doInBackground(Object... params)
{
HttpGet req = (HttpGet) params[0];
String url = (String) params[1];
return executeRequest(req, url);
}
}
And here's executeRequest method called in doInBackground:
private JSONObject executeRequest(HttpGet request, String url)
{
HttpClient client = new DefaultHttpClient();
JSONObject jsonObj = null;
client = getNewHttpClient();
HttpResponse httpResponse;
try {
httpResponse = client.execute(request);
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String response = convertStreamToString(instream);
try {
jsonObj = new JSONObject(response);
} catch (JSONException e1) {
e1.printStackTrace();
}
// Closing the input stream will trigger connection release
instream.close();
}
} catch (ClientProtocolException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
} catch (IOException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
}
return jsonObj;
}
Just looking at your LogCat stack trace (in this case) it tells you all you need to know about what this exception is and what has caused it:
thread exiting with uncaught exception
Tells you that an exception has been thrown which your code does not handle
An error occurred while executing doInBackground()
This tells you that your doInBackground() function in your Async task has thrown this unhandled exception
Caused by: java.lang.ClassCastException ...HttpPost... (RestClient.java:275)
And that tells you that you have encountered a ClassCastException, resulting from a HttpPost call at line 275 in that source file.
EDIT:
Should have read that stack trace more carefully... as HandlerExploit has posted It's the HttpPost that's throwing that error, where you're expecting a HttpGet... but the following debug method still stands:
If you add an extra catch (ClassCastException e) with an e.getMessage() you'll most likely see a useful error message that describes the problem in more detail.
When in this situation and I find an unexpected exception being thrown like this I tend to add a temporary 'catch all' (catch (Exception e) { e.printStackTrace() } ) and stick a break point on the e.printStackTrace() so I can see all the details about the exception... might not be the most efficient way of doing it but its a start when you're in the dark!
My best guess would be that :
HttpGet req = (HttpGet) params[0];
Is returning a HttpPost instead of a HttpGet.
Please post where you are calling new CallServiceTask().execute();

Using Android to submit to a Google Spreadsheet Form

First time asking a question here. Usually I can find my answer without having to ask, but this time I'm stuck and can't figure out what I'm missing.
I'm just trying to have my Android app fill out a form on a website and submit it. I don't need the app to do anything with any data being sent back, just fill out the form and submit it. Basically I'm trying to collect the results of a voting app. I thought form submission would be simple so I created a Google Spreadsheet and made a form out of it. I figured I'd point the Android app to the form and then I would have all the data in the spreadsheet for later viewing. I can't get the Android app to actually fill out the form though. Here's the resources.
Form
Spreadsheet
private void submitVote(String outcome) {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("https://spreadsheets.google.com/spreadsheet/formResponse?hl=en_US&formkey=dDlwZzh4bGFvNFBxUmRsR0d2VTVhYnc6MQ&ifq");
List<BasicNameValuePair> results = new ArrayList<BasicNameValuePair>();
results.add(new BasicNameValuePair("entry.0.single", cardOneURL));
results.add(new BasicNameValuePair("entry.1.single", outcome));
results.add(new BasicNameValuePair("entry.2.single", cardTwoURL));
try {
post.setEntity(new UrlEncodedFormEntity(results));
} catch (UnsupportedEncodingException e) {
// Auto-generated catch block
Log.e("YOUR_TAG", "An error has occurred", e);
}
try {
client.execute(post);
} catch (ClientProtocolException e) {
// Auto-generated catch block
Log.e("YOUR_TAG", "An error has occurred", e);
} catch (IOException e) {
// Auto-generated catch block
Log.e("YOUR_TAG", "An error has occurred", e);
}
}
I made both the form and the spreadsheet public so feel free to mess around with it and try and get it to work yourself.
I get no errors from my program, no compile errors, no errors in DDMS. When I actually run the program and click the button that executes this code I can see the delay since right now this is in the UI thread, so I know it's executing it. It appears as if everything is working perfectly, but my spreadsheet doesn't update at all.
Any thoughts? I'm sure it's something stupid that I'm missing, but any help would be appreciated.
Here's the updated code with lots of logging and debugging stuff.
private void submitVote(String outcome) {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("https://spreadsheets.google.com/spreadsheet/formResponse?hl=en_US&formkey=dDlwZzh4bGFvNFBxUmRsR0d2VTVhYnc6MQ&ifq");
List<BasicNameValuePair> results = new ArrayList<BasicNameValuePair>();
results.add(new BasicNameValuePair("entry.0.single", cardOneURL));
results.add(new BasicNameValuePair("entry.1.single", outcome));
results.add(new BasicNameValuePair("entry.2.single", cardTwoURL));
try {
post.setEntity(new UrlEncodedFormEntity(results));
} catch (UnsupportedEncodingException e) {
// Auto-generated catch block
Log.e("YOUR_TAG", "An error has occurred", e);
}
try {
HttpResponse httpResponse = client.execute(post);
Log.e("RESPONSE", "info: " + httpResponse);
BufferedReader rd = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
String line;
while ((line = rd.readLine()) != null) {
Log.i("words", line);
}
Intent intent = new Intent(this, ReadingView.class);
intent.putExtra("html", line);
startActivity(intent);
} catch (ClientProtocolException e) {
// Auto-generated catch block
Log.e("YOUR_TAG", "client protocol exception", e);
} catch (IOException e) {
// Auto-generated catch block
Log.e("YOUR_TAG", "io exception", e);
}
}
I use ReadingView.class for something else in my app, but hijacked it for this logging purpose right now. It only has an onCreate() method, which is below.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.readingview);
WebView mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
//mWebView.loadUrl(getIntent().getExtras().getString("url"));
mWebView.loadData(getIntent().getExtras().getString("html"), "text/html", "utf-8");
}
Also worth noting that in the DDMS it only logs one output of line. I believe this is just because the html code is returned all as one line. Correct me if I'm wrong.
So I finally figured out what was going on. Through messing with manually encoding answers to the end of the form POST url I was able to find that the url it gave when viewing the source had encoding issues of it's own in it.
Here's the url from source:
<form action="https://spreadsheets.google.com/spreadsheet/formResponse?hl=en_US&formkey=dDlwZzh4bGFvNFBxUmRsR0d2VTVhYnc6MQ&ifq" method="POST" id="ss-form">
But here's what it needs to be to actually work in the above code:
https://spreadsheets.google.com/spreadsheet/formResponse?hl=en_US&formkey=dDlwZzh4bGFvNFBxUmRsR0d2VTVhYnc6MQ
The extra amp; was what was messing it up. For whatever reason it works without the last &ifq too, so I left that off. Anyway, here's completed code:
private void submitVote(String outcome) {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("https://spreadsheets.google.com/spreadsheet/formResponse?hl=en_US&formkey=dDlwZzh4bGFvNFBxUmRsR0d2VTVhYnc6MQ");
List<BasicNameValuePair> results = new ArrayList<BasicNameValuePair>();
results.add(new BasicNameValuePair("entry.0.single", cardOneURL));
results.add(new BasicNameValuePair("entry.1.single", outcome));
results.add(new BasicNameValuePair("entry.2.single", cardTwoURL));
try {
post.setEntity(new UrlEncodedFormEntity(results));
} catch (UnsupportedEncodingException e) {
// Auto-generated catch block
Log.e("YOUR_TAG", "An error has occurred", e);
}
try {
client.execute(post);
} catch (ClientProtocolException e) {
// Auto-generated catch block
Log.e("YOUR_TAG", "client protocol exception", e);
} catch (IOException e) {
// Auto-generated catch block
Log.e("YOUR_TAG", "io exception", e);
}
}
Hope this helps someone else when trying to work with Google Spreadsheet Forms. And thanks to #pandre for pointing me in the right direction.
The format, entry.0.single might not work in many cases. You must always find the proper id of the elements to create your POST request. This article provides the proper way to post data to a Google docs sheet via android app.
Have a look at the source for Acra. This uploads stack traces to a Google spreadsheet.
You probably are not seing errors because you are printing exceptions in the wrong way.
You are using e.printStackTrace(); which does not appear in DDMS/Logcat.
You should use instead
Log.e("YOUR_TAG, "An error has occurred", e);
which will log your error in DDMS/Logcat. You should see the stacktrace of the exception, and it will help you understand what's wrong.
EDIT:
Have you checked what is returned in client.execute(post); ?
You should check what is being returned in the POST response by doing:
HttpResponse httpResponse = client.execute(post);
You can also run the application in debug mode and check where it is crashing / stopping
So the cardOneUrl's are text edit fields in a layout.xml "results.add(new BasicNameValuePair("entry.0.single", cardOneURL));" Thanks, Joe

why java.net.UnknownHostException: Host is unresolved: webservername.com:80?

I m implementing android app in that I m working on web api. Sometimes my app gets connected to webserver but sometimes it throws exception as java.net.UnknownHostException: Host is unresolved: webservername.com:80. I m fetching json response from api.
I m using fetching code as following:
String queryResult = null;
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
try {
request.setURI(new URI(archiveQuery));
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//HttpResponse response = client.execute(request, new BasicResponseHandler());
try {
queryResult = client.execute(request, new BasicResponseHandler());
}
catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I think it's a DNS issue of your server, according to your comments. Sometimes you ping, sometimes you don't, but on your browser it always work? Surely it's a server connectivity issue.
The Answer is really very simple. You need to Restart the emulator.Check out this
Just restart adb, find adb.exe in your adt bundle and double click it. Some shit will happen on command prompt, and there you go, restart your emulator and it should work fine,

Categories

Resources