9

I have develop one application.Now i am trying to integrate the twitter in my application.My problem is when i login the application it show "android.os.NetworkOnMainThreadException" "at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)".

Please any one help me thanks...

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.RequestToken;
import twitter4j.conf.ConfigurationBuilder;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class TwitterActivity extends Activity {
    static final String CONSUMER_KEY="my consumer key";
    static final String CONSUMER_SECRETKEY="my secret key";
    Button buttonLoginTwitter;
    SharedPreferences sharedpref;
    Twitter twitter;
    private static RequestToken requestToken;
    static final String TWITTER_CALLBACK_URL = "oauth://t4jsample";
    static final String ISTWITTERLOGIN="isTwitterLogedIn";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_twitter);
        buttonLoginTwitter=(Button)findViewById(R.id.btnidLogin);
        sharedpref=getApplicationContext().getSharedPreferences("mypreference", 0);
        TwitterLogin();
    }
    private void TwitterLogin() {
        buttonLoginTwitter.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                if(!istwitterLogin())
                {
                    ConfigurationBuilder builder = new ConfigurationBuilder();
                    builder.setOAuthConsumerKey(CONSUMER_KEY);
                    builder.setOAuthConsumerSecret(CONSUMER_SECRETKEY);
                    twitter4j.conf.Configuration configuration=builder.build();
                    TwitterFactory factory = new TwitterFactory(configuration);
                    twitter = factory.getInstance();

                        try {
                            requestToken = twitter
                                    .getOAuthRequestToken(TWITTER_CALLBACK_URL);
                            TwitterActivity.this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
                                    .parse(requestToken.getAuthenticationURL())));
                        } catch (TwitterException e) {
                            e.printStackTrace();
                        }
                }
                else {
                    Toast.makeText(getApplicationContext(),"Already Logged into twitter", Toast.LENGTH_LONG).show();
                }
            }
        });
    }
    protected boolean istwitterLogin() {
        return sharedpref.getBoolean(ISTWITTERLOGIN, false);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.twitter, menu);
        return true;
    }

}

When i trying to login i got this error:

  E/AndroidRuntime( 5946): FATAL EXCEPTION: main
E/AndroidRuntime( 5946): android.os.NetworkOnMainThreadException
E/AndroidRuntime( 5946):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
E/AndroidRuntime( 5946):    at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
E/AndroidRuntime( 5946):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
E/AndroidRuntime( 5946):    at java.net.InetAddress.getAllByName(InetAddress.java:214)
E/AndroidRuntime( 5946):    at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
E/AndroidRuntime( 5946):    at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
E/AndroidRuntime( 5946):    at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:341)
E/AndroidRuntime( 5946):    at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
E/AndroidRuntime( 5946):    at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
E/AndroidRuntime( 5946):    at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:315)
E/AndroidRuntime( 5946):    at libcore.net.http.HttpEngine.connect(HttpEngine.java:310)
E/AndroidRuntime( 5946):    at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:289)
E/AndroidRuntime( 5946):    at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:239)
E/AndroidRuntime( 5946):    at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:80)
E/AndroidRuntime( 5946):    at libcore.net.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:188)
E/AndroidRuntime( 5946):    at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:158)
E/AndroidRuntime( 5946):    at twitter4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:65)
E/AndroidRuntime( 5946):    at twitter4j.internal.http.HttpClientWrapper.post(HttpClientWrapper.java:102)
E/AndroidRuntime( 5946):    at twitter4j.auth.OAuthAuthorization.getOAuthRequestToken(OAuthAuthorization.java:121)
E/AndroidRuntime( 5946):    at twitter4j.auth.OAuthAuthorization.getOAuthRequestToken(OAuthAuthorization.java:104)
E/AndroidRuntime( 5946):    at twitter4j.TwitterBaseImpl.getOAuthRequestToken(TwitterBaseImpl.java:276)
E/AndroidRuntime( 5946):    at com.androidhive.twitterconnect.MainActivity.loginToTwitter(MainActivity.java:236)
E/AndroidRuntime( 5946):    at com.androidhive.twitterconnect.MainActivity.access$1(MainActivity.java:223)
E/AndroidRuntime( 5946):    at com.androidhive.twitterconnect.MainActivity$1.onClick(MainActivity.java:123)
E/AndroidRuntime( 5946):    at android.view.View.performClick(View.java:4084)
E/AndroidRuntime( 5946):    at android.view.View$PerformClick.run(View.java:16966)
E/AndroidRuntime( 5946):    at android.os.Handler.handleCallback(Handler.java:615)
E/AndroidRuntime( 5946):    at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime( 5946):    at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime( 5946):    at android.app.ActivityThread.main(ActivityThread.java:4745)
E/AndroidRuntime( 5946):    at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime( 5946):    at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime( 5946):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
E/AndroidRuntime( 5946):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
E/AndroidRuntime( 5946):    at dalvik.system.NativeStart.main(Native Method)
W/ActivityManager(  282):   Force finishing activity com.androidhive.twitterconnect/.MainActivity
D/mobiled--->listener(   76): [Client side (recv_cnt: 3671)]: Data is coming, go to check fd_set.
D/mobiled--->listener(   76): [Client side (recv_cnt: 3671)]: Find a socket with data, unlock and receive.
D/mobiled--->netlink_listener(   76): Going to decode uevent.
Sunil Kumar
  • 7,083
  • 4
  • 31
  • 50
