Android Reverse Geocoding在TextView中不显示任何文本

时间:2013-12-10 02:34:49

标签: android json parsing textview geocoding

我目前的目标是解析Google Map API以返回有关某些坐标的信息。

我遇到的主要问题是我在运行程序时无法显示任何内容。下面给出的代码将在没有任何错误停止程序的情况下运行,但只会出现一个空白的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;

}
}

2 个答案:

答案 0 :(得分:1)

long_name密钥位于address_components JSONArray中的JSONObject中,而不是results JSONArray中的JSONObject,因此您需要首先从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 :(得分:0)

以下是使用Android / Google位置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 );
}