-1

她是我的 android 代码,用于从 twitter 检索用户推文。我在lowerapi版本中成功地做到了这一点。我怎样才能在异步任务中做同样的事情,以避免主线程异常的网络?

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;

    }
4

2 回答 2

0

与此类似的东西应该可以工作,尽管我还没有验证编译:

public class MainActivity extends ActionBarActivity
{

    public Bitmap placeholder;
    Context mContext;
    Twitter mTwitter;
    ListView mListView;
    ArrayList<Tweet> mTweets;
    ArrayAdapter<Tweet> mAdapter;

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

        showTweetsAbout("IntelAndroid");
    }


    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 void showTweetsAbout(String queryString)
    {
        new AsyncTask<Void, Void, Void>()
        {
            List<Status> statuses = new ArrayList<Status>();

            @Override
            protected Void doInBackground(Void... voids)
            {
                try
                {
                    statuses = mTwitter.search(new Query(queryString)).getTweets();
                    for (Status s : statuses)
                    {
                        Tweet tweet = onStatus(s);
                        mTweets.add(tweet);
                    }
                }
                catch (TwitterException e)
                {
                    e.printStackTrace();
                }

                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid)
            {
                super.onPostExecute(aVoid);

                mAdapter = new TweetItemAdapter(this, R.layout.listitem, tweets);
                mListView.setAdapter(adapter);
            }
        }.execute();
    }
}
于 2014-07-12T00:10:37.177 回答
0

对于任何有类似问题的人来说,这对我来说效果非常好。查看

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);
    }

}
于 2014-07-12T01:14:56.580 回答