Отображение индикатора выполнения при загрузке списка - PullRequest
2 голосов
/ 17 ноября 2011

Хорошо. Теперь я признаю, что я новичок в использовании индикатора выполнения. Я никогда его не использую, но теперь мне нужно его использовать. У меня есть действие (основное) и меню, которое может начать 6 новых действий. Из этих действий есть действие, которое загружает данные в ListView, загрузка которого занимает 3-4 секунды. Это действие анализирует json и передает данные другому действию. Как я могу показать индикатор выполнения, как только пользователь щелкнет опцию меню для этого действия и исчезнет, ​​когда будет загружен список.

Вот актив

    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();
    }
}

Заранее спасибо !!

Ответы [ 5 ]

6 голосов
/ 17 ноября 2011

Используйте 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();
1 голос
/ 11 января 2014

возможно это поможет. Я использую BroadcastReceiver для обновления 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));
1 голос
/ 17 ноября 2011

Для этого типа операций вы должны использовать AsyncTask, чтобы вы могли показывать диалог прогресса, пока он загружается.

Официальное руководство довольно полезно.Изучите метод onPostExecute(), чтобы выяснить, как завершить выполнение любого индикатора прогресса.

Надеюсь, это поможет

1 голос
/ 17 ноября 2011

Вы должны сделать это с 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();
    }

}
0 голосов
/ 17 ноября 2011

Вы можете сделать это, добавив свойство к своей деятельности:

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();
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...