Async task crashes the aplication on android when internet is unavailable - android

In my android app I've used a async task to handle my internet request. I achieved that by using the okhttp library, which makes it easy to make internet requests. I have a lot of the code surrounded my try/catch statements, but they somehow do not trigger when there is an unhandled exception so the app crashes. That only happens when the internet is disconnected or is slow in areas.
I've looked for similar posts, but found out that people who had the same problems didn't try/catch, so the exceptions weren't handled
I've also tried to make a checker for the internet accessibility, but that didn't work out too well, because i would much rather do it with clean try-catching.
private class prenesi extends AsyncTask<String, Void, String>
{
String odgovor = null;
protected String doInBackground(String... params)
{
OkHttpClient client = new OkHttpClient();
RequestBody vsebina = new FormEncodingBuilder()
.add("kraj", params[0])
.build();
Request request = new Request.Builder()
.url("http://mypage.com/login.php")
.post(vsebina)
.build();
Response response = null;
try
{
response = client.newCall(request).execute();
}
catch (IOException e)
{
e.printStackTrace();
}
if (!response.isSuccessful())
{
odgovor = "Napaka.";
}
else
try
{
odgovor = response.body().string();
}
catch (IOException e)
{
e.printStackTrace();
}
return odgovor;
}
}
The devconsole says the problem is in the doInBackground() and i guess it caused because the null pointer exception, though I'm not entirely sure what that means:
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
Caused by: java.lang.NullPointerException
Could somebody point me towards the flaw please. I'm stuck with this.
All the help will be very appreciated, hope to solve this problem soon.
Thanks for contributing.

It seems that you forgot to initialize your String value. Run it by first setting String odgovor=""; instead of String odgovor= null;
Try modifying the code to this
String odgovor="";
try{
response = client.newCall(request).execute();
if (!response.isSuccessful()) {
odgovor = "Napaka.";
} else{
odgovor = response.body().string();
}} catch (IOException e) {
e.printStackTrace();
}

Seems the problem in the end was with the isSuccessul method, which was a bit cheesy, idk why, but instead of it i used if(response == null).

Related

Handle "Server not responding" exception in AsyncTask

How do you handle the RuntimeException when AsyncTask couldn't connect to server since server is "down" for some reason?
What do I try is a bunch of catch blocks (doesn't help):
try {
// Create Request to server and get response
HttpGet httpget = new HttpGet(activity.getString(R.string.get_channels_lang_host));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
downloadedString = httpclient.execute(httpget, responseHandler);
}catch (MalformedURLException e) {
Log.e("URL:","is a malformed URL");
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
Log.e("URL:"," UnsupportedEncodingException");
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.e("URL:"," ClientProtocolException");
} catch (SocketTimeoutException e) {
e.printStackTrace();
Log.e("URL:"," SocketTimeoutException");
} catch (ConnectTimeoutException e) {
e.printStackTrace();
Log.e("URL:"," ConnectTimeoutException");
} catch (IOException e) {
Log.e("URL:","IOException");
e.printStackTrace();
}
if (downloadedString != null) {
//parse request to object
dataChannelsLangArrayList = JsonParser.getDataChannelsLang(downloadedString);
} else {
Toast.makeText(ActivityLoading.this, "Failed to load data. Restarting...", Toast.LENGTH_LONG).show();
Global.restartApp(ActivityLoading.this);
}
i'm still getting the runtime error:
04-09 11:31:29.610 3696-3719/tenkol.design.com.imbrecords E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:864)
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:121)
at android.widget.Toast$TN.<init>(Toast.java:322)
at android.widget.Toast.<init>(Toast.java:91)
at android.widget.Toast.makeText(Toast.java:238)
at tenkol.design.com.imbrecords.Global.restartApp(Global.java:115)
at tenkol.design.com.imbrecords.ActivityLoading$LoadingAsyncTask.getChannelsLang(ActivityLoading.java:249)
at tenkol.design.com.imbrecords.ActivityLoading$LoadingAsyncTask.doInBackground(ActivityLoading.java:157)
at tenkol.design.com.imbrecords.ActivityLoading$LoadingAsyncTask.doInBackground(ActivityLoading.java:141)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
            at java.util.concurrent.FutureTask.run(FutureTask.java:137)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
            at java.lang.Thread.run(Thread.java:864)
