Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/272.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 从goole map API解析json数据失败_Android - Fatal编程技术网

Android 从goole map API解析json数据失败

Android 从goole map API解析json数据失败,android,Android,我想得到纬度和经度,我想使用AsyncTask,但我看不到日志值,它不起作用 我错过了哪一步?任何帮助都将不胜感激 我的全局变量: double editLatitude, editLongitude; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

我想得到纬度和经度,我想使用AsyncTask,但我看不到日志值,它不起作用

我错过了哪一步?任何帮助都将不胜感激

我的全局变量:

double editLatitude, editLongitude;

@Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {


        View view = inflater.inflate(R.layout.traffic_information_fragment, container, false);


        mapFrag = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
        mapFrag.getMapAsync(this);
        //it's my json url----------------------------------------------    
        new TrafficInformationTask().execute("http://maps.googleapis.com/maps/api/geocode/json?address=國泰綜合醫院+TW=true_or_false");

        return view;

    }
这是我的任务:

public class TrafficInformationTask extends AsyncTask<String, Integer, String> {
        @Override
        protected String doInBackground(String... strings) {
            String url = strings[0];
            try {
                String routeJson = getRoute(url);
                return routeJson;
            } catch (IOException ex) {
                Log.d(TAG, ex.toString());
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            showRoute(s);
        }
    }


    private String getRoute(String url) throws IOException {
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        int responseCode = connection.getResponseCode();
        StringBuilder jsonIn = new StringBuilder();
        if (responseCode == 200) {
            BufferedReader bf = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = bf.readLine()) != null) {
                jsonIn.append(line);
            }
        } else {
            Log.d(TAG, responseCode + "responseCode");
        }
        connection.disconnect();
        Log.d(TAG, jsonIn + "jsonIn");
        return jsonIn.toString();
    }
    //it's my parse step
    private void showRoute(String route) {
        try {
            JSONObject jsonObject = new JSONObject(route);
            JSONArray resultsArray = jsonObject.getJSONArray("results");
            JSONObject zeroJson = resultsArray.getJSONObject(0);
            JSONObject geometryJson = zeroJson.getJSONObject("geometry");
            editLatitude = geometryJson.getJSONObject("location").getDouble("lat");
            editLongitude = geometryJson.getJSONObject("location").getDouble("lng");
            //there is no value from log
            Log.d("editLatitude",editLatitude+"");
            Log.d("editLongitude",editLongitude+"");

        } catch (JSONException ex) {
            ex.printStackTrace();
        }
    }
公共类TrafficInformationTask扩展异步任务{
@凌驾
受保护的字符串背景(字符串…字符串){
字符串url=字符串[0];
试一试{
字符串routeJson=getRoute(url);
返回路线;
}捕获(IOEX异常){
Log.d(标记,例如toString());
}
返回null;
}
@凌驾
受保护的void onPostExecute(字符串s){
展览路线;;
}
}
私有字符串getRoute(字符串url)引发IOException{
HttpURLConnection连接=(HttpURLConnection)新URL(URL).openConnection();
int responseCode=connection.getResponseCode();
StringBuilder jsonIn=新的StringBuilder();
如果(响应代码==200){
BufferedReader bf=新的BufferedReader(新的InputStreamReader(connection.getInputStream());
弦线;
而((line=bf.readLine())!=null){
jsonIn.append(行);
}
}否则{
Log.d(标签,响应代码+“响应代码”);
}
连接断开();
Log.d(TAG,jsonIn+“jsonIn”);
返回jsonIn.toString();
}
//这是我的解析步骤
专用void showRoute(字符串路由){
试一试{
JSONObject JSONObject=新的JSONObject(路由);
JSONArray resultsArray=jsonObject.getJSONArray(“结果”);
JSONObject zeroJson=resultsArray.getJSONObject(0);
JSONObject geometryJson=zeroJson.getJSONObject(“几何体”);
editLatitude=geometryJson.getJSONObject(“位置”).getDouble(“纬度”);
Edit经度=geometryJson.getJSONObject(“位置”).getDouble(“液化天然气”);
//日志中没有值
Log.d(“editLatitude”,editLatitude+”);
Log.d(“编辑经度”,编辑经度+”);
}捕获(JSONException ex){
例如printStackTrace();
}
}

您可以使用
Geocoder
()获取经度

 public void Get_LatLng(){
    if(Geocoder.isPresent()){
        try {
            String location = "your_location_name";
            Geocoder gc = new Geocoder(this);
            List<Address> addresses= gc.getFromLocationName(location, 5); // get the Address Objects

            List<LatLng> ll = new ArrayList<LatLng>(addresses.size()); // A list to save the coordinates if they are available
            for(Address ad : addresses){
                if(ad.hasLatitude() && ad.hasLongitude()){
                    ll.add(new LatLng(ad.getLatitude(), ad.getLongitude()));
                    Log.d("editLatitude",ad.getLatitude());
                    Log.d("editLongitude",ad.getLongitude());
                }  
            }  
        } catch (IOException e) {
             // handle the exception
        }
    }
}

url是否返回了
JSON
数据?感谢您提供的信息,但我看到一些建议不支持此功能,因此我决定使用JSON
 private class TrafficInformationTask extends AsyncTask<String, Void, String[]> {
   ProgressDialog dialog = new ProgressDialog(MainActivity.this);
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dialog.setMessage("Loading..");
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    @Override
    protected String[] doInBackground(String... params) {
        String response;
        try {
            response = getLatLongByURL("http://maps.google.com/maps/api/geocode/json?address=dhaka&sensor=false");
            Log.d("response",""+response);
            return new String[]{response};
        } catch (Exception e) {
            return new String[]{"error"};
        }
    }

    @Override
    protected void onPostExecute(String... result) {
        try {
            JSONObject jsonObject = new JSONObject(result[0]);

            double lng = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
                    .getJSONObject("geometry").getJSONObject("location")
                    .getDouble("lng");

            double lat = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
                    .getJSONObject("geometry").getJSONObject("location")
                    .getDouble("lat");

            Log.d("latitude", "" + lat);
            Log.d("longitude", "" + lng);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (dialog.isShowing()) {
            dialog.dismiss();
        }
    }
}


public String getLatLongByURL(String requestURL) {
    URL url;
    String response = "";
    try {
        url = new URL(requestURL);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(15000);
        conn.setConnectTimeout(15000);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        conn.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");
        conn.setDoOutput(true);
        int responseCode = conn.getResponseCode();

        if (responseCode == HttpsURLConnection.HTTP_OK) {
            String line;
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            while ((line = br.readLine()) != null) {
                response += line;
            }
        } else {
            response = "";
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    return response;
}