public Asynk startThread(ListView listView, ProgressBar progressBar, TextView textView) { Asynk asyncThread = new Asynk(listView, progressBar, textView); asyncThread.setOnCompleteListener( new Asynk.OnComplete() { @Override public void onIncrement(ProgressBar progressBar, TextView textView, int i) { progressBar.setProgress(i); textView.setText("" + i); } @Override public void completed( ListView listView, ProgressBar progressBar, TextView textView, ArrayList<String> items) { ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, items); frag.setArrayList(items); listView.setAdapter(adapter); progressBar.setVisibility(View.GONE); textView.setVisibility(View.GONE); } }); asyncThread.execute(); return asyncThread; }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView = (ListView) findViewById(R.id.listView); textView = (TextView) findViewById(R.id.textView); progressBar = (ProgressBar) findViewById(R.id.progress); fManager = getSupportFragmentManager(); frag = (MyFragment) fManager.findFragmentByTag(MyFragment.TAG); if (null != frag) { // screen was rotated ArrayList<String> items = frag.getArrayList(); if (null == items) { // the async task has not yet finished, grab it from the fragment and reset the references // to the views Asynk asyncThread = frag.getAsynk(); asyncThread.setAll(listView, progressBar, textView); } else { // the async task has finished, set list adapter ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, items); listView.setAdapter(adapter); progressBar.setVisibility(View.GONE); textView.setVisibility(View.GONE); } } else { // initial setup, first time onCreate is run. progressBar.setProgress(0); // start the long running operation on the background thread. Asynk asyncThread = startThread(listView, progressBar, textView); frag = new MyFragment(); frag.setAsynk( asyncThread); // keep the asyncTask in the fragment, the fragment will not be destroyed // when we rotate the screen, the activity will be though. fManager.beginTransaction().add(frag, MyFragment.TAG).commit(); } }