开发者

Wait for Lat and Long before getting info

开发者 https://www.devze.com 2023-03-06 10:09 出处:网络
so i have this code public class List extends ListActivity implements LocationListener { int ct_id; String[] ct_number = null;

so i have this code

public class List extends ListActivity implements LocationListener {

    int ct_id;
    String[] ct_number = null;
    String[] ct_address = null;
    String[] ct_phone = null;
    String[] ct_fax = null;
    String[] ct_email = null;
    String[] ct_city = null;
    String[] ct_province = null;
    String[] ct_country = null;
    String[] ct_pcode = null;
    String[] ct_lat = null;
    String[] ct_long = null;
    String[] ct_di开发者_Go百科stance = null;
    String[] ct_show = null;
    String[] ct_listinfo = null;

    private LocationManager locationManager;

    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        //setContentView(R.layout.timslist);

        locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000L, 500.0f, this);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 500.0f, this);
        Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

        double lat = location.getLatitude();
        double lng = location.getLongitude();

        String result = null;
        InputStream is = null;
        StringBuilder sb = null;
        //http post
        try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://www.somedomain.com/list.php?lat=" + lat + "&long=" + lng + "");
            //httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
        }catch(Exception e){
            Log.e("log_tag", "Error in http connection"+e.toString());
        }
        //convert response to string
        try{
            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
            sb = new StringBuilder();
            sb.append(reader.readLine() + "\n");
            String line="0";
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            result=sb.toString();
        }catch(Exception e){
            Log.e("log_tag", "Error converting result"+e.toString());
        }
        //paring data
        JSONArray jArray;
        try{
            jArray = new JSONArray(result);
            JSONObject json_data=null;
            ct_number=new String[jArray.length()];
            ct_address=new String[jArray.length()];
            ct_phone=new String[jArray.length()];
            ct_fax=new String[jArray.length()];
            ct_email=new String[jArray.length()];
            ct_city=new String[jArray.length()];
            ct_province=new String[jArray.length()];
            ct_country=new String[jArray.length()];
            ct_pcode=new String[jArray.length()];
            ct_lat=new String[jArray.length()];
            ct_long=new String[jArray.length()];
            ct_distance=new String[jArray.length()];
            ct_listinfo=new String[jArray.length()];
            for(int i=0;i<jArray.length();i++){
                json_data = jArray.getJSONObject(i);
                ct_id=json_data.getInt("location_id");
                ct_number[i]=json_data.getString("store_number");
                ct_address[i]=json_data.getString("store_address");
                ct_phone[i]=json_data.getString("store_phone");
                ct_fax[i]=json_data.getString("store_fax");
                ct_email[i]=json_data.getString("store_email");
                ct_city[i]=json_data.getString("store_city");
                ct_province[i]=json_data.getString("store_province");
                ct_country[i]=json_data.getString("store_country");
                ct_pcode[i]=json_data.getString("store_pcode");
                ct_lat[i]=json_data.getString("store_lat");
                ct_long[i]=json_data.getString("store_long");
                ct_distance[i]=json_data.getString("store_distance");
                ct_listinfo[i] = new String (ct_address[i] + "\n" + ct_city[i] + ", " + ct_province[i] + " - " + ct_distance[i] + " Km");
            }
        }
        catch(JSONException e1){
            Toast.makeText(getBaseContext(), "No Addresses Found" ,Toast.LENGTH_LONG).show();
        } catch (ParseException e1) {
            e1.printStackTrace();
        }

        setListAdapter(new ArrayAdapter<String>(this,R.layout.listview,ct_listinfo));
        ListView lv;
        lv = getListView();
        lv.setTextFilterEnabled(true);
        lv.setBackgroundColor(Color.rgb(83, 05, 14));
        lv.setCacheColorHint(Color.rgb(83, 05, 14));
        lv.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> timslist, View view,
                    int position, long id) {

                Intent i1 = new Intent(getApplicationContext(), TimsListMore.class);

                i1.putExtra("ct_number_pass", ct_number[position]);
                i1.putExtra("ct_address_pass", ct_address[position]);
                i1.putExtra("ct_phone_pass", ct_phone[position]);
                i1.putExtra("ct_city_pass", ct_city[position]);
                i1.putExtra("ct_province_pass", ct_province[position]);
                i1.putExtra("ct_country_pass", ct_country[position]);
                i1.putExtra("ct_pcode_pass", ct_pcode[position]);
                i1.putExtra("ct_distance_pass", ct_distance[position]);

                startActivity(i1);

            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000L, 500.0f, this);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 500.0f, this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        locationManager.removeUpdates(this);
    }

    public void onLocationChanged(Location location) {
        if (location != null) {
            location.getLatitude();
            location.getLongitude();
        }
    }

    public void onProviderDisabled(String provider) {
        // required for interface, not used
        Toast.makeText(getApplicationContext(), " Your " + provider + " is disabled. Please enable it!", 
                Toast.LENGTH_LONG).show();
    }

    public void onProviderEnabled(String provider) {
        Toast.makeText(this, "Enabled new provider " + provider,
                Toast.LENGTH_SHORT).show();
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {
        // required for interface, not used
    }

    protected boolean isRouteDisplayed() {
        // TODO Auto-generated method stub
        return false;
    }

}

