我想建立一個RSS閱讀器,並把RSS提要獲取作爲ansyctask, ,返回列表視圖中的飼料,或返回一個文本視圖,說「沒有互聯網連接」 但應用程序仍然崩潰,我不知道有什麼問題,請你幫忙。Android AsyncTask活動崩潰RSS閱讀器
這裏是代碼:
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);
}
}
你會得到什麼樣的例外? (我猜這是一個networkonmainthreadexception) – viplezer
@coelho:由於網絡代碼是在AsyncTask中執行的,因此不應該追加NetworkOnMainThreadException。 Larbi:你可以在你的文章中添加堆棧跟蹤,這樣我們可以幫助你嗎? – chteuchteu
@chteuchteu這裏是錯誤: –