关于从活动到片段获取纬度和经度的困惑

时间:2016-05-13 08:59:03

标签: java android google-maps android-fragments gps

我正在研究在线租车搜索apk。我希望这个程序从服务器获取数据库并根据位置(与用户当前租车车库位置的距离)对其进行排序。 但我在这里混淆如何根据距离对列表视图进行排序?我的意思是,我知道如何计算距离,但我对于如何在不打开mapActivity的情况下获取用户当前的经度和经度感到空白? 这是我现在的状况: 1.我的结果列表在ResultListFragment.java中,我的谷歌地图活动在MapActivity.java上。 2.我必须尝试使用​​我在MapActivity.java上创建的getLatitude和getLongitude方法获取经度,纬度,但它只返回零(非空)。 3.我试图在GPStracker类上分离gps监听器,但它仍无效。

请帮助我,我如何获得当前用户位置的纬度和经度。

NB。这是我的ResultListFragment.java

public class ResultListFragment extends Fragment implements InternetConnectionListener,
    LocationChangeListener {

public static String catId;
public static String titleId;
public static String searchTerm;
public static LocationChangeListener locationChangeListener;
private final int RESULT_ACTION = 1;
private final int RESULT_LIMIT = 100;
private ArrayList<Item> searchResultList;
private ResultListCallbacks mCallbacks;
private InternetConnectionListener internetConnectionListener;
private ArrayList<Item> resultList;
private ListView resultListView;
private LatLng itemLocation;
GPSTrackStandAlone gTrack = new GPSTrackStandAlone(getContext());
MapActivity mAct = new MapActivity();
public HomeActivity hAct = new HomeActivity();
public ResultListFragment() {

}

public static ResultListFragment newInstance(String id, String title) {
    ResultListFragment fragment = new ResultListFragment();
    catId = id;
    titleId = title;
    searchTerm = "";
    locationChangeListener = fragment;
    return fragment;
}

public static ResultListFragment newInstance(String id, String title,String term) {
    ResultListFragment fragment = new ResultListFragment();
    catId = id;
    titleId = title;
    searchTerm = term;
    locationChangeListener = fragment;
    return fragment;
}

public void getGPSLoc(){
        double latitude = mAct.getLatitudeSend();
        double longitude = mAct.getLongitudeSend();
        Log.d("LatitudeCurrGPSLoc",String.valueOf(latitude));
        Log.d("LongCur",String.valueOf(longitude));
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        mCallbacks = (ResultListCallbacks) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException("Activity must implement ResultListCallbacks.");
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_result_list, container, false);
    resultListView = (ListView) rootView.findViewById(R.id.resultListView);
    setHasOptionsMenu(true);
    return rootView;
}


@Override
public void onResume() {
    super.onResume();
    isHomeOpened = false;
    isResultListFragmentOpened = true;
    if (UtilMethods.isConnectedToInternet(getActivity())) {
        if (!TextUtils.isEmpty(catId))
            initResultList();
        else if (!TextUtils.isEmpty(searchTerm))
            getSearchResults(searchTerm);
    } else {

        internetConnectionListener = (InternetConnectionListener) ResultListFragment.this;
        showNoInternetDialog(getActivity(), internetConnectionListener, getResources().getString(R.string.no_internet),
                getResources().getString(R.string.no_internet_text),
                getResources().getString(R.string.retry_string),
                getResources().getString(R.string.exit_string), RESULT_ACTION);
    }

}

private void initResultList() {
    Log.d("Pembuktian", catId);
    if(Integer.parseInt(catId)>100 && Integer.parseInt(catId)<200 ){

        new getCarRent().execute();
    }else if(Integer.parseInt(catId)>199 && Integer.parseInt(catId)<300){

        new getCarBrand().execute();
    }else if(Integer.parseInt(catId)>299 && Integer.parseInt(catId)<400){

        new getCarType().execute();
    }
    /**
     * json is populating from text file. To make api call use ApiHandler class
     * pass parameter using ContentValues (values)
     *
     * <CODE> ApiHandler handler = new ApiHandler(this, URL_GET_RESULT_LIST_WITH_AD, values);</CODE> <BR>
     * <CODE> handler.doApiRequest(ApiHandler.REQUEST_POST);</CODE> <BR>
     *
     * You will get the response in onSuccessResponse(String tag, String jsonString) method
     * if successful api call has done.
     */

   // String jsonString = loadJSONFromAsset(getActivity(), "get_result_list");
    //parseJson(jsonString);
}

