简体   繁体   English

加载列表时显示进度条

[英]Showing progress bar while loading a List

Ok Now i admit that i am new to using progress bar infact i never use it but now i need to use it I have an activity (Main) and a menu which can start 6 new activity. 好的我现在承认我是新手使用进度条我从不使用它但现在我需要使用它我有一个活动(主)和一个菜单,可以启动6个新的活动。 From these activities there is an activity which load the data in a ListView it take 3-4 second to load .This activity parse the json and pass the data to another activity. 从这些活动中有一个活动,它在ListView中加载数据需要3-4秒才能加载。这个活动解析json并将数据传递给另一个活动。 How can i show the progress bar as soon as user click the menu option for this activity and disappear it when List will be loaded. 如果用户单击此活动的菜单选项,我将如何显示进度条,并在加载列表时将其消失。

Here is the activiy 这是活动

    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
     final Intent intent=new Intent(this ,GetLatAndLng.class);
    setContentView(R.layout.listplaceholder);
    //ProgressBar pb=(ProgressBar)findViewById(R.id.progressbar);
    LocationManager locationManager;
    String context=Context.LOCATION_SERVICE;
    locationManager=(LocationManager)getSystemService(context);

    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    criteria.setAltitudeRequired(false);
    criteria.setBearingRequired(false);
    criteria.setCostAllowed(true);
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    String provider = locationManager.getBestProvider(criteria, true);
    Location location = locationManager.getLastKnownLocation(provider);

    final LocationListener locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
        updateWithNewLocation(location);
        }
        public void onProviderDisabled(String provider){
        updateWithNewLocation(null);
        }
        public void onProviderEnabled(String provider){ }
        public void onStatusChanged(String provider, int status,
        Bundle extras){ }
        };
    updateWithNewLocation(location);
    locationManager.requestLocationUpdates(provider, 2000, 10,
            locationListener);
    double geoLat = location.getLatitute();
    double geoLng = location.getLongitude();
         Bundle b=new Bundle();
    //pb.setVisibility(View.VISIBLE);
    ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();

    JSONObject json = JSONFunction.getJSONfromURL(getUrl());
    Log.v(TAG, "got the json"); 
    try{
        JSONArray  JArray = json.getJSONArray("results");
           Log.v(TAG, "getting results");
        for(int i=0;i<JArray.length();i++){                     
            HashMap<String, String> map = new HashMap<String, String>();    
            JSONObject e = JArray.getJSONObject(i);
            JSONObject location1=e.getJSONObject("geometry").getJSONObject("location");
            latitude[i]=location1.getDouble("lat");
            longitude[i]=location1.getDouble("lng");
            reference[i]=e.getString("reference");
            Log.v(TAG, reference[i]);
            distance[i]=GetLatAndLng.gps2m(geoLat, geoLng,latitude[i] ,longitude[i]); 
            map.put("id",  String.valueOf(i));
            map.put("name", "" + e.getString("name"));
            map.put("vicinity", "Address " +  e.getString("vicinity")+" "+"Disance:"+distance[i]);

            mylist.add(map);                
        }           
    }catch(JSONException e)        {
         Log.e("log_tag", "Error parsing data "+e.toString());
    }
//   pb.setVisibility(View.GONE);
    b.putStringArray("key", reference);
    intent.putExtras(b);
    Log.v(TAG, ""+reference); 
    ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.listview, 
                    new String[] { "name", "vicinity", }, 
                    new int[] { R.id.item_title, R.id.item_subtitle });

    setListAdapter(adapter);
    final ListView lv = getListView();
    lv.setTextFilterEnabled(true);  
    lv.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {        
            @SuppressWarnings("unchecked")
            HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);                   
           Toast.makeText(JsonExampleActivity.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show();
            intent.putExtra("clickedid",position);
            startActivity(intent);
        }
    });
}
public void updateWithNewLocation(Location location2) {
    if(location2!=null) {
          double geoLat = location2.getLatitude();
            double geoLng = location2.getLongitude();
    }
}

Thanks in Advance!! 提前致谢!!

Use AsyncTask to load data in background while showing loading indicator. 使用AsyncTask在后台加载数据,同时显示加载指示符。 In AsyncTask's doInBackground method , process the JSON or anything which is taking time. AsyncTask's doInBackground方法中,处理JSON或任何花费时间的事情。

public class HeavyWorker extends AsyncTask < String , Context , Void > {

    private ProgressDialog      progressDialog ;
    private Context             targetCtx ;

