Android display my own error message ifrom an exception - android

i have implemented a try block that does some network requests but whenever it throws an exception such has a Timeout one, the android application displays a message Saying
Sorry: The application has stopped unexpectedy, please try again.
the only option presented to the user is a force close button. i want to catch this exception and simple display my own error message and let the user try the connection again instead of the user having to close the app.
Here is the code below:
all i want to do is return null after a exception is caught and what ever class that calls this will do it its own error handling like this:
if(postRequest == null){ display error message}
private HttpResponseObject PostRequest() {
//int response = 0;
String responseBody = "";
HttpResponseObject response = new HttpResponseObject();
try {
Log.d(TAG, "IN POST_REQUEST_METHOD");
Log.d(TAG, "URL : " + url);
httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 1);
//httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000);
httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5);
Log.d(TAG, "httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);");
post = new HttpPost(url);
// ClientConnectionRequest connRequest = new ManagedClientConnection();
// post.setConnectionRequest((ClientConnectionRequest) connRequest.getConnection(3000, TimeUnit.MILLISECONDS));
ByteArrayEntity entity = new ByteArrayEntity(data.getBytes());
entity.setChunked(true);
post.setEntity(new StringEntity(data));
HttpResponse httpResponse = httpclient.execute(post);
HttpEntity resEntity = httpResponse.getEntity();
if (resEntity != null) {
// indicate that the content of this entity is no longer
// required
response.setResponseBody(EntityUtils.toString(resEntity));
Header[] header = httpResponse.getAllHeaders();
Log.d(TAG, "httpResponse.getAllHeaders() = " + header[0].getName());
response.setResponseHeader(httpResponse.getAllHeaders().toString());
resEntity.consumeContent();
}
// release all recources from the httpClient object
httpclient.getConnectionManager().shutdown();
response.setResponseCode(httpResponse.getStatusLine().getStatusCode() ) ;
Log.d(TAG, "responseBody = " + response.getResponseBody());
Log.d(TAG, "response code = " + response.getResponseCode());
Log.d(TAG, "response header = " + response.getResponseHeader());
return response;
} catch (SocketTimeoutException e) {
e.printStackTrace();
Log.d(TAG, "SocketTimeoutException e = " + e.toString());
return null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d(TAG, "IOException e = " + e.toString());
return null;
}
}

The Force Close dialog appears due to an uncaught exception. Since you are not throwing a checked exception yourself, this is due to a runtime exception, most probably a Null Pointer one. This means that there is bug in your code that causes this and not a network error.
In order to find the problem you need to know the type of the Exception being thrown and its message. You can see these at the LogCat - if you are using Eclipse it is available in the debug perspective.

Related

Android keep trying POST until it goes through

