使用 twitter4j 库发布最后一条推文 - AsyncTask 应该在哪里实现?



我的代码很简单:从我的主页检索最后一条推文,然后在我的应用程序的Textview字段中发布。

public void lastTwitterpost() throws TwitterException
{
webView=(TextView) findViewById(R.id.webview);
ConfigurationBuilder cf = new ConfigurationBuilder();
cf.setDebugEnabled(true)
.setOAuthConsumerKey("YYOkYp9G85lFxfXZPQAWcjAmX")
.setOAuthConsumerSecret("TLZrCAgeiuCbN6WOoUzO6e0hfWySA01PEOK1KPEH6yB8kxEYSz ")
.setOAuthAccessToken("4188976763-zVUUUMwEKvBD6J9mE3tiscaKQD85vWRkIyPdqBl")
.setOAuthAccessTokenSecret("K1neDCJq9shWhBxxU6otD4PCU4HJObd8lch3X4XsRq5ew ");
TwitterFactory tf = new TwitterFactory(cf.build());
twitter4j.Twitter twitter = tf.getInstance();

Log.d(TAG, "main: tweets messages:");
int totalTweets = 1 ;// no of tweets to be fetched
Paging paging = new Paging(1, totalTweets);
List tweets = twitter.getHomeTimeline(paging);
webView.setText(tweets.toString());
}

但是我收到以下错误:

FATAL EXCEPTION: main  Process: com.example.android.bluesky, PID: 8320
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.bluesky/com.example.android.bluesky.Search.SearchActivity}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2406)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2466)
at android.app.ActivityThread.access$1200(ActivityThread.java:152)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1341)

我该如何处理它?

你应该使用AsyncTask或nay ither库,但由于你是初学者,那么我建议你现在异步任务。 我正在提供解决方案,但您必须了解 AsyncTask 的工作原理

public class FetchData extends AsyncTask<Void,Void,List>{
@Override
protected void onPreExecute() {
super.onPreExecute();
// this will run first and you can perform any ui based task like showing progress bar here
webView=(TextView) findViewById(R.id.webview);
}
@Override
protected List doInBackground(Void... voids) {
// this will run after pro execute and it will run  on another thread and you can not perform any ui based task here

ConfigurationBuilder cf = new ConfigurationBuilder();
cf.setDebugEnabled(true)
.setOAuthConsumerKey("YYOkYp9G85lFxfXZPQAWcjAmX")
.setOAuthConsumerSecret("TLZrCAgeiuCbN6WOoUzO6e0hfWySA01PEOK1KPEH6yB8kxEYSz ")
.setOAuthAccessToken("4188976763-zVUUUMwEKvBD6J9mE3tiscaKQD85vWRkIyPdqBl")
.setOAuthAccessTokenSecret("K1neDCJq9shWhBxxU6otD4PCU4HJObd8lch3X4XsRq5ew ");
TwitterFactory tf = new TwitterFactory(cf.build());
twitter4j.Twitter twitter = tf.getInstance();

Log.d(TAG, "main: tweets messages:");
int totalTweets = 1 ;// no of tweets to be fetched
Paging paging = new Paging(1, totalTweets);
List tweets = twitter.getHomeTimeline(paging);

return tweets;
}
@Override
protected void onPostExecute(List result) {
super.onPostExecute(result);
// this will run at last after doInBackground and you can perform any ui based task like showing progress bar here
webView.setText(result.toString());
}
}

现在lastTwitterpost()呼叫替换为new FetchData().execute()

最新更新