3

I have searched a lot on it but not able to find a solution. I am trying to integrate twitter in my Android app. It works fine on emulator but does not go well on honeycomb and higher devices. Below, I have attached the log cat error with code.

01-14 11:56:31.226: W/System.err(3649): android.os.NetworkOnMainThreadException
01-14 11:56:31.230: W/System.err(3649):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
01-14 11:56:31.230: W/System.err(3649):     at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
01-14 11:56:31.230: W/System.err(3649):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
01-14 11:56:31.230: W/System.err(3649):     at java.net.InetAddress.getAllByName(InetAddress.java:220)
01-14 11:56:31.230: W/System.err(3649):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:71)
01-14 11:56:31.230: W/System.err(3649):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
01-14 11:56:31.230: W/System.err(3649):     at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:351)
01-14 11:56:31.230: W/System.err(3649):     at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:86)
01-14 11:56:31.230: W/System.err(3649):     at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
01-14 11:56:31.230: W/System.err(3649):     at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:308)
01-14 11:56:31.230: W/System.err(3649):     at libcore.net.http.HttpEngine.connect(HttpEngine.java:303)
01-14 11:56:31.230: W/System.err(3649):     at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:282)
01-14 11:56:31.234: W/System.err(3649):     at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:232)
01-14 11:56:31.234: W/System.err(3649):     at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:273)
01-14 11:56:31.234: W/System.err(3649):     at libcore.net.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:479)
01-14 11:56:31.234: W/System.err(3649):     at twitter4j.internal.http.HttpResponseImpl.<init>(HttpResponseImpl.java:45)
01-14 11:56:31.234: W/System.err(3649):     at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:178)
01-14 11:56:31.234: W/System.err(3649):     at twitter4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:75)
01-14 11:56:31.234: W/System.err(3649):     at twitter4j.internal.http.HttpClientWrapper.get(HttpClientWrapper.java:103)
01-14 11:56:31.238: W/System.err(3649):     at twitter4j.Twitter.getAccountSettings(Twitter.java:1440)
01-14 11:56:31.238: W/System.err(3649):     at com.recipe.pack.TwitterUtils.isAuthenticated(TwitterUtils.java:23)
01-14 11:56:31.238: W/System.err(3649):     at com.recipe.pack.RecpieActivity.onClick(RecpieActivity.java:763)
01-14 11:56:31.238: W/System.err(3649):     at android.view.View.performClick(View.java:3511)
01-14 11:56:31.238: W/System.err(3649):     at android.view.View$PerformClick.run(View.java:14105)
01-14 11:56:31.238: W/System.err(3649):     at android.os.Handler.handleCallback(Handler.java:605)
01-14 11:56:31.238: W/System.err(3649):     at android.os.Handler.dispatchMessage(Handler.java:92)
01-14 11:56:31.238: W/System.err(3649):     at android.os.Looper.loop(Looper.java:137)
01-14 11:56:31.242: W/System.err(3649):     at android.app.ActivityThread.main(ActivityThread.java:4424)
01-14 11:56:31.242: W/System.err(3649):     at java.lang.reflect.Method.invokeNative(Native Method)
01-14 11:56:31.242: W/System.err(3649):     at java.lang.reflect.Method.invoke(Method.java:511)
01-14 11:56:31.242: W/System.err(3649):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
01-14 11:56:31.242: W/System.err(3649):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
01-14 11:56:31.246: W/System.err(3649):     at dalvik.system.NativeStart.main(Native Method)

TwitterUtils.java

public static boolean isAuthenticated(SharedPreferences prefs) {

        String token = prefs.getString(OAuth.OAUTH_TOKEN, "");
        String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");

        AccessToken a = new AccessToken(token,secret);
        Twitter twitter = new TwitterFactory().getInstance();
        twitter.setOAuthConsumer(Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET);
        twitter.setOAuthAccessToken(a);

        try {
            twitter.getAccountSettings();
            return true;
        } catch (TwitterException e) {
            return false;
        }
    }

    public static void sendTweet(SharedPreferences prefs,String msg) throws Exception {
        String token = prefs.getString(OAuth.OAUTH_TOKEN, "");
        String secret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");

        AccessToken a = new AccessToken(token,secret);
        Twitter twitter = new TwitterFactory().getInstance();
        twitter.setOAuthConsumer(Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET);
        twitter.setOAuthAccessToken(a);
        twitter.updateStatus(msg);
    }

class where button is implemented:

case R.id.btweet:
            Toast.makeText(this, "Recipe Tweet will be posted on your profile", 5000).show();
            try{
            if (TwitterUtils.isAuthenticated(prefs)) {
                sendTweet();
            } else {
                Intent i = new Intent(getApplicationContext(), PrepareRequestTokenActivity.class);
                i.putExtra("tweet_msg",getTweetMsg());
                startActivity(i);
            }
            }catch(Exception e){
                e.printStackTrace();
            }
            break;
Rohit
  • 490
  • 3
  • 15
  • 1
    This exception is thrown when an application attempts to perform a networking operation on its main thread. Run your code in AsyncTask. More information: http://stackoverflow.com/q/6343166/812269 – Sapan Diwakar Jan 14 '13 at 10:47

2 Answers2

3

You can't use Network actions on main thread, you've got to implement an AsyncTask which does the network actions on its doInBackground method.

Try this on your button:

Toast.makeText(this, "Recipe Tweet will be posted on your profile", 5000).show();
            try{
            if (TwitterUtils.isAuthenticated(prefs)) {
                new AsyncTask<Void,Void,Void>(){

                    protected Void doInBackground(Void... args){
                        sendTweet();
                        return null;
                    }

                }.execute();
            } else {
                Intent i = new Intent(getApplicationContext(), PrepareRequestTokenActivity.class);
                i.putExtra("tweet_msg",getTweetMsg());
                startActivity(i);
            }
            }catch(Exception e){
                e.printStackTrace();
            }
            break;
Charlie-Blake
  • 10,832
  • 13
  • 55
  • 90
  • Also, DO NOT use 5000 as toast length. It doesn't work that way: you have to pass either Toast.LENGTH_SHORT or Toast.LENGTH_LONG. – Charlie-Blake Jan 14 '13 at 10:50
  • Also, do not use getApplicationContext() as the intent context. Instead, use YourActivityName.this. – Charlie-Blake Jan 14 '13 at 10:51
  • If you want to perform any operations on main thread (UI actions) you can perform them by overriding onPreExecute and onPostExecute in your AsyncTask. onPreExecute will be called before doInBackground. onPostExecute will be called after doInBackground. – Charlie-Blake Jan 14 '13 at 10:52
  • Wrap every network call with an AsyncTask. I don't know which methods are actually network calls. Use the Eclipse debugger to find where are you getting your exception, then wrap it in an AsyncTask. – Charlie-Blake Jan 14 '13 at 11:06
  • i do not have any more network calls in my code. Do i need to perform any changes in TwitterUtils.java class. – Rohit Jan 14 '13 at 11:11
  • In which line of your code do you get the exception? Are you getting the same exception with the AsyncTask? – Charlie-Blake Jan 14 '13 at 13:30
-3

write these lines and in oncreate and it will not give you exception

//-----------------Checking thread policy
    int SDK_INT = android.os.Build.VERSION.SDK_INT;
    if (SDK_INT >= 10) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }          
Babar Sanah
  • 533
  • 1
  • 7
  • 13
  • 1
    The exception is there for a good reason. Doing network operations on UI thread is a bad idea and you should be notified of it with an exception. Don't hide your programming errors! – laalto Jun 12 '13 at 06:30
  • said about avoiding exception – Babar Sanah Jun 12 '13 at 10:36
  • 1
    This should never be suggested as a solution. The framework is trying to warn you against doing it and suppressing is in no way useful. – LostPuppy Jun 24 '14 at 00:16