private void getSearchResults(String query) {

    /**
     * json is populating from text file. To make api call use ApiHandler class
     * pass parameter using ContentValues (values)
     *
     * <CODE> ApiHandler handler = new ApiHandler(this, URL_GET_SEARCH_LIST_AD, values);</CODE> <BR>
     * <CODE> handler.doApiRequest(ApiHandler.REQUEST_POST);</CODE> <BR>
     *
     * You will get the response in onSuccessResponse(String tag, String jsonString) method
     * if successful api call has done.
     */

    String jsonString = loadJSONFromAsset(getActivity(), "get_search_list");
    parseJson(jsonString);
}

public class getCarRent extends AsyncTask<Void, Void, Void>{
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(Void... params) {
        URL hp = null;
        try {

            hp = new URL(getString(R.string.liveurl)
                    + "getCarRent.php?value=" + catId);
            // hp = new URL(
            // "http://192.168.1.106/restourant/foodtype.php?value="
            // + id);
            Log.d("URL", "" + hp);
            URLConnection hpCon = hp.openConnection();
            hpCon.connect();
            InputStream input = hpCon.getInputStream();
            Log.d("input", "" + input);

            BufferedReader r = new BufferedReader(new InputStreamReader(
                    input));

            String x = "";
            x = r.readLine();
            String total = "";

            while (x != null) {
                total += x;
                x = r.readLine();
            }
            Log.d("URL", "" + total);

            JSONArray j = new JSONArray(total);
            Log.d("URL1", "" + j.length());
            Item[] itemList = new Item[j.length()];
            resultList = new ArrayList<Item>();
            for (int i = 0; i < j.length(); i++) {
                Item item = new Item();// buat variabel category
                //JSONObject Obj;
                JSONObject Obj = j.getJSONObject(i); //sama sperti yang lama, cman ini lebih mempersingkat karena getJSONObject cm d tulis sekali aja disini

                item.setId(Obj.getString(JF_ID));
                //item.setTitle(Obj.getString(JF_TITLE));


                item.setAddress(Obj.getString(JF_ADDRESS));

                item.setTelephoneNumber(Obj.optString(JF_TELEPHONE, NO_DATA_FOUND));

                item.setEmailAddress(Obj.optString(JF_EMAIL, NO_DATA_FOUND));
                item.setWebUrl(Obj.optString(JF_WEB, NO_DATA_FOUND));
                item.setFacebookUrl(Obj.optString(JF_FACEBOOK, NO_DATA_FOUND));

                item.setLatitude(Obj.optDouble(JF_LATITUDE, NULL_LOCATION));
                item.setLongitude(Obj.optDouble(JF_LONGITUDE, NULL_LOCATION));
                try {
                    item.setRating(Float.parseFloat(Obj.optString(JF_RATING, NO_DATA_FOUND)));
                } catch (NumberFormatException e) {
                    item.setRating(0.0f);
                }

                try {
                    item.setRatingCount(Integer.parseInt(Obj.optString(JF_RATING_COUNT, NO_DATA_FOUND)));
                } catch (NumberFormatException e) {
                    item.setRatingCount(0);
                }

                try {
                    item.setRatingCount(Integer.parseInt(Obj.optString(JF_RATINGSCORE, NO_DATA_FOUND)));
                } catch (NumberFormatException e) {
                    item.setRatingCount(0);
                }


                item.setTagLine(Obj.optString(JF_TAG_LINE, NO_DATA_FOUND));
                item.setDescription(Obj.optString(JF_DESCRIPTION, NO_DATA_FOUND));
                item.setVerification(Obj.optString(JF_VERIFICATION, NO_DATA_FOUND).equals("1") ? true : false);

                item.setCarId(Obj.optString(JF_CARID, NO_DATA_FOUND));
                item.setTitle(Obj.optString(JF_CARTITLE, NO_DATA_FOUND));
                item.setCarRentalId(Obj.optString(JF_CARRENTALID, NO_DATA_FOUND));
                item.setCarPrice(Obj.optString(JF_CARPRICE, NO_DATA_FOUND));
                item.setCarYear(Obj.optString(JF_CARYEAR, NO_DATA_FOUND));

                JSONArray imgArr = Obj.getJSONArray("thumbImage");
                String[] imageThumb = new String[imgArr.length()];
                // String[] imageLarge = new String[imgArr.length()];

                for (int k = 0; k < imgArr.length(); k++) {
                    imageThumb[k] = imgArr.getString(k);
                    // imageLarge[k] = imgArr.getJSONObject(k).getString(JF_TITLE);
                }


                for(int l = 0; l <imgArr.length(); l++) {
                    item.setImageLargeUrls(imageThumb);
                }


                item.setImageThumbUrls(imageThumb);
                // item.setImageLargeUrls(imageLarge);

                //  JSONArray imgArr = Obj.getJSONArray("thumbImage");

                /*String[] imgCount = new String[imgArr.length()];
                for(int k = 0 ; k < imgCount.length; k++) {


                    imgCount[k] = imgArr.getString(k);
                    item.setImageThumbUrls(imgCount);
                }*/





                    Location trgtLocation = new Location("trgtLocation");
                    trgtLocation.setLatitude(item.getLatitude());
                    trgtLocation.setLongitude(item.getLongitude());

                    Location crntLocation = new Location("crntlocation");
                    crntLocation.setLatitude(gTrack.getLatitude());
                    crntLocation.setLongitude(gTrack.getLongitude());
                    Log.d("latitudeCurr", String.valueOf(gTrack.getLatitude()));
                    Log.d("curLocLong", String.valueOf(gTrack.getLongitude()));

                    //LatLng currentLatLng = new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
                    item.setDistance(crntLocation.distanceTo(trgtLocation) / 1000);
                    Log.d("distance", String.valueOf(item.getDistance()));


                Log.d("URL1", "" + Obj.getString(JF_TITLE));

                resultList.add(item);


                itemList[i]=item;

                Log.d("itemList",String.valueOf(itemList[i]));

                Arrays.sort(itemList, new Comparator<Item>() {
                    @Override
                    public int compare(Item lhs, Item rhs) {
                        return 0;
                    }
                });


            }


            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    resultListView.setAdapter(new ResultListAdapterRental(getActivity(), mCallbacks, resultList));
                }
            });

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NullPointerException e) {
            // TODO: handle exception
        }
        return null;
    }
    }