    public HeavyWorker ( Context context ) {
        this.targetCtx = context ;
        this.needToShow = true;
        progressDialog = new ProgressDialog ( targetCtx ) ;
        progressDialog.setCancelable ( false ) ;
        progressDialog.setMessage ( "Retrieving data..." ) ;
        progressDialog.setTitle ( "Please wait" ) ;
        progressDialog.setIndeterminate ( true ) ;
    }

    @ Override
    protected void onPreExecute ( ) {
        progressDialog.show ( ) ;
    }

    @ Override
    protected Void doInBackground ( String ... params ) {
      // Do Your WORK here

       return null ;
    }

    @ Override
    protected void onPostExecute ( Void result ) {
        if(progressDialog != null && progressDialog.isShowing()){
            progressDialog.dismiss ( ) ;
        }
    }
}

In your Activity's onCreate() execute AsyncTask 在Activity的onCreate()执行AsyncTask

new HeavyWorker().execute();

maybe it will help. 也许它会有所帮助。 I use BroadcastReceiver to update ListView in my app. 我使用BroadcastReceiver在我的应用程序中更新ListView。

public static final String UPDATE_HISTORY_LIST = "com.myapp.update_history_list";

onPostExecute AsyncTask onPostExecute AsyncTask

@Override
    protected void onPostExecute(JSONObject par) {
        Intent intent = new Intent(AppSettings.UPDATE_HISTORY_LIST);
        LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);
    }

Receiver in Activity 活动中的接收者

private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
          @Override
          public void onReceive(Context context, Intent intent) {
              Log.i(TAG, "Action: " + intent.getAction());
              if (AppSettings.UPDATE_HISTORY_LIST.equals(intent.getAction())) {
                  OrderHistoryFragment history = (OrderHistoryFragment)getFragmentManager().findFragmentByTag("history");
                  if(history != null && history.isVisible()){
                      history.refresh();
                  }
              }
          }
    };
    @Override
    protected void onPause() {
        Log.i(TAG, "onPause");
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
        super.onPause();
    }

    @Override
    protected void onResume() {
        Log.i(TAG, "onResume");
        super.onResume();
        LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
        IntentFilter filter = new IntentFilter();
        filter.addAction(AppSettings.UPDATE_HISTORY_LIST);
        lbm.registerReceiver(mMessageReceiver, filter);
    }

Layout 布局

<ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
</ListView>
<ProgressBar
        android:id="@android:id/progress"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:indeterminate="true" />

Activity 活动

mList = (ListView)rootView.findViewById(R.id.listView1);
mList.setEmptyView(rootView.findViewById(android.R.id.progress));

For this type of operations, you should use AsyncTask with that you can show progress dialog , while it loads. 对于这种类型的操作,您应该使用AsyncTask ,以便在加载时显示进度对话框。

The official tutorial is pretty helpful. 官方教程非常有帮助。 Look into the onPostExecute() method to figure out how to end any sort of progress bar you may have. 查看onPostExecute()方法以了解如何结束您可能拥有的任何类型的进度条。

Hope it helps 希望能帮助到你

You should do it with an AsyncTask and show a progress dialog in the onPreExecuteMethod and dismiss it on onPostExecute: 您应该使用AsyncTask执行此操作并在onPreExecuteMethod中显示进度对话框并在onPostExecute上将其关闭:

class MyAsyncTask extends AsyncTask<String,Void,Object> {
    ProgressDialog pd;
    Context context;
    public MyAsyncTask(Context c) {
        context = c;
    }
    @Override
    protected void onPreExecute() {
        pd = ProgressDialog.show(context, "Loading", "Wait", true, true);
        pd.setOnCancelListener(new OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                finish();
            }
        });
    }
    @Override
    protected Object doInBackground(String... params) {
        return null;
    }

    @Override
    protected void onPostExecute(Object result) {
        if(pd.isShowing())
            pd.dismiss();
    }

}

You can do that adding a property to your Activity: 您可以这样做,为您的活动添加一个属性:

ProgressDialog dialog;

Then just use this code to show your dialog: 然后使用此代码显示您的对话框:

dialog = ProgressDialog.show(this, "Title", "Loading", true);

And then add this when you want to delete it: 然后在要删除它时添加它:

if(dialog!= null && dialog.isShowing())
   dialog.dismiss();

Also add to your onStop those lines (just in case the user exists the Activity): 还要在onStop上添加这些行(以防万一用户存在Activity):

public void onStop()
{
    if(dialog!= null && dialog.isShowing())
       dialog.dismiss();
    super.onStop();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM