Skip to content Skip to sidebar Skip to footer

Getting Networkonmainthreadexception While Integrating Twitter Api In Android

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 hig

Solution 1:

Try this:

Replace this code:

if (TwitterUtils.isAuthenticated(prefs)) {

With the following:

newAsyncTask<SharedPreferences,Object, Boolean>() {

        @OverrideprotectedBooleandoInBackground(SharedPreferences... params) {
            returnTwitterUtils.isAuthenticated(params[0]);
        }

        @OverrideprotectedvoidonPostExecute(Boolean isAuthenticated) {
            if (isAuthenticated) {
                // Do processing after successful authenticationsendTweet();
            }
            else {
                // Do processing after authentication failureIntent i = newIntent(getApplicationContext(), PrepareRequestTokenActivity.class);
                    i.putExtra("tweet_msg",getTweetMsg());
                    startActivity(i);
            }
        }
    }.execute(prefs);

Solution 2:

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

                    protectedVoid doInBackground(Void... args){
                        sendTweet();
                        returnnull;
                    }

                }.execute();
            } else {
                Intent i = new Intent(getApplicationContext(), PrepareRequestTokenActivity.class);
                i.putExtra("tweet_msg",getTweetMsg());
                startActivity(i);
            }
            }catch(Exception e){
                e.printStackTrace();
            }
            break;

Solution 3:

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

//-----------------Checking thread policyintSDK_INT= android.os.Build.VERSION.SDK_INT;
    if (SDK_INT >= 10) {
        StrictMode.ThreadPolicypolicy=newStrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }          

Post a Comment for "Getting Networkonmainthreadexception While Integrating Twitter Api In Android"