androidmultithreadingthread-exceptions

Run network task on a separate thread to avoid crash in android api greater than 3


Her is my android code for retieving user tweets from twitter. I d this succesfully in lowerapi versions. How can I be able to do the same thing in asynctask,to avoid network on main thread exception?

public class MainActivity extends ActionBarActivity {

    public Bitmap placeholder;
    Context mContext;
    Twitter mTwitter;
    ListView mListView;

    static String TWITTER_CONSUMER_KEY = "GHGHGJHghghgjhggM";
    static String TWITTER_CONSUMER_SECRET = "jkhKJHjhkjhkHkjhHk38YQXUs";
    static String TWITTER_ACCESS_TOKEN = "343434343434-fAZAMIuwAAKlXgby2rXeyvAnhKJHJHJHjhjHJKHjhjhjhhhJ";
    static String TWITTER_TOKEN_SECRET = "JBKJkjhJHJJHHFDJBJbhjvghdgsxs";


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mListView = (ListView) findViewById(R.id.ListViewId);
        mContext = getApplicationContext();
        mTwitter = getTwitter();

        ArrayList<Tweet> tweets = showTweetsAbout("IntelAndroid");

        ArrayAdapter<Tweet> adapter = new TweetItemAdapter(this, R.layout.listitem, tweets);
        mListView.setAdapter(adapter);
    }


    private Twitter getTwitter() {

        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
        cb.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
        cb.setOAuthAccessToken(TWITTER_ACCESS_TOKEN);
        cb.setOAuthAccessTokenSecret(TWITTER_TOKEN_SECRET);
        cb.setUseSSL(true);
        //cb.setJSONStoreEnabled(true);
        return new TwitterFactory(cb.build()).getInstance();
    }

    private ArrayList<Tweet> showTweetsAbout(String queryString) {

        ArrayList<Tweet> tweets = new ArrayList<Tweet>();
        List<Status> statuses = new ArrayList<Status>();

        try {


        statuses = mTwitter.search(new Query(queryString)).getTweets();
        for (Status s : statuses) {
            Tweet tweet = onStatus(s);
            tweets.add(tweet);
        }

        } catch (TwitterException e) {
            e.printStackTrace();
        }   

        return tweets;

    }

Solution

  • For anyone out there with a similar problem, this worked awesomely well for me. Check

    public class MainActivity extends ActionBarActivity
    {
    
        public Bitmap placeholder;
        Context mContext;
        Twitter mTwitter;
        ListView mListView;
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            mListView = (ListView) findViewById(R.id.ListViewId);
            mContext = getApplicationContext();
            mTwitter = getTwitter();
    
            new NetworkRetrieveTweets(this).execute((Void) null);
    
        }
    
        private Twitter getTwitter() {
    
            ConfigurationBuilder cb = new ConfigurationBuilder();
            cb.setOAuthConsumerKey(Constants.TWITTER_CONSUMER_KEY);
            cb.setOAuthConsumerSecret(Constants.TWITTER_CONSUMER_SECRET);
            cb.setOAuthAccessToken(Constants.TWITTER_ACCESS_TOKEN);
            cb.setOAuthAccessTokenSecret(Constants.TWITTER_TOKEN_SECRET);
            cb.setUseSSL(true);
    
            return new TwitterFactory(cb.build()).getInstance();
        }
    
        private ArrayList<Tweet> showTweetsAbout(String queryString) {
    
            ArrayList<Tweet> tweets = new ArrayList<Tweet>();
            List<Status> statuses = new ArrayList<Status>();
    
            try {
    
                statuses = mTwitter.search(new Query(queryString)).getTweets();
                for (Status s : statuses) {
                    Tweet tweet = onStatus(s);
                    tweets.add(tweet);
                }
    
            } catch (TwitterException e) {
                e.printStackTrace();
            }
    
            return tweets;
    
        }
    
        public Tweet onStatus(Status status) {
    
            User user = status.getUser();
    
            String image_url = user.getBiggerProfileImageURL();
    
            String username = user.getScreenName();
    
            String userLocation = user.getLocation();
    
            Date createdAt = status.getCreatedAt();
    
            long tweetId = status.getId();
    
            String message = status.getText();
    
            Tweet tweet = new Tweet(username, message, image_url, tweetId);
    
            return tweet;
    
        }
    
        public class NetworkRetrieveTweets extends AsyncTaskEx<Void, Void, ArrayList<Tweet>> {
    
            Context context;
            ProgressDialog mDialog;
    
            public NetworkRetrieveTweets(Context c) {
                this.context = c;
    
                mDialog = ProgressDialog.show(c, "", getString(R.string.loading), true, false);
                mDialog.setCancelable(true);
            }
    
            @Override
            public void onPreExecute() {
    
                /**
                 * show dialog
                 */
                super.onPreExecute();
    
            }
    
    
            @Override
            protected ArrayList<Tweet> doInBackground(Void... params) {
    
                /**
                 * Do network related stuff
                 * return string response.
                 */
    
                ArrayList<Tweet> tweets = showTweetsAbout("IntelAndroid");
    
                return tweets;
            }
    
            @Override
            protected void onPostExecute(ArrayList<Tweet> tweets) {
    
                /**
                 * update ui thread and remove dialog
                 */
                super.onPostExecute(tweets);
    
                conVenience(tweets);
    
                if(mDialog.isShowing()) {
                    try {
                        mDialog.dismiss();
                    } catch (Exception e) { //This occasionally fails
                        e.printStackTrace();
                    }
                }
    
            }
        }
    
        public void conVenience(ArrayList<Tweet> tweets) {
            ArrayAdapter<Tweet> adapter = new TweetItemAdapter(this, R.layout.listitem, tweets);
            mListView.setAdapter(adapter);
        }
    
    }