I have a POST message I absolutely have to send on Android in a given circumstance, to the point I would like it to keep trying until it completes. I was under the understanding that setting:
urlConnection.setConnectTimeout(0);
would keep trying the connection until it goes through, but what is actually happening is the try block is failing, and the UnknownHostException is being thrown instead:
private class SendAlert extends AsyncTask<String, String, String> {
protected String doInBackground(String... strings) {
Log.d(TAG, "sendAlarm: sending alarm");
String stringUrl = createUri();
HttpsURLConnection urlConnection = null;
BufferedReader reader = null;
String postData = "";
Log.d(TAG, "sendAlarm: apikey: " + apiKey);
try{
Log.d(TAG, "sendAlarm: trying");
URL finalURL = new URL(stringUrl);
urlConnection = (HttpsURLConnection)finalURL.openConnection();
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(0);
urlConnection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
urlConnection.setRequestProperty("Accept","application/json");
urlConnection.setRequestProperty("x-api-key",apiKey);
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
int responseCode = urlConnection.getResponseCode();
Log.d(TAG, "doInBackground: response code = " + responseCode);
}catch (MalformedURLException e) {
e.printStackTrace();
Log.d(TAG, "doInBackground: error 1 " + e.toString());
}catch(UnknownHostException e){
Log.d(TAG, "doInBackground: e: " + e);
Log.d(TAG, "doInBackground: retrying");
}
catch(Exception e){
Log.d(TAG, "doInBackground: error 2 " + e.toString());
}
Wondering what the best way to set up the post message on Android is, to keep trying the connection until it goes through, even if the phone is on airplane mode for 5 hours.
Edit: going of #user3252344's answer below, is there any problem with calling the function again directly in the catch block of the AyncTask:
catch(UnknownHostException e){
Log.d(TAG, "doInBackground: e: " + e);
Log.d(TAG, "doInBackground: retrying");
SendAlarm sendAlarm = new SendAlarm;
sendAlarm.execute();
}
Setting the connection timeout to 0 will mean it won't timeout, but if it fails to connect it won't handle it still. I'm guessing you get a an UnknownHostException because it fails to resolve the url since it can't reach a DNS server.
I'd suggest you just set a reasonable connection timeout, catch the timeout exception if it happens and re-run.
final int READ_TIMEOUT = 500; // Timeout
final int RETRY_MS = 2000; //Retry every 2 seconds
final Handler handler = new Handler();
Runnable myUrlCall = () -> {
try {
//Make things
urlConnect.setReadTimeout(READ_TIMEOUT);
//Make the URL call, do response
} catch (SocketTimeoutException e) {
handler.postDelayed(myUrlCall, RETRY_MS);
} catch (/* other unintended errors*/ e) {
//Log the error or alert the user
}
};
handler.post(myUrlCall);
Possible even better idea: use Android settings to check if there's internet before you make the call. If there's no internet, use a longer delay. Something like this would be the code you're looking for.

How to fix "400 bad request" with uploading file on android with java HttpClient?

I need to upload a file to server. If i use the "curl -i -F filedata=#"PATH TO FILE" http://█.199.166.14/audiostream " it return a 200 OK code (Or may be this command incorrect) .
But when I use java function
public String send()
{
try {
url = "http://█.199.166.14/audiostream";
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "test.pcm");
try {
Log.d("transmission", "started");
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
ResponseHandler Rh = new BasicResponseHandler();
InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true); // Send in multiple parts if needed
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
response.getEntity().getContentLength();
StringBuilder sb = new StringBuilder();
try {
BufferedReader reader =
new BufferedReader(new InputStreamReader(response.getEntity().getContent()), 65728);
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
}
catch (IOException e) { e.printStackTrace(); }
catch (Exception e) { e.printStackTrace(); }
Log.d("Response", sb.toString());
Log.d("Response", "StatusLine : " + response.getStatusLine() + " Entity: " + response.getEntity()+ " Locate: " + response.getLocale() + " " + Rh);
return sb.toString();
} catch (Exception e) {
// show error
Log.d ("Error", e.toString());
return e.toString();
}
}
catch (Exception e)
{
Log.d ("Error", e.toString());
return e.toString();
}
}
It's return 400 Bad request.
I'm also not sure that server proceed correctly my attempts to upload this file, but I can't check it.
From the error received its likely a bad formatted HTTP query. If audiostream is a php, write the full link.
Also it seems that there might be a wrong/bad encoded char at "http://█.199.166.14/audiostream, the link should be http://(IP or DNS)/(rest of URL)(the URI)
You should erase the link, then manually writte it again.
If those didnt fix the issue, its also possible that the Server (or its path equipment) might be blocking you. Check from the Access Log and the security rules of its accesses, that you are not blocked (some routers may block users from performing repeated querys as a sort of anti "Denial of Service" measure)

Android Compare Strings from HttpResponse

