显示进度条在加载列表
现在好了,我承认我是新来使用进度条INFACT我从来没有使用它,但现在我需要使用它 我有一个活动(主)和可同时启动6个新菜单活动。从这些活动中有其加载数据在ListView它需要3-4秒来加载。这活动解析JSON和数据传递到另一个活动的活动。我怎样才能尽快显示进度条用户点击菜单选项,这项活动消失它时,列表将被载入。显示进度条在加载列表
这里是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();
}
}
谢谢!
使用AsyncTask
在后台加载数据同时显示加载指示器。在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 () ;
}
}
}
在你活动的onCreate()
执行AsyncTask
new HeavyWorker().execute();
你可以做到这一点添加一个属性到你的活动:
ProgressDialog dialog;
然后,只需使用此代码来显示您的对话框:
dialog = ProgressDialog.show(this, "Title", "Loading", true);
然后当你想删除它补充一点:
if(dialog!= null && dialog.isShowing())
dialog.dismiss();
还添加到您的onStop这些行(以防万一用户存在活动):
public void onStop()
{
if(dialog!= null && dialog.isShowing())
dialog.dismiss();
super.onStop();
}
对于这种类型的操作,你应该使用AsyncTask
与您可以显示进度对话框,而它加载。
的official tutorial是非常有益的。查看onPostExecute()
方法,了解如何结束您可能拥有的任何类型的进度栏。
希望它可以帮助
好的我承认我需要asynkTask,但我可以将数据从asynkTask类传递到另一个活动?当我通过上面。 –
是的,你可以,在onPostExecute方法中,你可以工作UI操作并且可以将数据传递给其他活动。 – Udaykiran
你应该用的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();
}
}
也许会有所帮助。我用广播接收器在我的应用程序更新的ListView。
public static final String UPDATE_HISTORY_LIST = "com.myapp.update_history_list";
onPostExecute的AsyncTask
@Override
protected void onPostExecute(JSONObject par) {
Intent intent = new Intent(AppSettings.UPDATE_HISTORY_LIST);
LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);
}
接收机在活动
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);
}
布局
<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" />
活动
mList = (ListView)rootView.findViewById(R.id.listView1);
mList.setEmptyView(rootView.findViewById(android.R.id.progress));
这会导致'progress.getialArgumentException:View未附加到'progressDialog.dismiss() '当屏幕方向改变时显示对话框。 – AndreKR