Il Forum è consultabile solo in modalità lettura. Per domande o consigli iscriviti al nostro GRUPPO FACEBOOK / COMMUNITY cliccando qui

Problema sincronizzazione thread principale con thread secondario

Discussione in 'Development' iniziata da giupardeb, 4 Ago 2015.

  1. giupardeb

    giupardeb Baby Droid

    Iscritto:
    26 Lug 2010
    Messaggi:
    13
    "Mi Piace":
    0
    Buongiorno ragazzi, da circa due giorni sto impazzendo con questo problema. Vorrei che la mia applicazione recuperi le coordinate gps e determini la località in cui mi trovo, fatto ciò deve salvare questa località in un'altra variabile e all'interno di un arrayLIst. Ecco il codice:

    LocationAddress, usata per determinare la località

    Codice:
    public class LocationAddress {
    
        private static final String TAG = "LocationAddress";
    
        public static void getAddressFromLocation(final double latitude, final double longitude,
                                                  final Context context, final Handler handler) {
            Thread thread = new Thread() {
                    [USER=106217]Override[/USER]
                public void run() {
                    Geocoder geocoder = new Geocoder(context, Locale.getDefault());
                    String result = null;
                    try {
                        List<Address> addressList = geocoder.getFromLocation(latitude, longitude, 1);
    
                        if (addressList != null && addressList.size() > 0) {
                            Address address = addressList.get(0);
                            StringBuilder sb = new StringBuilder();
                            for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
                                sb.append(address.getAddressLine(i)).append("\n");
                            }
                            //   sb.append(address.getLocality()).append("\n");
                            //   sb.append(address.getPostalCode()).append("\n");
                            //   sb.append(address.getCountryName());
                            //   result = sb.toString();
                            result = address.getLocality();
                        }
                    } catch (IOException e) {
                        Log.e(TAG, "Unable connect to Geocoder", e);
                    } finally {
                        Message message = Message.obtain();
                        message.setTarget(handler);
                        if (result != null) {
                            message.what = 1;
                            Bundle bundle = new Bundle();
                            //result = "Latitude: " + latitude + " Longitude: " + longitude +"\n\nAddress:\n" + result;
                            bundle.putString("address", result);
                            message.setData(bundle);
                        } else {
                            message.what = 1;
                            Bundle bundle = new Bundle();
                            //result = "Latitude: " + latitude + " Longitude: " + longitude +"\n Unable to get address for this lat-long.";
                            bundle.putString("address", result);
                            message.setData(bundle);
                        }
                        message.sendToTarget();
                    }
                }
            };
            thread.start();
        }
    }
    Questo runnable è associato ad un alert dialog,

    Codice:
    final Runnable runnable = new Runnable() {
                [USER=106217]Override[/USER]
            public void run() {
                if (alert.isShowing()) {
                    alert.dismiss();
                    actualStar = (int) rating.getRating();
                    rating.setRating(0); //ripristino il valore delle stelle
    
                    if (actualTag.equalsIgnoreCase("")) {
                        actualTag = NOCATEGORIA;
                        copyActualTag = actualTag;
                        actualTag = "";
                    } else {
                        copyActualTag = actualTag;
                        actualTag = "";
                    }
                    // new GetLocation().execute();
                    getLocation();
    
                    //prova per testare il funzionamento del DB
                    db.open();
                    Cursor cursor = db.getPhotosTo(LocalitaArray.get(0), true);
                    cursor.moveToNext();
                    Log.i("Id", cursor.getString(0));
                    Log.i("Path", cursor.getString(1));
                    Log.i("Tag", cursor.getString(2));
                    Log.i("Star", cursor.getString(3));
                    Log.i("locality", cursor.getString(4));
    
                    onResume();
                }
            }
        };
    Questo è il metodo getLocation()

    Codice:
     private void getLocation() {
    
            Location location = gps.getLocation(LocationManager.GPS_PROVIDER);
    
            if (location != null) {
                double latitude = location.getLatitude();
                double longitude = location.getLongitude();
                LocationAddress locationAddress = new LocationAddress();
                locationAddress.getAddressFromLocation(latitude, longitude, mContext, new GeocoderHandler());
            } else showGpsSettingsAlert();
        }
    Questa è la classe handler

    Codice:
      private class GeocoderHandler extends Handler {
               [USER=106217]Override[/USER]
            public void handleMessage(Message message) {
                String locationAddress;
                switch (message.what) {
                    case 1:
                        Bundle bundle = message.getData();
                        locationAddress = bundle.getString("address");
                        break;
                    default:
                        locationAddress = null;
                }
                locality = locationAddress;
                localita.add(locality);
    
            }
        }
    Quando vado a fare il debug, il mio arrayLIst risulta di dimensione zero, e la variabile locality è vuota. Cosa sto sbagliando? Ho notato che l'applicazione si blocca ancora prima che il thread che determina la località venga terminato. COme posso far in modo che il thread principale dell'applicazione aspetti che il thread che determina la località finisca?
    Spero di risolvere, buona giornata