Satheesh
  • 1,712
  • 25
  • 34

4 Answers4

11

you have to check this onCreate() method:

if (android.os.Build.VERSION.SDK_INT > "YOur minimum SDK Version here") {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }

And add permission to manifest..

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Update

android.os.NetworkOnMainThreadException means you are performing your network operation on main thread which it will be blocked. So above solution is to restrict network error. But to overcome with this error you should use AsyncTask or by creating child thread and update your UI in runOnUiThread method which will update UI in that method.

Piyush
  • 24,288
  • 6
  • 40
  • 72
5

This exception is thrown when an application attempts to perform a networking operation on its main thread. Run your code in AsyncTask:

class RetreiveFeedTask extends AsyncTask<String, Void, RSSFeed> {

    private Exception exception;

    protected RSSFeed doInBackground(String... urls) {
        try {
            URL url= new URL(urls[0]);
            SAXParserFactory factory =SAXParserFactory.newInstance();
            SAXParser parser=factory.newSAXParser();
            XMLReader xmlreader=parser.getXMLReader();
            RssHandler theRSSHandler=new RssHandler();
            xmlreader.setContentHandler(theRSSHandler);
            InputSource is=new InputSource(url.openStream());
            xmlreader.parse(is);
            return theRSSHandler.getFeed();
        } catch (Exception e) {
            this.exception = e;
            return null;
        }
    }

    protected void onPostExecute(RSSFeed feed) {
        // TODO: check this.exception 
        // TODO: do something with the feed
    }
}

How to execute the task:

new RetreiveFeedTask().execute(urlToRssFeed);

Don't forget to add this to AndroidManifest.xml file:

<uses-permission android:name="android.permission.INTERNET"/>
shiju B
  • 1,690
  • 10
  • 23
  • in his case, this does not work, as a static reference is used: twitter = factory.getInstance(); – Sonic Oct 09 '15 at 14:57
2

Just add the following code in the oncreate off Activity:

 if (android.os.Build.VERSION.SDK_INT > 8) {
      StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
      StrictMode.setThreadPolicy(policy);
    }
Exceptional
  • 2,936
  • 1
  • 16
  • 24
0

You are making your connection on main thread. All the code in method TwitterLogin() should be written either in a thread or start an Async task.

CodeWarrior
  • 4,675
  • 5
  • 27
  • 43