【问题标题】:Android Reverse Geocoding no text displays in TextViewAndroid反向地理编码在TextView中不显示文本
【发布时间】:2013-12-10 02:34:49
【问题描述】:

我目前的目标是解析 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;

}
}

【问题讨论】:

  • 您为什么使用 Web API 而不是常规的 Google Maps for Android API?只是好奇。
  • 我希望我有一个答案。这是我第一个使用 Android 编程的学期,我的教授给了我帮助。任何关于如何改进它的积极反馈将不胜感激!
  • 我建议您使用 Google Location API,您不必处理 JSON 或 HTTP 等问题:developer.android.com/google/play-services/location.html ...将在下面发布答案

标签: android json parsing textview geocoding


【解决方案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 线程上进行网络操作。

【讨论】:

  • 感谢您的快速帮助。假设我想显示的不仅仅是城市(即州、国家/地区)的信息,这将如何改变上面定义我的 TAG_* 变量的方式?
  • @JoeFerraro:只需打印有关它的日志并确定所需的键,只需在JSONObject c = location.getJSONObject(i); 之后添加Log.d("location object",c.toString());
【解决方案2】:

以下是一些使用 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 );
}

【讨论】:

  • 感谢您发布此信息。我一定会考虑将此作为参考。
  • 仅供参考,您可能想要投票而不是发布感谢 cmets(如果可以,不确定它可以让您用 1 个代表做什么)
  • 它说我需要 15 个代表。一旦达到这么多的代表,我会很乐意这样做!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-03
  • 2014-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多