【发布时间】:2014-12-29 18:18:40
【问题描述】:
我正在尝试构建一个 RSS 阅读器并将 rss 提要获取作为 ansyctask, 在列表视图中返回一个提要,或返回一个文本视图说“没有互联网连接” 但是应用还是崩溃了,不知道怎么回事,请帮忙看看。
代码如下:
package rss;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.TextView;
import com.enporan.polytechoran.R;
public class RSSActivity extends ActionBarActivity {
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
rssfeedget alpha = new rssfeedget();
alpha.execute();
}
private class rssfeedget extends AsyncTask<String, Void, FeedSource> {
protected void onPreExecute() {
}
@Override
protected FeedSource doInBackground(String... params) {
FeedSource f = new HttpFeedSource();
if(f!=null)
return f;
else {
return null;
}
}
@Override
protected void onPostExecute(FeedSource result){
ListView rssItemList = (ListView) findViewById(R.id.rssListview);
rssItemList.setVerticalFadingEdgeEnabled(true);
if(doInBackground()==null){
TextView tv= (TextView) findViewById(R.id.textView2);
tv.setText("No internet Connection...");
}
else{
RSSItemAdapter adapter = new RSSItemAdapter(getApplicationContext(), R.layout.rssitem, doInBackground().getFeed());
rssItemList.setAdapter(adapter);
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_news, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
【问题讨论】:
-
你得到什么样的异常? (我猜是networkonmainthread异常)
-
@coelho :由于网络代码在 AsyncTask 中执行,因此不应附加 NetworkOnMainThreadException。 Larbi :您能否在您的帖子中添加堆栈跟踪以便我们为您提供帮助?
-
@chteuchteu 这里是错误:
-
12-29 20:08:33.902 22681-22681/com.enporan.polytechoran E/AndroidRuntime:致命异常:主进程:com.enporan.polytechoran,PID:22681 java.lang.RuntimeException: android.os.NetworkOnMainThreadException at rss.NewsParser.parse(NewsParser.java:52) at rss.HttpFeedSource.getFeed(HttpFeedSource.java:17)
-
告诉你。问题是您必须仅在 doInBackground 方法中使用网络通信,并且您在 onPostExecute 方法中使用它。
标签: android android-asynctask rss