进度条动画到延迟加载列表视图

时间:2015-04-02 18:47:02

标签: android lazy-loading

我在我的应用程序中使用延迟加载,我想显示加载动画或进度条或任何内容,直到内容从远程服务器加载,只是告诉用户该页面不是空白或正在构建中。这是我的活动,请告诉我让用户等到内容加载的解决方案。

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.hotel_listview);

    // URL to the XML data
    String strUrl = "http://xxx.php";

    // Creating a new non-ui thread task to download xml data
    DownloadTask downloadTask = new DownloadTask();

    // Starting the download process
    downloadTask.execute(strUrl);
    if (!isOnline(this)) {
        showDialog(DIALOG_ERROR_CONNECTION); //displaying the created dialog.
    } else {
        //Internet available. Do what's required when internet is available.
    }



}
public boolean isOnline(Context c) {
    ConnectivityManager cm = (ConnectivityManager) c
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo ni = cm.getActiveNetworkInfo();

    if (ni != null && ni.isConnected())
        return true;
    else
        return false;
}
@Override
protected Dialog onCreateDialog(int id) {
    Dialog dialog = null;
    switch (id) {
        case DIALOG_ERROR_CONNECTION:
            AlertDialog.Builder errorDialog = new AlertDialog.Builder(this);
            errorDialog.setTitle("Error");
            errorDialog.setMessage("Connection Error....!");
            errorDialog.setNeutralButton("OK",
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.dismiss();
                        }
                    });

            AlertDialog errorAlert = errorDialog.create();
            return errorAlert;

        default:
            break;
    }
    return dialog;
}
/** A method to download xml data from url */
private String downloadUrl(String strUrl) throws IOException{
    String data = "";
    InputStream iStream = null;
    try{
        URL url = new URL(strUrl);

        // Creating an http connection to communicate with url
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        // Connecting to url
        urlConnection.connect();

        // Reading data from url
        iStream = urlConnection.getInputStream();

        BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

        StringBuffer sb  = new StringBuffer();

        String line = "";
        while( ( line = br.readLine())  != null){
            sb.append(line);
        }

        data = sb.toString();

        br.close();

    }catch(Exception e){
        Log.d("Exception while downloading url", e.toString());
    }finally{
        iStream.close();
    }
    return data;
}

/** AsyncTask to download xml data */
private class DownloadTask extends AsyncTask<String, Integer, String>{
    String data = null;
    @Override
    protected String doInBackground(String... url) {
        try{
            data = downloadUrl(url[0]);
        }catch(Exception e){
            Log.d("Background Task",e.toString());
        }
        return data;
    }

    @Override
    protected void onPostExecute(String result) {
        if (result != null) {
        // The parsing of xml data is done in a non-ui thread
        ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask();

        // Start parsing xml data
        listViewLoaderTask.execute(result);
    }}
}

/** AsyncTask to parse xml data and load ListView */
private class ListViewLoaderTask extends AsyncTask<String, Void, SimpleAdapter>{

    StringReader reader;

    // Doing the parsing of xml data in a non-ui thread
    @Override
    protected SimpleAdapter doInBackground(String... strXml) {
        try{
            reader = new StringReader(strXml[0]);
        }catch(Exception e){
            Log.d("XML Exception1",e.toString());
        }

        // Instantiating xml parser class
        HotelListParser hotelListParser = new HotelListParser();

        // A list object to store the parsed countries list
        List<HashMap<String, Object>> hotelList = null;

        try{
            // Getting the parsed data as a List construct
            hotelList = hotelListParser.parse(reader);
        }catch(Exception e){
            Log.d("Exception",e.toString());
        }

        // Keys used in Hashmap
        String[] from = { "hotel","photo","rupees","review","distance"};

        // Ids of views in listview_layout
        int[] to = { R.id.tv_hotelName,R.id.iv_photo,R.id.tv_rupees,R.id.tv_review,R.id.tv_distance};

        // Instantiating an adapter to store each items
        // R.layout.listview_layout defines the layout of each item
        SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), hotelList, R.layout.hotel_listview_layout, from, to);

        return adapter;
    }

    /** Invoked by the Android when "doInBackground" is executed */
    @Override
    protected void onPostExecute(SimpleAdapter adapter) {
        // Setting adapter for the listview
        mListView.setAdapter(adapter);

        for(int i=0;i<adapter.getCount();i++){
            HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(i);
            String imgUrl = (String) hm.get("photo_path");
            ImageLoaderTask imageLoaderTask = new ImageLoaderTask();

            HashMap<String, Object> hmDownload = new HashMap<String, Object>();
            hm.put("photo_path",imgUrl);
            hm.put("position", i);

            // Starting ImageLoaderTask to download and populate image in the listview
            imageLoaderTask.execute(hm);
        }


    }
}

