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

}

How can I have new School().execute(); happen oncreate without getting a nullpointer error because right now when oncreate executes it executes new School().execute(); before it even knows what the asynchtask is. How can i have it execute correctly oncreate?

Hasan
  • 200
  • 2
  • 12

1 Answers1

0

You can post a runnable to the current thread's handler. The runnable starts the AsyncTask. Here is an easy example of using handler: https://stackoverflow.com/a/1921759/1843698

Official Doc for Handler: http://developer.android.com/reference/android/os/Handler.html The handler schedule a task (your runnable) in current thread, and your task will be executed later in the same thread as soon as possible, but it will be executed after onCreate() finishes.

Community
  • 1
  • 1
Kaifei
  • 1,568
  • 2
  • 13
  • 16
  • When I tried that I got an error "Cannot make a static reference to the non-static method postDelayed(Runnable, long) from the type Handler" – Hasan Jul 14 '14 at 15:45
  • You should initialize a handler: *Handler handler = new Handler();* Then call *handler.postDelayed()*. Handler is the class, and handler is one instance of it. Ref: http://stackoverflow.com/a/6550537/1843698 – Kaifei Jul 14 '14 at 19:49