public class MainActivity extends Activity {
TextView statustv = (TextView) findViewById(R.id.status);;
ProgressDialog pd;
String status, url = "http://wvde.state.wv.us/closings/county/monongalia";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new School().execute();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private class School extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(MainActivity.this);
pd.setTitle("Android Basic JSoup Tutorial");
pd.setMessage("Loading...");
pd.setIndeterminate(false);
pd.show();
}
@Override
protected Void doInBackground(Void... params) {
try {
Document doc = Jsoup.connect(url).get();
Elements table = doc.select("td#content_body");
status = table.select("table").text();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
statustv.setText(status);
pd.dismiss();
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_refresh) {
new School().execute();
return true;
}
return super.onOptionsItemSelected(item);
}
}
如何在没有得到nullpointer错误的情况下发生new School().execute();
oncreate,因为现在当oncreate执行时它会在它甚至知道asynchtask是什么之前执行new School().execute();
。我怎样才能正确执行oncreate?
答案 0 :(得分:0)
您可以将runnable发布到当前线程的处理程序。 runnable启动AsyncTask。 以下是使用处理程序的简单示例:https://stackoverflow.com/a/1921759/1843698
Handler官方文档:http://developer.android.com/reference/android/os/Handler.html 处理程序在当前线程中安排一个任务(你的runnable),你的任务将在稍后的同一个线程中执行,但它将在onCreate()完成后执行。