如何在Android的方法语法之间修复此distanceBet?

时间:2015-09-16 00:12:09

标签: java android

您好我正在尝试从http://developer.android.com/reference/android/location/Location.html#distanceBetween(double,double,double,double,float [])实现distanceBetween方法。

我是编码的新手,所以我相信我会比现在更难,但我不知道为什么。我试图获取该JSON对象并从FIeld1(呼号),Field2(频率),Field21(纬度),Field24(纬度)中获取信息。 然后我想运行distanceBetween以查明它是否在350公里半径范围内。有人可以帮我提供一些提示或代码吗?谢谢!

这是我的UPDATED MainActivity.java

    package com.dredaydesigns.radiostationfinder;

import android.R;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;


public class MainActivity extends Activity implements GoogleApiClient.ConnectionCallbacks {
    public static final String TAG = MainActivity.class.getSimpleName();
    private RadioData mRadioData;

    private GoogleApiClient mGoogleApiClient;
    private Location mLastLocation;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list_content);
        ButterKnife.bind(this);


        Location locationUserLatitude = mLastLocation;
        Location locationUserLongitude = mLastLocation;
        Location latitudeStation;
        Location longitudeStation;
        RadioData mRadioData = new RadioData();

        OkHttpClient client = new OkHttpClient();
        String radioFinderURL = "http://dredaycreative.com/json/radioData.json";
        Request request = new Request.Builder()
                .url(radioFinderURL)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
            }

            @Override
            public void onResponse(Response response) throws IOException {
                try {
                    String jsonData = response.body().string();
                    Log.v(TAG, jsonData);
                    if (response.isSuccessful()) {
                        getCurrentRadioData(jsonData);
                    }

                } catch (IOException e) {
                    Log.e(TAG, "Exception Caught: ", e);
                } catch (JSONException e) {
                    Log.e(TAG, "Exception Caught:", e);
                }
            }

        });


    }


    private List getCurrentRadioData(String jsonData) throws JSONException{
        List radioData = new ArrayList<String>();
        Object obj=JSONValue.parse(jsonData);
        JSONArray data;
        data = (JSONArray)obj;
        for (int i=0; i<data.length(); i++) {
            JSONObject jasonObj = data.getJSONObject(i);
            if (Location.distanceBetween() <= 350) {

                float[] results = new float[3];
                Location.distanceBetween(mLastLocation.getLatitude(), mLastLocation.getLongitude(), latitudeStation, longitudeStation, results);
                float distance = results[0];

                JSONObject callsign = jasonObj.getJSONObject("FIELD1");
                radioData.add(callsign);
                JSONObject frequency = jasonObj.getJSONObject("FIELD2");
                radioData.add(frequency);
                double latitudeStations = jasonObj.getDouble("FIELD21");
                radioData.add(latitudeStations);
                double longitudeStations = jasonObj.getDouble("FIELD24");
                radioData.add(longitudeStations);
            } else {
            }



        }
return radioData;
    }



    private void updateDisplay() {
        mLatitudeLabel.setText(String.valueOf(mLastLocation.getLatitude()));
        mLongitudeLabel.setText(String.valueOf(mLastLocation.getLongitude()));
    }


    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener((GoogleApiClient.OnConnectionFailedListener) this)
                .addApi(LocationServices.API)
                .build();


    }


    @Override
    public void onConnected(Bundle bundle) {
        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
                mGoogleApiClient);
        if (mLastLocation != null) {
          //  mLatitudeLabel.setText(String.valueOf(mLastLocation.getLatitude()+ ""));
           // mLongitudeLabel.setText(String.valueOf(mLastLocation.getLongitude()+""));
        }
    }


    @Override
    public void onConnectionSuspended(int i) {

    }


}

这是我从github上的某人那里抓到的jsonValue.java

  package com.dredaydesigns.radiostationfinder;

/*
 * $Id: JSONValue.java,v 1.1 2006/04/15 14:37:04 platform Exp $
 * Created on 2006-4-15
 */

import org.json.simple.parser.JSONParser;

import java.io.Reader;
import java.io.StringReader;


/**
 * @author FangYidong<fangyidong@yahoo.com.cn>
 */
