使用异步任务从一个活动下载数据到另一个活动时显示进度条

时间:2014-12-21 21:27:00

标签: android android-asynctask

我正在尝试使用tast.execute(参数).get()使用Async任务将数据加载到对象列表中,但是当我使用它时它不允许显示进度条。它会卡住一段时间,然后填充该数据。

这是我的异步任务

public class GetAllCars extends AsyncTask<String, Void, List<Car>> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(List<Car> result) {
        super.onPostExecute(result);

    }

    @Override
    protected List<Car> doInBackground(String... params) {
        // TODO Auto-generated method stub
        List<Car> cars = new ArrayList<Car>();
        try {
            String result = HttpClient.SendHttpGet(UrlUtils.BASE_URL
                    + UrlUtils.GET_LOCALCARS + params[0]);
            ResponseParser parser = new ResponseParser();

            cars = parser.parseCar(result);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return cars;
    }
}

这是调用异步任务的Activity。

public class ViewCars extends ActionBarActivity {

    ListView mainlist;
    List<Car> list;
    Bitmap bit;
    ImageView cImage;
    Intent intent;

    private ProgressDialog progress;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_cars);
        progress= new ProgressDialog(this);
        Intent i = getIntent();
        String param = Integer.toString(Integer.parseInt(i.getExtras()
                .getString("Location")) + 1);

        try {
            final GetAllCars task = new GetAllCars();
            task.execute(param);
            list = task.get();

            mainlist = (ListView) findViewById(R.id.mainlist);
            mainlist.setAdapter(new carListAdapter(this));
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NumberFormatException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        mainlist.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {

                int carId = (int) id;
                Car car = list.get(carId);
                intent = new Intent(ViewCars.this, ViewCar.class);
                intent.putExtra("CarId", car.getCarId());
                startActivity(intent);
            }

        });
    }

    public void open(View view){
        progress.setMessage("Downloading");
        progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progress.setIndeterminate(true);
        progress.show();
    }

    class carListAdapter extends BaseAdapter {

        Context context;

        carListAdapter(Context c) throws InterruptedException,
                ExecutionException, NumberFormatException, JSONException {
            context = c;
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return list.size();
        }

        @Override
        public Object getItem(int arg0) {
            // TODO Auto-generated method stub
            return list.size();
        }

        @Override
        public long getItemId(int arg0) {
            // TODO Auto-generated method stub
            return arg0;
        }

        @Override
        public View getView(int arg0, View arg1, ViewGroup arg2) {
            // TODO Auto-generated method stub
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View row = inflater.inflate(R.layout.viewcars, arg2, false);
            TextView cName = (TextView) row.findViewById(R.id.cName);
            TextView cCapacity = (TextView) row.findViewById(R.id.cCapacity);
            cImage = (ImageView) row.findViewById(R.id.cPoster);

            Car c = list.get(arg0);
            cName.setText(c.getName().toString());
            cCapacity.setText(Integer.toString(c.getCapacity()));
            /*
             * ImageLoader imgLoader = new ImageLoader(getApplicationContext());
             * imgLoader.DisplayImage(UrlUtils.GET_CAR_IMAGE+c.getCarImage1(),
             * R.drawable.logo, cImage);
             */
            ImageDownloader id = new ImageDownloader();
            try {
                bit = id.execute(UrlUtils.GET_CAR_IMAGE + c.getCarImage1())
                        .get();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ExecutionException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            cImage.setImageBitmap(bit);
            return row;
        }

    }
}

这是第一个调用第二个活动的活动

public class LocalActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_local);

public void findTaxi(View v){

        Intent intent = new Intent(LocalActivity.this,ViewCars.class);
        intent.putExtra("Location",""+spinnerCity.getSelectedItemId());
        intent.putExtra("Date", btnChooseDate.getText().toString());
        startActivity(intent);
    }
}

我想实现一个进度条,向用户显示数据已加载。请帮我解决这个问题...

1 个答案:

答案 0 :(得分:0)

使用ViewCars课程后

private ProgressDialog pDialog

预执行方法:

@Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(ViewCars.this,
                    ProgressDialog.THEME_DEVICE_DEFAULT_DARK);
            pDialog.setTitle("Please wait");
            pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            pDialog.setMessage("Loading data...");
            pDialog.setIndeterminate(true);
            pDialog.setCancelable(false);
            pDialog.setInverseBackgroundForced(true);
            pDialog.show();
        }

然后你的帖子执行:

@Override
        protected void onPostExecute(String result) {
            ListDrawer();
            pDialog.dismiss();
        }

如果您想阻止在用户旋转屏幕时重新创建活动,您可以使用

@Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            if (pDialog.isShowing() && pDialog != null) {
                pDialog.show();
            } else {
                pDialog.dismiss();
            }
        }
        if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            if (pDialog.isShowing() && pDialog != null) {
                pDialog.show();
            } else {
                pDialog.dismiss();
            }
        }
    }

希望它有所帮助!!!