我尝试从像这样的系统服务中获取Lng和Lat,但它仍然不起作用。这段代码对吗?

GPSTracker.java

public class GPSTrackStandAlone extends Service implements LocationListener {
private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
private Context mContext;
private boolean isGpsEnabled = false;
private boolean isNetworkEnabled = false;
private boolean canGetLocation = false;
private Location mLocation;
private double mLatitude;
private double mLongitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATE = 10;
private static final long MIN_TIME_FOR_UPDATE = 60000;
private LocationManager mLocationManager;
private static final long INTERVAL = 1000 * 10;
private static final long FASTEST_INTERVAL = 1000 * 5;

public GPSTrackStandAlone(Context mContext) {

    this.mContext = mContext;
}


/**
 * @return location
 */
public Location getLocation() {


    try {

        mLocationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);

        /*getting status of the gps*/
        isGpsEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

        /*getting status of network provider*/
        isNetworkEnabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGpsEnabled && !isNetworkEnabled) {

            /*no location provider enabled*/
        } else {

            this.canGetLocation = true;

            /*getting location from network provider*/
            if (isNetworkEnabled) {
                if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                        || ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                    mLocationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_FOR_UPDATE,
                            MIN_DISTANCE_CHANGE_FOR_UPDATE, this);
                    Log.d("Perms", "Permission for GPS Granted");

                    if (mLocationManager != null) {

                        mLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

                        if (mLocation != null) {
                            mLatitude = mLocation.getLatitude();
                            mLongitude = mLocation.getLongitude();
                        }
                    }
                }
                /*if gps is enabled then get location using gps*/
                if (isGpsEnabled) {
                    if (mLocation == null) {
                        mLocationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_FOR_UPDATE,
                                MIN_DISTANCE_CHANGE_FOR_UPDATE, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (mLocationManager != null) {
                            mLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (mLocation != null) {
                                mLatitude = mLocation.getLatitude();
                                mLongitude = mLocation.getLongitude();
                            }

                        }
                    }

                }
            }
        }

    } catch (Exception e) {

        e.printStackTrace();
    }

    return mLocation;
}