public class JSONValue {
    /**
     * parse into java object from input source.
     * @param in
     * @return instance of : JSONObject,JSONArray,String,Boolean,Long,Double or null
     */
    public static Object parse(Reader in){
        try{
            JSONParser parser=new JSONParser();
            return parser.parse(in);
        }
        catch(Exception e){
            return null;
        }
    }

    public static Object parse(String s){
        StringReader in=new StringReader(s);
        return parse(in);
    }
}

这是XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:paddingLeft="@dimen/activity_horizontal_margin"
                android:paddingRight="@dimen/activity_horizontal_margin"
                android:paddingTop="@dimen/activity_vertical_margin"
                android:paddingBottom="@dimen/activity_vertical_margin"
                tools:context=".MainActivity"
                android:background="#ffffed">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Text"
        android:id="@+id/latitudeLabel"
        android:layout_alignParentTop="true"
        android:layout_marginTop="49dp"
        android:layout_centerHorizontal="true"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Text"
        android:id="@+id/longitudeLabel"
        android:layout_below="@+id/latitudeLabel"
        android:layout_marginTop="72dp"
        android:layout_centerHorizontal="true"/>

</RelativeLayout>

这就是getter和setter RadioData.java ......我正在从teamtreehouse学到的这个项目拼凑起来,如果它非常俗气,请道歉。

 package com.dredaydesigns.radiostationfinder;

/**
 * Created by Andreas on 8/10/2015.
 */
public class RadioData {
    public String getCallSign() {
        return mCallsign;
    }

    public void setCallSign(String callsign) {
        mCallsign = callsign;
    }

    public double getFrequency() {
        return mFrequency;
    }

    public void setFrequency(double frequency) {
        mFrequency = frequency;
    }

    public int getChannel() {
        return mChannel;
    }

    public void setChannel(int channel) {
        mChannel = channel;
    }

    public double getLatitude() {
        return mLatitude;
    }

    public void setLatitude(double latitude) {
        mLatitude = latitude;
    }

    public double getLongitude() {
        return mLongitude;
    }

    public void setLongitude(double longitude) {
        mLongitude = longitude;
    }

    private String mCallsign;
    private double mFrequency;
    private int mChannel;
    private double mLatitude;
    private double mLongitude;



}

在用户的建议之后我现在已将MainActivity代码的这一部分更改为以下内容,但在某处似乎仍然存在错误,我需要帮助,谢谢!我的gradle建设很好,但我不能让genymotion上班,所以我无法知道什么是有效的!如果这部分工作正常,我的下一步就是向用户显示localRadioData:D :

 private List getCurrentRadioData() throws JSONException{
        List radioData = new ArrayList<String>();
        List localRadioData = new ArrayList();
        Object obj=JSONValue.parse(String.valueOf(radioData));
        JSONArray data;
        data = (JSONArray)obj;
        float[] results = new float[3];
        double latitudeStation = 0;
        double longitudeStation = 0;
        for (int i=0; i<data.length(); i++) {
            JSONObject jasonObj = data.getJSONObject(i);
            double latitudeStations = jasonObj.getDouble("FIELD21");
            radioData.add(latitudeStations);
            double longitudeStations = jasonObj.getDouble("FIELD24");
            radioData.add(longitudeStations);
            Location.distanceBetween(mLastLocation.getLatitude(), mLastLocation.getLongitude(), latitudeStation, longitudeStation, results);
            float distance = results[0];
            distance = Math.round(distance);

            if ((distance) > 350) {
                JSONObject callsign = jasonObj.getJSONObject("FIELD1");
                localRadioData.add(callsign);
                JSONObject frequency = jasonObj.getJSONObject("FIELD2");
                localRadioData.add(frequency);
            } else {
            radioData.add(getCurrentRadioData());

            }


        }

        return localRadioData;
    }

1 个答案:

答案 0 :(得分:2)

distanceBetween是Location类的静态函数,这意味着您只需通过执行以下操作即可调用它:

float[] results = new float[3];
Location.distanceBetween(startLat, startLong, endLat, endLong, results);
float distance = results[0];

关于如何在代码中实现它,它可能看起来像这样:

float[] results = new float[3];
Location.distanceBetween(mLastLocation.getLatitude(), mLastLocation.getLongitude(), latitudeStation, longitudeStation, results);
float distance = results[0];

我希望这有助于:)