2013-12-10 103 views
1

我目前的目標是解析Google Map API以返回有關某些座標的信息。Android反向地理編碼TextView中沒有文本顯示

我遇到的主要問題是我運行程序時無法顯示任何內容。下面給出的代碼在沒有任何錯誤停止程序的情況下運行,但是隻會提供一個空白的TextView。我對JSON解析不太熟悉(這是我使用過的第一個程序),我想知道是什麼導致了返回的信息不能顯示在TextView上。

是否有一種特定的方式讓文本在通過JSON解析時出現?我感謝所有的幫助。

我MainActivity.java類:

import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

import android.app.Activity; 
import android.os.Bundle; 
import android.os.StrictMode; 
import android.os.StrictMode.ThreadPolicy; 
import android.widget.TextView; 

public class MainActivity extends Activity { 

// URL to make the request to 
private static String url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=40.1031,-75.1522&sensor=true"; 

// JSON Node names 
private static final String TAG_LOCATION = "results"; 
private static final String TAG_CITY = "long_name"; 

// The JSON Array 
JSONArray location = null; 

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

    ThreadPolicy tp = ThreadPolicy.LAX; 
    StrictMode.setThreadPolicy(tp); 

    // Creating JSON Parser instance 
    JSONParser jParser = new JSONParser(); 

    // getting JSON string from URL 
    JSONObject json = jParser.getJSONFromUrl(url); 

    try { 
     // Getting Array of Location 
     location = json.getJSONArray(TAG_LOCATION); 

     // looping through each part of location 
     for(int i = 0; i < location.length(); i++){ 
      JSONObject c = location.getJSONObject(i); 

      // Storing each JSON item in a variable 
      String city = c.getString(TAG_CITY); 

      // For whichever one works 
      System.out.println(city); 

      TextView textView = (TextView) findViewById(R.id.textView1); 
      textView.setText("City: " + city); 



     } 
    } catch (JSONException e) { 
      e.printStackTrace(); 
    } 

} 

} 

我JSONParser.java類:

package com.example.finalproject; 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.UnsupportedEncodingException; 


import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.json.JSONException; 
import org.json.JSONObject; 


import android.util.Log; 

public class JSONParser { 

static InputStream is = null; 
static JSONObject jObj = null; 
static String json = ""; 

// constructor 
public JSONParser() { 

} 

public JSONObject getJSONFromUrl(String url) { 

    // Making HTTP request 
    try { 
     // defaultHttpClient 
     DefaultHttpClient httpClient = new DefaultHttpClient(); 
     HttpGet httpGet = new HttpGet(url); 

     HttpResponse httpResponse = httpClient.execute(httpGet); 
     HttpEntity httpEntity = httpResponse.getEntity(); 
     is = httpEntity.getContent();   

    } catch (UnsupportedEncodingException e) { 
     e.printStackTrace(); 
    } catch (ClientProtocolException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    try { 
     BufferedReader reader = new BufferedReader(new InputStreamReader(
       is, "iso-8859-1"), 8); 
     StringBuilder sb = new StringBuilder(); 
     String line = null; 
     while ((line = reader.readLine()) != null) { 
      sb.append(line + "\n"); 
     } 
     is.close(); 
     json = sb.toString(); 
    } catch (Exception e) { 
     Log.e("Buffer Error", "Error converting result " + e.toString()); 
    } 

    // try parse the string to a JSON object 
    try { 
     jObj = new JSONObject(json); 
    } catch (JSONException e) { 
     Log.e("JSON Parser", "Error parsing data " + e.toString()); 
    } 

    // return JSON String 
    return jObj; 

} 
} 
+0

你爲什麼要使用Web API和普通谷歌地圖Android版API一些示例代碼?只是好奇。 – pjco

+1

我希望我有這個答案。這是我第一個學期使用Android編程,我正在脫離我的教授給我的幫助。任何正面的反饋如何改變它更好,將不勝感激! –

+0

我建議使用Google位置API,除此之外,您不必處理JSON或HTTP:http://developer.android.com/google/play-services/location.html ...將發佈回答低於 – pjco

回答

1

long_name關鍵是把JSONObject這是address_components JSONArray代替的JSONObject這是results JSONArray所以你應該首先從c JSONObject獲取JSONArray,如下所示:

for(int i = 0; i < location.length(); i++){ 
      JSONObject c = location.getJSONObject(i); 
       // get address_components JSONArray from c 
      JSONArray add_array=c.getJSONArray("address_components"); 
      for(int j = 0; j < add_array.length(); j++){ 
       JSONObject obj_add = add_array.getJSONObject(i); 
        // Storing each JSON item in a variable 
       String city = c.getString(TAG_CITY); 
       //your code here.... 
       } 

} 

並且還使用AsyncTask從weservice獲取數據,而不是在主UI線程上執行網絡操作。

+1

感謝您的快速幫助。假設我想顯示的不僅僅是城市(即州,國家)的信息,那麼如何改變如何定義上面的TAG_ *變量呢? –

+0

@JoeFerraro:只需打印關於它的日誌並確定所需的鍵,只需在'JSONObject c = location.getJSONObject(i)'後加'Log.d(「location object」,c.toString());'' –

0

下面是採用了Android /谷歌的位置API

http://developer.android.com/google/play-services/location.html

import android.location.Address; 
import android.location.Criteria; 
import android.location.Geocoder; 
import android.location.Location; 
import android.location.LocationManager; 



private void reverseGeocode() 
{ 
    AsyncTask< LatLng, Integer, List<Address> > task 
        = new AsyncTask< LatLng, Integer, List<Address> >() 
    { 
     @Override 
     protected List<Address> doInBackground(LatLng... params) 
     { 
      LatLng latLng = params[0]; 
      Geocoder geoCoder = new Geocoder(getActivity().getApplicationContext()); 
      List<Address> matches = null; 

      try 
      { 
       matches = geoCoder.getFromLocation(latLng.latitude, latLng.longitude, 1); 
      } 
      catch (IOException e) 
      { 
       e.printStackTrace(); 
      } 

      return matches; 
     } 

     @Override 
     protected void onPostExecute(List<Address> result) 
     { 

      if (result != null && result.size() > 0) 
      { 
       if (D) Log.v(TAG, "onPostExecute result size=" + result.size()); 
       Address bestMatch = (result.isEmpty() ? null : result.get(0)); 
        //showGeocodedAddress(bestMatch); 
      } 
     } 
    }; 

    task.execute(latLng); 
} 
+1

感謝您發佈此信息。我一定會考慮用這個作爲參考。 –

+0

只是FYI,你可能想要投票而不是張貼感謝評論(如果你可以,不知道它是什麼讓你做1代表) – pjco

+1

它說我需要15代表。我會很高興這樣做,只要我達到那麼多的代表! –