I'm having a curious problem, i have two apps (Web and Android), the first always response in text/plain with the following sintax
If the business logic is successfully the response is
OK
2013-04-01 14:31:26
if fail
ERROR
TypeError:MessageError
now the web app es working fine the problem is when i'm going to read the response in my android device
final HttpEntity entity = response.getEntity();
BufferedReader buffer;
String line = null;
try {
buffer = new BufferedReader(new InputStreamReader(entity.getContent()), 2048);
// Read first line
line = buffer.readLine();
Log.i(TAG, "Result : '" + line + "'");
if(line == "OK") {
// To something with the following lines
} else {
while(null != (line = buffer.readLine()) {
Log.i(TAG, "ERROR: " + line);
}
}
} catch (IllegalStateException e1) {
} catch (IOException e1) {
}
the problem line never is equals to OK event if the line Log.i(TAG, "Result : '" + line + "'") prints Result : 'OK'
In java you have to use .equals() to compare strings...
So your code should look like this:
if(line.equals("OK")) {

share image to inastagram from own android application

i m trying to share the image from my android application to instagram application......... i cant upload the image.........
#SuppressWarnings("unchecked")
public Map<String, String> doUpload() {
Log.i(TAG, "Upload");
Long timeInMilliseconds = System.currentTimeMillis()/1000;
String timeInSeconds = timeInMilliseconds.toString();
MultipartEntity multipartEntity = new
MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
Map returnMap = new HashMap<String, String>();
// check for cookies
/* if( httpClient.getCookieStore() == null ) {
returnMap.put("result", "Not logged in");
return returnMap;
}*/
try {
// create multipart data
System.out.println("image path name : "+processedImageUri.getPath());
System.out.println("image file path : "+ImgFilePath);
File imageFile = new File(ImgFilePath);//processedImageUri.getPath());
FileBody partFile = new FileBody(imageFile);
StringBody partTime = new StringBody(timeInSeconds);
multipartEntity.addPart("photo", partFile );
multipartEntity.addPart("device_timestamp", partTime);
} catch ( Exception e ) {
Log.e(TAG,"Error creating mulitpart form: " + e.toString());
returnMap.put("result", "Error creating mulitpart form: " + e.toString());
return returnMap;
}
// upload
try {
System.out.println("111111111111111111");
System.out.println("multipart entity value : "+multipartEntity.toString());
HttpPost httpPost = new HttpPost(Utils.UPLOAD_URL);
httpPost.setEntity(multipartEntity);
System.out.println("http post vlaue : "+httpPost.toString());
System.out.println("http client value : "+httpClient.toString());
HttpResponse httpResponse = httpClient.execute(httpPost);
System.out.println("Http response value : "+httpResponse.toString());
HttpEntity httpEntity = httpResponse.getEntity();
Log.i(TAG, "Upload status: " + httpResponse.getStatusLine());
System.out.println("staus entity value : "+httpResponse.getStatusLine().toString());
System.out.println("http status : "+HttpStatus.SC_OK);
// test result code
if( httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK ) {
Log.e(TAG, "Login HTTP status fail: " + httpResponse.getStatusLine().getStatusCode());
returnMap.put("result", "HTTP status error: " + httpResponse.getStatusLine().getStatusCode() );
return returnMap;
}
// test json response
// should look like
/*
{"status": "ok"}
*/
if( httpEntity != null ) {
BufferedReader reader = new BufferedReader(new InputStreamReader(httpEntity.getContent(), "UTF-8"));
String json = reader.readLine();
System.out.println("Entity value : "+json);
JSONTokener jsonTokener = new JSONTokener(json);
JSONObject jsonObject = new JSONObject(jsonTokener);
Log.i(TAG,"JSON: " + jsonObject.toString());
String loginStatus = jsonObject.getString("status");
if( !loginStatus.equals("ok") ) {
Log.e(TAG, "JSON status not ok: " + jsonObject.getString("status"));
returnMap.put("result", "JSON status not ok: " + jsonObject.getString("status") );
return returnMap;
}
}
} catch( Exception e ) {
Log.e(TAG, "HttpPost exception: " + e.toString());
returnMap.put("result", "HttpPost exception: " + e.toString());
return returnMap;
}
// configure / comment
try {
HttpPost httpPost = new HttpPost(Utils.CONFIGURE_URL);
String partComment = txtCaption.getText().toString();
List<NameValuePair> postParams = new ArrayList<NameValuePair>();
postParams.add(new BasicNameValuePair("device_timestamp", timeInSeconds));
postParams.add(new BasicNameValuePair("caption", partComment));
httpPost.setEntity(new UrlEncodedFormEntity(postParams, HTTP.UTF_8));
System.out.println("http client value : "+httpClient.toString());
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// test result code
if( httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK ) {
Log.e(TAG, "Upload comment fail: " + httpResponse.getStatusLine().getStatusCode());
returnMap.put("result", "Upload comment fail: " + httpResponse.getStatusLine().getStatusCode() );
return returnMap;
}
returnMap.put("result", "ok");
return returnMap;
} catch( Exception e ) {
Log.e(TAG, "HttpPost comment error: " + e.toString());
returnMap.put("result", "HttpPost comment error: " + e.toString());
return returnMap;
}
the above is the code which i m using for upload the image and the url for this is UPLOAD_URL = "http://instagr.am/api/v1/media/upload/" .............
pls can anyone help me to upload the image to instagram....... Thanks in advance
The Instagram API doesn't support uploading yet.
From the Instagram API Docs:
At this time, uploading via the API is not possible. We made a conscious choice not to add this for the following reasons:
Instagram is about your life on the go – we hope to encourage photos
from within the app. However, in the future we may give whitelist
access to individual apps on a case by case basis. We want to fight
spam & low quality photos. Once we allow uploading from other sources,
it's harder to control what comes into the Instagram ecosystem. All
this being said, we're working on ways to ensure users have a
consistent and high-quality experience on our platform.

DefaultHttpClient change response size?

What I try to do
Hello Guys, I'm trying to create an App in which I can view the Orders the Customers gave to me. For this I created a interface on my server, on which I can send post/get/set request's. The response of the Server is in JSON-Format. (For your Information atm only dummydata is filled in)
Now when I do a get request from my app to the server, I get a response from it but it isn't complete about the half of the response I should get isn't there! :( But when I open the URL with the Get-Request in my browser, I get the full response.
Question
Like you see it can't be a server-based problem, because I also tryed via 'curl' to do this get requst, and allways got the full response.
In my App i work with the DefaultHttpClient, so I tought the Problem simply could be that there's a limit for the response but I didn't found it.
So where can I change this "response-size" and what else could be the problem why I don't get the full response! Some good code-snippets or whatever you can imagine would help!
Down here you'll find the code of the Methode which does the Get-Request.
Code
If you need more Code, just write it in the comments!
getOrders()
public void getOrders() {
Log.d("DataHandlerService", "Aufträge werden geladen");
Thread t = new Thread() {
public void run() {
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
String userid = settings.getString("userid", "uid");
Log.d("DataHandlerService", userid);
// Download-URL
String URL = "http://api.i-v-o.ch/users/" + userid
+ "/assignments.json";
Log.d("Request-URL", URL);
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse response;
try {
HttpGet request = new HttpGet();
request.setURI(new URI(URL));
request.addHeader("Content-Type",
"application/x-www-form-urlencoded");
response = client.execute(request);
int statuscode = response.getStatusLine().getStatusCode();
switch (statuscode) {
case 200:
if (response != null) {
StringBuilder sb = new StringBuilder();
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity()
.getContent()));
String line;
while ((line = rd.readLine()) != null) {
sb.append(line + "\n");
}
String result;
result = sb.toString();
Log.d("Response", result);
JSONReader(result); //here the json will be generated
}
break;
case 500:
// Error-Handling
break;
}
} catch (Exception e) {
e.printStackTrace();
Log.e("DataHandler", "URLConnection-Error" + e);
}
}
};
t.start();
}
Here's the Response you asked for, like you see a part of it isn't there!:
[{"created_at":"2012-01-06T17:10:00Z","end_datetime":"2008-03-25T13:00:00Z","id":2127,"start_datetime":"2008-03-25T13:00:00Z","updated_at":"2012-01-06T17:10:00Z","title":"2127 Foobar","referee_forename":"Peter","referee_surname":"Gertsch","referee_full_name":"Peter Gertsch","category_title":"Installation - SAT","status_title":"Closed - Erfolgreich"},{"created_at":"2012-01-06T17:10:03Z","end_datetime":"2008-04-04T12:00:00Z","id":2134,"start_datetime":"2008-04-04T12:00:00Z","updated_at":"2012-01-06T17:10:03Z","title":"2134 Foobar","referee_forename":"Daniel","referee_surname":"Brunner","referee_full_name":"Daniel Brunner","category_title":"Installation - SAT","status_title":"Closed - Erfolgreich"},{"created_at":"2012-01-06T17:10:03Z","end_datetime":"2008-04-07T12:00:00Z","id":2136,"start_datetime":"2008-04-07T12:00:00Z","updated_at":"2012-01-06T17:10:03Z","title":"2136 Foobar","referee_forename":"Andreas","referee_surname":"Lutz","referee_full_name":"Andreas Lutz","category_title":"Installation - SAT","status_title":"Closed - technisches problem"},{"created_at":"2012-01-06T17:10:08Z","end_datetime":"2008-05-22T07:00:00Z","id":2144,"start_datetime":"2008-05-22T07:00:00Z","updated_at":"2012-01-06T17:10:08Z","title":"2144 Foobar","referee_forename":"Pascal","referee_surname":"Pichand","referee_full_name":"Pascal Pichand","category_title":"Installation - SAT","status_title":"Closed - Erfolgreich"},{"created_at":"2012-01-06T17:10:08Z","end_datetime":"2008-05-15T07:00:00Z","id":2145,"start_datetime":"2008-05-15T07:00:00Z","updated_at":"2012-01-06T17:10:08Z","title":"2145 Foobar","referee_forename":"Hansruedi","referee_surname":"W\u00fcrgler","referee_full_name":"Hansruedi W\u00fcrgler","category_title":"Installation - SAT","status_title":"Closed - Erfolgreich"},{"created_at":"2012-01-06T17:10:08Z","end_datetime":"2008-05-26T08:00:00Z","id":2146,"start_datetime":"2008-05-26T08:00:00Z","updated_at":"2012-01-06T17:10:08Z","title":"2146 Foobar","referee_forename":"Martina","referee_surname":"Issler","referee_full_name":"Martina Issler","category_title":"Installation - SAT","status_title":"Closed - Erfolgreich"},{"created_at":"2012-01-06T17:10:08Z","end_datetime":"2008-06-03T14:00:00Z","id":2147,"start_datetime":"2008-06-03T14:00:00Z","updated_at":"2012-01-06T17:10:08Z","title":"2147 Foobar","referee_forename":"Matthias ","referee_surname":"Kuhn","referee_full_name":"Matthias Kuhn","category_title":"Installation - SAT","status_title":"Closed - Erfolgreich"},{"created_at":"2012-01-06T17:10:12Z","end_datetime":"2008-07-07T07:00:00Z","id":2157,"start_datetime":"2008-07-07T07:00:00Z","updated_at":"2012-01-06T17:10:12Z","title":"2157 Foobar","referee_forename":"Eberhard","referee_surname":"Polatzek","referee_full_name":"Eberhard Polatzek","category_title":"Installation - SAT","status_title":"Closed - Erfolgreich"},{"created_at":"2012-01-06T17:10:13Z","end_datetime":"2008-07-11T08:00:00Z","id":2161,"start_datetime":"2008-07-11T08:00:00Z","updated_at":"2012-01-06T17:10:13Z","title":"2161 Foobar","referee_forename":"Magali","referee_surname":"Bohin","referee_full_name":"Magali Bohin","category_title":"Installation - SAT","status_title":"Closed - Erfolgreich"},{"created_at":"2012-01-06T17:10:14Z","end_datetime":"2008-07-25T08:30:00Z","id":2163,"start_datetime":"2008-07-25T08:30:00Z","updated_at":"2012-01-06T17:10:14Z","title":"2163 Foobar","referee_forename":"(Hotel Centrum Griesalp)","referee_surname":"Haltenegg Betriebs AG","referee_full_name":"(Hotel Centrum Griesalp) Haltenegg Betriebs AG","category_title":"Installation - SAT","status_title":"Closed - Erfolgreich"},{"created_at":"2012-01-06T17:10:16Z","end_datetime":"2008-08-07T09:00:00Z","id":2170,"start_datetime":"2008-08-07T09:00:00Z","updated_at":"2012-01-06T17:10:16Z","title":"2170 Foobar","referee_forename":".","referee_surname":"SAC Hollandiah\u00fctte","referee_full_name":". SAC Hollandiah\u00fctte","category_title":"Installation - SAT","status_title":"Closed - Erfolgreich"},{"created_at":"2012-01-06T17:10:16Z","end_datetime":"2009-05-07T06:30:00Z","i
Ah. Right, the problem isn't your connection or anything like that. Your service is returning an array - not an object - thus you should parse it like this:
HttpResponse response = ...
if (.. validate status ..) {
JSONArray array = new JSONArray(HttpEntityUtils.toString(response.getEntity()));
// Your JSONArray is now ready to play with.
}
And consider using an AsyncTask instead of a Thread, like this:
class AssignmentsTask extends AsyncTask<String, Void, JSONArray> {
#Override
protected JSONArray doInBackground(String... params) {
final String url = "http://api.i-v-o.ch/users/" + params[0]
+ "/assignments.json";
try {
HttpResponse response = mClient.execute(new HttpGet(url));
if (response.getStatusLine().getStatusCode() == 200) {
return new JSONArray(EntityUtils.toString(response.getEntity()));
} else {
Log.w(TAG, "Error receiving assignments for " + params[0] + ", " + response.getStatusLine());
}
} catch (ClientProtocolException e) {
Log.w(TAG, "Proto: Error fetching assignments for " + params[0], e);
} catch (IOException e) {
e.printStackTrace();
Log.w(TAG, "IO: Error reading assignments for " + params[0], e);
} catch (ParseException e) {
Log.w(TAG, "Parse: Error parsing assignments for " + params[0], e);
} catch (JSONException e) {
Log.w(TAG, "JSON: Error parsing JSON for " + params[0], e);
}
return null;
}
#Override
protected void onPostExecute(JSONArray result) {
// Stuff that handles the resulting JSONObject on
// the UI-thread goes here (i.e. update View:s)
// result is null if the operation failed
}
}
And to retrieve an order for the user "116":
new AssignmentsTask().execute("116");
The response size should be given by the web server you are contacting. You could read the response size using :
httpResponse.getEntity().getContentLength()
Also, what can happen is a connection timeout, making it impossible for the client to receive all data of the response. In that case, try using a timeout that is long enough to be sure you get all the data.
If your json is too large, then it's not a good idea in a mobile context to expect all the data coming in a single request, you could then have to design a web server that could give you chunks of a response, you would then require the first chunk, then the a different one, etc..
Usually, the http protocole's partial content is the answer for that problem.

Categories

Resources