I'm mostly interested in two cases:
When server doesn't respond at all;
When the time spend for request is too big (i.e. with slow Internet).
What is the proper way to handle those?
Can't create handler inside thread that has not called Looper.prepare()
Well, you have created a Handler, but the thread it is linked to doesn't have any message queue to post stuff on.
Try new Handler(Looper.getMainLooper()) for a handler linked to main thread.
Then you can post a Runnable on it which shows a toast.
But seriously, why not collect exception and result both and handle it all in onPostExecute() ?
Public class Result<T>{
public T data;
public Exception exception;
public String message;
}

NullPointerException only when on Google Play Store?

I recently uploaded an update of my app to Google Play. When trying it out, I get an error when clicking on a manually added banner (e.g. not AdMob or anything like that). The click is setting of an AsyncTask that sends data to a php-script using POST. I use ProGuard so when I send the error report to myself I am only able to see the method in which the error is caused: doInBackground. I am also able to see that it is a NullPointerException. The strange thing is, when I run the app on my device from my computer using Eclipse, the error doesn't occur, so I can't really find what line is causing the NullPointerException. It has worked perfectly in previous versions of my app, and I haven't made any changes to this code. And when I look through the method doInBackground, I can't find any place where a NullPointerException might occur.
Here is the error message from my developers console, this is proguarded though:
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:278)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
Caused by: java.lang.NullPointerException
at se.nollekollen.main.d.a(Unknown Source)
at se.nollekollen.main.d.doInBackground(Unknown Source)
at android.os.AsyncTask$2.call(AsyncTask.java:264)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
... 5 more
And here is my doInBackground:
#Override
protected String doInBackground(String... arg0) {
String url_stats = "http://xxxxx.xx/statistik/sendStatistics_click.php";
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("activity", getClass().getEnclosingClass().getName().substring(20)));
params.add(new BasicNameValuePair("section", SECTION));
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_stats);
try {
httpPost.setEntity(new UrlEncodedFormEntity(params));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
try {
httpClient.execute(httpPost);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
The only thing that could be null here is actually "SECTION", but that wouldn't cause a NullPointerException since the value can be null when creating a new BasicNameValuePair(key, value).
Can anyone find what could cause the NullPointerException? And how is it possible that this ONLY occurs when the app is downloaded from Google Play, and not when run from the computer?

Crashing JSON Parsing Android App

Im trying to create an app that gets a json object from a url.
This is proving to be unnecessarily frustrating as it keeps crashing on the activity that is supposed to load and parse the json object. It just pops up the message "Unfortunately, (AppName) has stopped." and then exits the application. The data from the JSON is never shown on the screen. Here is the code with the activity and the JSON parsing
package com.example.Accomplist;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.RemoteException;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
/**
* Created with IntelliJ IDEA.
* User: DESAI_628IL
* Date: 3/1/13
* Time: 7:34 PM
* To change this template use File | Settings | File Templates.
*/
public class MainScreen extends Activity{
TextView myTextView;
// HttpClient client;
// url to make request
final static String url = "http://accomplist.herokuapp.com/api/v1/sharedevent/2/?format=json";
private static final String TAG_EVENT="event"; //A JSON object within the JSON object that will be returned by JSONParse()
private static final String TAG_DESCRIPTION="description"; //A JSON tag within the JSON object EVENT
private static String eventString="Yo";
static JSONObject json;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_screen);
new JSONParse().execute(url);
}
private class JSONParse extends AsyncTask<String, String, String> {
HttpClient client;
JSONObject jsonObj= null;
#Override
protected String doInBackground(String... jsonurl) {
StringBuilder url= new StringBuilder(String.valueOf(jsonurl));
HttpGet get= new HttpGet(url.toString());
HttpResponse r= null;
try {
r = client.execute(get);
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
int status= r.getStatusLine().getStatusCode();
if (status==200){
HttpEntity e=r.getEntity();
String data= null;
try {
data = EntityUtils.toString(e);
} catch (IOException e1) {
e1.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
try {
jsonObj = new JSONObject(data);
} catch (JSONException e1) {
e1.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
try {
JSONObject eventJson= jsonObj.getJSONObject(TAG_EVENT);
eventString= eventJson.getString(TAG_DESCRIPTION);
}
catch (JSONException e1) {
eventString="Couldn't Parse Data";
}
return eventString;
}
else{
return eventString;
}
}
protected void onProgressUpdate(String... progress) {
Toast loadingToast= Toast.makeText(getApplicationContext(), "Loading", Toast.LENGTH_LONG);
loadingToast.show();
}
protected void onPostExecute(String result) {
eventString=result;
myTextView = (TextView)findViewById(R.id.textView1);
myTextView.setText(eventString);
}
}
}
I hope someone can help. Ive been stuck on this for the longest time. Ive tried many things. Ive tried different ways of getting the JSON object from the url, putting the parsing code in a different class, and lots of other small things. Any help would be appreciated. Here is the LogCat error report
02-26 12:18:46.691: ERROR/ThrottleService(324): problem during onPollAlarm: java.lang.IllegalStateException: problem parsing stats: java.io.FileNotFoundException: /proc/net/xt_qtaguid/iface_stat_all: open failed: ENOENT (No such file or directory)
02-26 12:19:53.601: WARN/dalvikvm(4073): threadid=11: thread exiting with uncaught exception (group=0x40a71930)
02-26 12:19:55.121: WARN/dalvikvm(4073): threadid=12: thread exiting with uncaught exception (group=0x40a71930)
02-26 12:19:57.632: WARN/InputMethodManagerService(324): Got RemoteException sending setActive(false) notification to pid 4073 uid 10048
02-26 12:20:03.452: WARN/dalvikvm(4094): threadid=11: thread exiting with uncaught exception (group=0x40a71930)
02-26 12:20:04.744: ERROR/AndroidRuntime(4094): FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
at java.util.concurrent.FutureTask.run(FutureTask.java:239)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:856)
Caused by: java.lang.IllegalArgumentException: Illegal character in path at index 0: [Ljava.lang.String;#40d12070
at java.net.URI.create(URI.java:727)
at org.apache.http.client.methods.HttpGet.<init>(HttpGet.java:75)
at com.example.Accomplist.MainScreen$JSONParse.doInBackground(MainScreen.java:84)
at com.example.Accomplist.MainScreen$JSONParse.doInBackground(MainScreen.java:78)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
... 4 more
02-26 12:20:10.512: WARN/InputMethodManagerService(324): Got RemoteException sending setActive(false) notification to pid 4094 uid 10048
02-26 12:20:24.401: WARN/dalvikvm(4111): threadid=11: thread exiting with uncaught exception (group=0x40a71930)
02-26 12:20:24.441: ERROR/AndroidRuntime(4111): FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
at java.util.concurrent.FutureTask.run(FutureTask.java:239)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:856)
Caused by: java.lang.IllegalArgumentException: Illegal character in path at index 0: [Ljava.lang.String;#40d12038
at java.net.URI.create(URI.java:727)
at org.apache.http.client.methods.HttpGet.<init>(HttpGet.java:75)
at com.example.Accomplist.MainScreen$JSONParse.doInBackground(MainScreen.java:84)
at com.example.Accomplist.MainScreen$JSONParse.doInBackground(MainScreen.java:78)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
... 4 more
02-26 12:20:29.411: WARN/InputMethodManagerService(324): Got RemoteException sending setActive(false) notification to pid 4111 uid 10048
try something like this..
HttpClient client = new DefaultHttpClient();
// Perform a GET request for a JSON list
HttpUriRequest request = new HttpGet("https://somejson.json");
// Get the response that sends back
HttpResponse response = null;
try {
response = client.execute(request);
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Try with this
new JSONParse().execute("");
instead of
new JSONParse().execute(url);
can u paste your logcat message so that i can help u more accurately.
The parameter in the doInbackgroud() is work like an array so that you can pass multiple argument to this method while calling the execute method on AsyncTask. The first passed parameter would be stored on the 0th position and so on. Since you are only passing one parameter to the execute method, that parameter would be stored on the 0th position... So you need to get the URL from jsonurl[0]
Try with
StringBuilder url= new StringBuilder(String.valueOf(jsonurl[0]));
Change your doInBackground method as :
#Override
protected String doInBackground(String... jsonurl) {
StringBuilder url= new StringBuilder(String.valueOf(jsonurl[0]));
HttpGet get= new HttpGet(url.toString());
HttpResponse r= null;
currently you are passing wrong url to get data form web service. see following to known move how we get value from varargs inside doInBackground method
What does the "..." mean in a parameter list? doInBackground(String... params)
You Haven't get your Http client
set
HttpClient httpClient = new DefaultHttpClient(); in your doInBackGround()
You have 2 mistakes
1. StringBuilder url= new StringBuilder(String.valueOf(jsonurl[0]));
// jsonurl[0]
2. client = new DefaultHttpClient();
// Add this line too

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();

Twitter + OAuth Integration

Anybody can please help in Android + Twitter Integration using OAuth.
I already worked on http://github.com/brione/Brion-Learns-OAuth and getting the error listed below, when I am posting status update...
WARN/System.err(190): org.apache.http.client.HttpResponseException: Unauthorized
WARN/System.err(190): at org.apache.http.impl.client.BasicResponseHandler.handleResponse(BasicResponseHandler.java:71)
WARN/System.err(190): at org.apache.http.impl.client.BasicResponseHandler.handleResponse(BasicResponseHandler.java:59)
WARN/System.err(190): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:657)
WARN/System.err(190): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:627)
WARN/System.err(190): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:616)
WARN/System.err(190): at com.test.twitter.BLOA$PostTask.doInBackground(BLOA.java:343)
WARN/System.err(190): at com.test.twitter.BLOA$PostTask.doInBackground(BLOA.java:1)
WARN/System.err(190): at android.os.AsyncTask$2.call(AsyncTask.java:185)
WARN/System.err(190): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:256)
WARN/System.err(190): at java.util.concurrent.FutureTask.run(FutureTask.java:122)
WARN/System.err(190): at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:648)
WARN/System.err(190): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:673)
WARN/System.err(190): at java.lang.Thread.run(Thread.java:1060)
I succeed with OAuth Authentication and getting user_secret and user_token and stored in preferences...
So the issue is with http posting using OAuth header...
and My Http Post Method is as :
private class PostTask extends AsyncTask<String, Void, JSONObject> {
ProgressDialog postDialog;
#Override
protected void onPreExecute() {
postDialog = ProgressDialog.show(BLOA.this,
getText(R.string.tweet_progress_title),
getText(R.string.tweet_progress_text), true, // indeterminate
// duration
false); // not cancel-able
}
#Override
protected JSONObject doInBackground(String... params) {
JSONObject jso = null;
try {
HttpPost post = new HttpPost(
"http://twitter.com/statuses/update.json");
LinkedList<BasicNameValuePair> out = new LinkedList<BasicNameValuePair>();
out.add(new BasicNameValuePair("status", params[0]));
post.setEntity(new UrlEncodedFormEntity(out, HTTP.UTF_8));
post.setParams(getParams());
// sign the request to authenticate
mConsumer.sign(post);
String response = mClient.execute(post,
new BasicResponseHandler());
jso = new JSONObject(response);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (OAuthMessageSignerException e) {
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
e.printStackTrace();
} catch (OAuthCommunicationException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
}
return jso;
}
// This is in the UI thread, so we can mess with the UI
protected void onPostExecute(JSONObject jso) {
postDialog.dismiss();
if (jso != null) { // authorization succeeded, the json object
// contains the user information
mEditor.setText("");
mLast.setText(getCurrentTweet(jso));
} else {
mLast.setText(getText(R.string.tweet_error));
}
}
}
Although you are received the user_secret and user_token successfully in onResume(), are you sure your original objects are still the same? I had this problem in my Android app. I would create the objects, but when onResume() was called it was a totally new instance of the Activity because it was free'd from memory when the browser launched. So when I tried to set the returned secret/token pair it wouldn't work. This is more likely to happen on a device with limited memory. Some people choose to persist the necessary info between calls and others decide to not launch the default browser intent, but rather host an embedded webview so their original signpost-oauth objects don't go out of scope.
OAuth instance state in Android
Not sure if this is the issue, but maybe worth a look.
You need to add the oauth information to the headers of the http request using post.addHeader(). To know which things to add to the headers, take a look here: http://dev.twitter.com/pages/auth
Please describe what Client/Consumer/Provider you are using, they must be DefaultHttpClient/CommonsHttpOAuthConsumer/CommonsHttpOAuthProvider to work properly for sure.
Ensure you call consumer.setTokenWithSecret(oToken, oTokenSecret); before calling this code.
Also, is post.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false); exists in your post params?
What's the reason for using empty BasicResponseHandler, it handles nothing and it can be omitted in execute call, I suppose.
And, may be a dumb question, may be you are overwriting params when calling setParams(...) after setEntity(...)
I have 2 tutorials for 2 different Java libs. First one (dated) is here, and 2nd one here with Scribe. It's for LinkedIn but it would be very easy to switch to Twitter. I would go with #2

Categories

Resources