/**
 * call this function to stop using gps in your application
 */
public void stopUsingGps() {

    if (mLocationManager != null) {
        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            mLocationManager.removeUpdates(GPSTrackStandAlone.this);
        }

    }
}

private boolean isGooglePlayServicesAvailable() {
    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
    if (ConnectionResult.SUCCESS == status) {
        return true;
    } else {
        Toast.makeText(GPSTrackStandAlone.this, "isGooglePlayServiceAvailable = False", Toast.LENGTH_SHORT).show();
        return false;
    }
}

protected void createLocationRequest() {
    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(INTERVAL);
    mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}


/**
 * @return latitude
 *         <p/>
 *         function to get latitude
 */
public double getLatitude() {
    getLocation();
    if (mLocation != null) {

        mLatitude = mLocation.getLatitude();
    }
    return mLatitude;
}

/**
 * @return longitude
 *         function to get longitude
 */
public double getLongitude() {
    getLocation();
    if (mLocation != null) {

        mLongitude = mLocation.getLongitude();
        Log.d("MGPS", String.valueOf(mLocation.getLatitude()));
    }

    return mLongitude;
}

/**
 * @return to check gps or wifi is enabled or not
 */
public boolean canGetLocation() {

    return this.canGetLocation;
}

@Override
public IBinder onBind(Intent arg0) {
    // TODO Auto-generated method stub
    return null;
}

public void onLocationChanged(Location location) {
    // TODO Auto-generated method stub

}

public void onProviderDisabled(String provider) {
    // TODO Auto-generated method stub

}

public void onProviderEnabled(String provider) {
    // TODO Auto-generated method stub

}

public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub

}

}

3 个答案:

答案 0 :(得分:0)

您是否考虑过使用Google Maps API?有了它,您只需执行以下操作即可获得用户的当前位置:

mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                    .getMap();
mMap.setMyLocationEnabled(true);
Location myLocation = googleMap.getMyLocation();

答案 1 :(得分:0)

您的意思是您可以getLnggetLat参加活动吗? 尝试使用public static来描述您的值,并在片段中使用MyActivity.value

答案 2 :(得分:0)

如果要将数据从活动传递到片段,则应使用bundle。 我会举个例子。

 public class CompleteJobFragment extends Fragment {
 private final static String PICKUP_TIME="pickup time";

public static CompleteJobFragment newInstance(String pickUpTime) {
    CompleteJobFragment fragment = new CompleteJobFragment();
    Bundle bundle = new Bundle();
    bundle.putString(PICKUP_TIME, pickUpTime);
    fragment.setArguments(bundle);
    return fragment;
}

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        pickUpTime = getArguments().getString(PICKUP_TIME);
    }
}

活动文件

  public class ActiveJobActivity extends AppCompatActivity  {
  String x1;
  public void loadData()
  {

   CompleteJobFragment completeJobFragment = CompleteJobFragment.newInstance(x1);
    final FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
    fragmentTransaction.replace(R.id.activez, completeJobFragment, COMPLETE_FRAGMENT);
    fragmentTransaction.addToBackStack(COMPLETE_FRAGMENT);
    completeJobFragment.setCommunicator(this);
    fragmentTransaction.commit();

    }