1

I want to send messages for twitter from android external application. I am looking for examples and I found this one, but it gives me an error:

public class OAuthAccessTokenActivity extends Activity {

final String TAG = getClass().getName();

private OAuthProvider httpOauthprovider = new DefaultOAuthProvider(Constants.REQUEST_URL, Constants.ACCESS_URL, Constants.AUTHORIZE_URL);
private CommonsHttpOAuthConsumer httpOauthConsumer = new CommonsHttpOAuthConsumer(Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET);

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.i(TAG, "Starting task to retrieve request token.");
}

@Override
protected void onResume() {
    super.onResume();
    WebView webview = new WebView(this);
    webview.getSettings().setJavaScriptEnabled(true);  
    webview.setVisibility(View.VISIBLE);
    setContentView(webview);

    Log.i(TAG, "Retrieving request token from Google servers");

    try {
    Log.i(TAG, "Last Log in Code."); 
        String authUrl = httpOauthprovider.retrieveRequestToken(httpOauthConsumer, Constants.OAUTH_CALLBACK_URL);
        Log.i(TAG, "This Log isn't shown");
        // WebViewClient must be set BEFORE calling loadUrl!   
        webview.setWebViewClient(new WebViewClient() {  

            @Override  
            public void onPageStarted(WebView view, String url,Bitmap bitmap)  {
                System.out.println("onPageStarted : " + url);
            }

            @Override  
            public void onPageFinished(WebView view, String url)  {  
                Uri uri = Uri.parse(url);

                if (uri != null && uri.toString().startsWith(Constants.OAUTH_CALLBACK_URL)) {
                    view.setVisibility(View.INVISIBLE);

                    String verifier = uri.getQueryParameter(oauth.signpost.OAuth.OAUTH_VERIFIER);
                    try {
                        // this will populate token and token_secret in consumer

                        httpOauthprovider.retrieveAccessToken(httpOauthConsumer, verifier);
                        String userKey = httpOauthConsumer.getToken();
                        String userSecret = httpOauthConsumer.getTokenSecret();

                        // Save user_key and user_secret in user preferences and return
                        SharedPreferences settings = getBaseContext().getSharedPreferences("your_app_prefs", 0);
                        SharedPreferences.Editor editor = settings.edit();
                        editor.putString("user_key", userKey);
                        editor.putString("user_secret", userSecret);
                        editor.commit();

                        startActivity(new Intent(OAuthAccessTokenActivity.this, TwitterConnectActivity.class));
                        finish();

                    } catch (Exception e) {

                    }                 
                }
            }   
        });  

        webview.loadUrl(authUrl);

    } catch (Exception ex) {
        ex.printStackTrace();
    }

}
}

And this is the LogCat:

04-01 03:51:02.505: W/System.err(1295): oauth.signpost.exception.OAuthCommunicationException: Communication with the service provider failed: null
04-01 03:51:02.515: W/System.err(1295):     at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:218)
04-01 03:51:02.515: W/System.err(1295):     at oauth.signpost.AbstractOAuthProvider.retrieveRequestToken(AbstractOAuthProvider.java:74)
04-01 03:51:02.515: W/System.err(1295):     at com.limecreativelabs.twitterconnect.OAuthAccessTokenActivity.onResume(OAuthAccessTokenActivity.java:43)
04-01 03:51:02.515: W/System.err(1295):     at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1192)
04-01 03:51:02.515: W/System.err(1295):     at android.app.Activity.performResume(Activity.java:5211)
04-01 03:51:02.535: W/System.err(1295):     at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2780)
04-01 03:51:02.535: W/System.err(1295):     at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2819)
04-01 03:51:02.535: W/System.err(1295):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2266)
04-01 03:51:02.535: W/System.err(1295):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
04-01 03:51:02.535: W/System.err(1295):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
04-01 03:51:02.545: W/System.err(1295):     at android.os.Handler.dispatchMessage(Handler.java:99)
04-01 03:51:02.545: W/System.err(1295):     at android.os.Looper.loop(Looper.java:137)
04-01 03:51:02.555: W/System.err(1295):     at android.app.ActivityThread.main(ActivityThread.java:5103)
04-01 03:51:02.555: W/System.err(1295):     at java.lang.reflect.Method.invokeNative(Native Method)
04-01 03:51:02.555: W/System.err(1295):     at java.lang.reflect.Method.invoke(Method.java:525)
04-01 03:51:02.555: W/System.err(1295):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
04-01 03:51:02.588: W/System.err(1295):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
04-01 03:51:02.588: W/System.err(1295):     at dalvik.system.NativeStart.main(Native Method)
04-01 03:51:02.607: W/System.err(1295): Caused by: android.os.NetworkOnMainThreadException
04-01 03:51:02.615: W/System.err(1295):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
04-01 03:51:02.615: W/System.err(1295):     at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
04-01 03:51:02.615: W/System.err(1295):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
04-01 03:51:02.635: W/System.err(1295):     at java.net.InetAddress.getAllByName(InetAddress.java:214)
04-01 03:51:02.645: W/System.err(1295):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
04-01 03:51:02.645: W/System.err(1295):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
04-01 03:51:02.665: W/System.err(1295):     at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
04-01 03:51:02.675: W/System.err(1295):     at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
04-01 03:51:02.685: W/System.err(1295):     at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
04-01 03:51:02.685: W/System.err(1295):     at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:316)
04-01 03:51:02.705: W/System.err(1295):     at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:461)
04-01 03:51:02.715: W/System.err(1295):     at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:433)
04-01 03:51:02.725: W/System.err(1295):     at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290)
04-01 03:51:02.725: W/System.err(1295):     at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240)
04-01 03:51:02.745: W/System.err(1295):     at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:81)
04-01 03:51:02.777: W/System.err(1295):     at libcore.net.http.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:165)
04-01 03:51:02.785: W/System.err(1295):     at oauth.signpost.basic.DefaultOAuthProvider.sendRequest(DefaultOAuthProvider.java:48)
04-01 03:51:02.785: W/System.err(1295):     at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:181)
04-01 03:51:02.797: W/System.err(1295):     ... 17 more
04-01 03:51:03.745: E/cutils-trace(1295): Error opening trace file: No such file or directory (2)
04-01 03:51:05.335: D/TilesManager(1295): Starting TG #0, 0x2a23b2e0