/** AsyncTask to download and load an image in ListView */
private class ImageLoaderTask extends AsyncTask<HashMap<String, Object>, Void, HashMap<String, Object>>{

    @Override
    protected HashMap<String, Object> doInBackground(HashMap<String, Object>... hm) {

        InputStream iStream=null;
        String imgUrl = (String) hm[0].get("photo_path");
        int position = (Integer) hm[0].get("position");

        URL url;
        try {
            url = new URL(imgUrl);

            // Creating an http connection to communicate with url
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

            // Connecting to url
            urlConnection.connect();

            // Reading data from url
            iStream = urlConnection.getInputStream();

            // Getting Caching directory
            File cacheDirectory = getBaseContext().getCacheDir();

            // Temporary file to store the downloaded image
            File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"+position+".png");

            // The FileOutputStream to the temporary file
            FileOutputStream fOutStream = new FileOutputStream(tmpFile);

            // Creating a bitmap from the downloaded inputstream
            Bitmap b = BitmapFactory.decodeStream(iStream);

            // Writing the bitmap to the temporary file as png file
            b.compress(Bitmap.CompressFormat.PNG,100, fOutStream);

            // Flush the FileOutputStream
            fOutStream.flush();

            //Close the FileOutputStream
            fOutStream.close();

            // Create a hashmap object to store image path and its position in the listview
            HashMap<String, Object> hmBitmap = new HashMap<String, Object>();

            // Storing the path to the temporary image file
            hmBitmap.put("photo",tmpFile.getPath());

            // Storing the position of the image in the listview
            hmBitmap.put("position",position);

            // Returning the HashMap object containing the image path and position
            return hmBitmap;

        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(HashMap<String, Object> result) {
        if (result != null) {
            // Getting the path to the downloaded image
            String path = (String) result.get("photo");

        // Getting the position of the downloaded image
        int position = (Integer) result.get("position");

        // Getting adapter of the listview
        SimpleAdapter adapter = (SimpleAdapter ) mListView.getAdapter();

        // Getting the hashmap object at the specified position of the listview
        HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(position);

        // Overwriting the existing path in the adapter
        hm.put("photo",path);

        // Noticing listview about the dataset changes
        adapter.notifyDataSetChanged();
    }}
}



@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

} `

1 个答案:

答案 0 :(得分:0)

显示和隐藏的进度对话框方法。 您可以在onPreExecute()中编写代码以显示onPostExecute()以隐藏进度对话框。

    ProgressDialog barProgressDialog;

    public void showHideProgressDialog(boolean status){
           if(barProgressDialog==null){
              barProgressDialog = new ProgressDialog(YourActivity.this);
              barProgressDialog.setTitle("Title");
              barProgressDialog.setMessage("Your Message");
           }

      if(status){
         barProgressDialog.show();
      }else{
         barProgressDialog.dismiss();
      }
    }

AsyncTask方法。

public void onPreExecute(...){
  showHideProgressDialog(true)
  ..
}

public void onPostExecute(...){
  showHideProgressDialog(false)
  ...
}

建议:仅在设备具有数据连接时执行http内容

.....

     DownloadTask downloadTask = new DownloadTask();

    // dont call http stuff here   
    //downloadTask.execute(strUrl);
    if (!isOnline(this)) {
        showDialog(DIALOG_ERROR_CONNECTION); //displaying the created dialog.
    } else {
        //Internet available. Do what's required when internet is available.
        downloadTask.execute(strUrl);
    }
....