2016-12-02 104 views
0

我试图创建一种方法来获取网站上的某个地点的高度: https://maps.googleapis.com/maps/api/elevation/json?locations=0,0(其中0,0可以用任何坐标替换)。Android getInputStream无法正常工作

但是,从URL连接获取InputStream时遇到问题。

private double altitude(double lat, double longi) { 
    String elevation = ""; 
    try { 
     URL alt = new URL("https://maps.googleapis.com/maps/api/elevation/json?locations="+lat+","+longi); 
     HttpURLConnection altFind = (HttpURLConnection) alt.openConnection(); 
     altFind.setDoInput(true); 
     BufferedReader in = new BufferedReader(new InputStreamReader(altFind.getInputStream())); 
     String inputLine; 
     OUT: 
     while ((inputLine = in.readLine()) != null) { 
      if (inputLine.contains("elevation")) { 
       for (int i = 23; ; i++) { 
        if (inputLine.charAt(i) != ',') { 
         elevation = elevation + "" + inputLine.charAt(i); 
        } else { 
         break OUT; 
        } 
       } 
      } 
     } 
     return Double.parseDouble(elevation); 
    } catch (MalformedURLException e) {} 
    catch (IOException e) {} 
    return 0; 
} 

这是方法和我把它从这里:

private TextView t; 
private LocationManager locationManager; 
private LocationListener listener; 
double elev; 

@Override 
protected void onCreate(@Nullable Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_display); 

    Intent intent = getIntent(); 
    String longlat = intent.getStringExtra(MainActivity.EXTRA_MESSAGE); 
    longlat = longlat.replaceAll(" ", ""); 
    String [] longilati = longlat.split(","); 
    final double [] coord = new double[2]; 
    coord[0] = Double.parseDouble(longilati[0]); 
    coord[1] = Double.parseDouble(longilati[1]); 

    t = (TextView) findViewById(R.id.textView); 

    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 
    NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); 
    if (networkInfo != null && networkInfo.isConnected()) { 
     elev = altitude(coord[0], coord[1]); 
    } else { 
     Toast.makeText(this, "No connection available", Toast.LENGTH_LONG).show(); 
    } 

我已试过无济于事类似的问题。

+2

请定义“无法正常工作”。你有错误吗?它会崩溃吗?什么是意外? – Knossos

+0

'我从URL连接中获取InputStream时遇到了问题。哪个问题? – greenapps

+1

你将有一个'NetworkOnMainThreadException'。你的应用崩溃了。你应该已经告诉过这一切! – greenapps

回答

1

您应该在后台线程上执行网络连接。

您可以使用Asynctask类并移动altitude方法doInBackground()

你可以在这里阅读更多: https://developer.android.com/reference/android/os/AsyncTask.html

编辑:

我发现这个班叫JSONParser我认为这是你需要什么,看看这个: https://gist.github.com/dmnugent80/b2e22e5546c4b1c391ee

复制和粘贴它进入你的项目。

您可以通过从JSONParser类调​​用makeHttpRequest方法并传递所需的所有参数来修改您的altitude方法。如果你做得对,那么该方法将从URL返回JSON对象。例如:

private static final String URL = "https://maps.googleapis.com/maps/api/elevation/json"; 
private static final String METHOD = "GET"; // You can use POST either 

private double altitude(double lat, double lng) { 
    double elevation = 0.0; 
    HashMap<String, String> params = new HashMap<>(); 
    params.put("locations", lat + "," + lng); 
    // Here you can put another params if needed 

    JSONParser jsonParser = new JSONParser(); 
    JSONObject jsonObject = jsonParser.makeHttpRequest(URL, METHOD, params); 

    if(jsonObject != null) { 
     Log.d(TAG, jsonObject.toString()); // Check if data has arrived safely? 

     try { 
      JSONArray results = jsonObject.getJSONArray("results"); 
      JSONObject result = results.getJSONObject(0); 
      elevation = result.getDouble("elevation"); 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 

     return elevation; 
    } else { 
     return -1; 
    } 
} 

呼叫altitudedoInBackground和看到的结果。

+0

我试图添加这个,但它没有奏效。虽然我可能做错了 –

+0

我有问题使用链接中的代码执行该方法 –

+0

@JoshuaTurner我编辑了我的答案,希望这可以帮助你。 –