Apparently the example was finished and ready to go, do you know what am I doing wrong? Is there anything else I need to run it? Thanks in advance.

Phantomluffy
  • 27
  • 1
  • 6

3 Answers3

0

First of all

new Testclass().execute();

declare this in your onCreate method or if you want to fire this in button's click event then put it inside button's click event.

and then outside the onCreate method

class Testclass extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(yourActivity.this);
            pDialog.setMessage("Please wait... Attempting login...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        @Override
        protected String doInBackground(String... args) {
             // Just copy your whole try block inside this
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once product deleted
            if (pDialog != null) {
                if (pDialog.isShowing()) {
                    pDialog.dismiss();
                }
            }
        }
    }

here inside doInBackground copt and paste your try block and remove your try and catch block. and pDialog is your private ProgressDialog pDialog; declare this at top of your activity.

InnocentKiller
  • 5,234
  • 7
  • 36
  • 84
  • When I place the try code into the doInBackground, it solves the network exception. However, it says I have to place the webview code outside the AsyncTask. `04-01 07:02:01.005: W/webview_proxy(1830): java.lang.Throwable:Warning: A WebView method was called on thread 'AsyncTask #1'. All WebView methods must be called on the UI thread. Future versions of WebView may not support use on other threads.` Where do I have to execute the webview methods? Thank you. – Phantomluffy Apr 01 '14 at 11:02
  • check this out, http://stackoverflow.com/questions/11356121/admob-not-working-with-asynctask, same error that you are getting. – InnocentKiller Apr 01 '14 at 11:08
  • Put your webview's code inside onPostexecute method. – InnocentKiller Apr 01 '14 at 11:23
  • Thanks you, can u tell me about any example of sending messages to tweet this way, please? This code only connects with Twitter, but it doesn't do anything more. – Phantomluffy Apr 02 '14 at 07:14
  • Check this example, http://www.androidhive.info/2012/09/android-twitter-oauth-connect-tutorial/ – InnocentKiller Apr 02 '14 at 07:16
  • @user3459766, You are welcome, Glad it worked for you. – InnocentKiller Apr 02 '14 at 07:27
  • In that example needs AsyncTask too :/ – Phantomluffy Apr 02 '14 at 07:50
  • Yes you have to use asynctask in that example also, or you can download that project directly from that site and just import it to your workspace, change your twitter key and run, it will work. – InnocentKiller Apr 02 '14 at 07:52
  • I've done that, downloaded the project and imported it to my workspace, then changed my twitter key. But when I run it, it gives me the same NetworkOnMainThreadException as when I needed to use the asynctask manually. – Phantomluffy Apr 02 '14 at 07:57
  • Yes you have to use asyntask just do the same thing which you did here or post your code in some new question and paste me link i will check it. – InnocentKiller Apr 02 '14 at 07:59
  • I've had to change the "target=android-##" line in my project.properties file from "8" to "18" in order to make the project work. Does this have something to do with the asynctask? Anyway, do you want to view the whole activity code? Thanks again. – Phantomluffy Apr 02 '14 at 08:04
  • Yes set `android:targetSdkVersion="19"` or `android:targetSdkVersion="18"` – InnocentKiller Apr 02 '14 at 08:06
  • Ok, forget it, i had to change the old libraries for the latest. It works now. – Phantomluffy Apr 02 '14 at 08:59
0

This is the code, the problem are in

requestToken=twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);

private void loginToTwitter() {
    // Check if already logged in
    if (!isTwitterLoggedInAlready()) {
        ConfigurationBuilder builder = new ConfigurationBuilder();
        builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
        builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
        Configuration configuration = builder.build();
        TwitterFactory factory = new TwitterFactory(configuration);
        twitter = factory.getInstance();
        try {
            requestToken=twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
            Log.i("LoginToTwitter", "6");
            this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL())));
            Log.i("LoginToTwitter", "7");
        } catch (TwitterException e) {
            e.printStackTrace();
            Log.i("LoginToTwitter", "catch 1");
        }
    } else {
        // user already logged into twitter
        Toast.makeText(getApplicationContext(),
                "Already Logged into twitter", Toast.LENGTH_LONG).show();
        Log.i("LoginToTwitter", "else 1");
    }
}
Phantomluffy
  • 27
  • 1
  • 6
0

I tried to implement this class, but launch TwitterException in the same line:

requestToken = twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);

class asyncTask extends AsyncTask<String, String, String> {

    ProgressDialog pDialog;
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Please wait... Attempting login...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected String doInBackground(String... args) {

        try {
            Log.i("LoginToTwitter", "joder 5");
            requestToken = twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
            Log.i("LoginToTwitter", "joder 6");
        } catch (TwitterException e) {
            e.printStackTrace();
            Log.i("LoginToTwitter", "joder catch 1");
        }
        return null;
    }

    protected void onPostExecute(String file_url) {
        // dismiss the dialog once product deleted
        Log.i("onPostExecute", "dejo de mostrar");
        if (pDialog != null) {
            if (pDialog.isShowing()) {
                pDialog.dismiss();
            }
        }
        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL())));
    }
}
Phantomluffy
  • 27
  • 1
  • 6