my issue is that i need it to have the current location then get the database in json array

//http post
            try{
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://www.somedomain.com/list.php?lat=" + lat + "&long=" + lng + "");
                //httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();
            }catch(Exception e){
                Log.e("log_tag", "Error in http connection"+e.toString());
            }

This way when i am asking for the info it has the current lat and long added to the request. Right now this all works but it is going off the old location and not waiting for the current one.


Hi used Below Code may be helpful to you.

below is MyLocation.Java file

import java.util.Timer;
import java.util.TimerTask;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

public class MyLocation {
    Timer timer1;
    LocationManager lm;
    LocationResult locationResult;
    boolean gps_enabled=false;
    boolean network_enabled=false;

    public boolean getLocation(Context context, LocationResult result)
    {
        //I use LocationResult callback class to pass location value from MyLocation to user code.
        locationResult=result;
        if(lm==null)
            lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

        //exceptions will be thrown if provider is not permitted.
        try{gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER);}catch(Exception ex){}
        try{network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception ex){}

        //don't start listeners if no provider is enabled
        if(!gps_enabled && !network_enabled)
            return false;

        if(gps_enabled)
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
        if(network_enabled)
            lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
        timer1=new Timer();
        timer1.schedule(new GetLastLocation(), 60000);
        return true;
    }

    LocationListener locationListenerGps = new LocationListener() {
        public void onLocationChanged(Location location) {
            timer1.cancel();
            locationResult.gotLocation(location);
            lm.removeUpdates(this);
            lm.removeUpdates(locationListenerNetwork);
        }
        public void onProviderDisabled(String provider) {}
        public void onProviderEnabled(String provider) {}
        public void onStatusChanged(String provider, int status, Bundle extras) {}
    };

    LocationListener locationListenerNetwork = new LocationListener() {
        public void onLocationChanged(Location location) {
            timer1.cancel();
            locationResult.gotLocation(location);
            lm.removeUpdates(this);
            lm.removeUpdates(locationListenerGps);
        }
        public void onProviderDisabled(String provider) {}
        public void onProviderEnabled(String provider) {}
        public void onStatusChanged(String provider, int status, Bundle extras) {}
    };

    class GetLastLocation extends TimerTask {
        @Override
        public void run() {
             lm.removeUpdates(locationListenerGps);
             lm.removeUpdates(locationListenerNetwork);

             Location net_loc=null, gps_loc=null;
             if(gps_enabled)
                 gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
             if(network_enabled)
                 net_loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

             //if there are both values use the latest one
             if(gps_loc!=null && net_loc!=null){
                 if(gps_loc.getTime()>net_loc.getTime())
                     locationResult.gotLocation(gps_loc);
                 else
                     locationResult.gotLocation(net_loc);
                 return;
             }

             if(gps_loc!=null){
                 locationResult.gotLocation(gps_loc);
                 return;
             }
             if(net_loc!=null){
                 locationResult.gotLocation(net_loc);
                 return;
             }
             locationResult.gotLocation(null);
        }
    }

    public static abstract class LocationResult{
        public abstract void gotLocation(Location location);
    }
}

And now used this file in another Main class file

MyLocation myLocation = new MyLocation();

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

    }

private void findCurrentLocation() {
        myLocation.getLocation(this, locationResult);
    }

public LocationResult locationResult = new LocationResult() {

        @Override
        public void gotLocation(Location location) {
            // TODO Auto-generated method stub
            if (location != null) {
                String strloc  = location.getLatitude() + ","
                        + location.getLongitude();
            }
        }
    };

now Toast messge of "strloc".

Thanks, Nik...

0

精彩评论

暂无评论...
验证码 换一张
取 消