0

我已经创建了一个 android 应用程序,用户可以在其中选择位置的起点和终点。此应用程序将使用 Google-Direction 网络服务并发出 HTTPRequest。我会简短地说,我想从 main_activity 调用 JSONParser 类中的 asynctask 方法。问题是,我不知道如何在 main_activtiy 方法中显示结果

这是异步任务方法

public class JSONParser {
InputStream is = null;
JSONObject jObj = null;
String json = "";

public JSONParser() {
}

public void getJSONFromUrl(final String url, final responseListener target) {
    new AsyncTask<Void, Void, String>() {
        protected String doInBackground(Void... params) {
            HttpURLConnection httpURLConnection = null;
            StringBuilder stringBuilder = new StringBuilder();
            try {
                httpURLConnection = (HttpURLConnection) new URL(url).openConnection();
                InputStreamReader inputStreamReader = new InputStreamReader(httpURLConnection.getInputStream());

                int read;
                char[] buff = new char[1024];
                while ((read = inputStreamReader.read(buff)) != -1) {
                    stringBuilder.append(buff, 0, read);
                }
                return stringBuilder.toString();
            } catch (MalformedURLException localMalformedURLException) {
                return "";
            } catch (IOException localIOException) {
                return "";
            } finally {
                if (httpURLConnection != null)
                    httpURLConnection.disconnect();
            }

        }

        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            target.onResponseComplete(result);
        }
    }.execute();
}

这是主要方法调用方法的方式

new JSONParser().getJSONFromUrl(url, new responseListener() {

        @Override
        public void onResponseComplete(String response) {
            try {
                ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
                JSONArray step = new JSONObject(response).getJSONArray("routes").getJSONObject(0).getJSONArray("legs")
                        .getJSONObject(0).getJSONArray("steps");

                for (int i = 0; i < step.length(); i++) {
                    HashMap<String,Object> row = new HashMap<String,Object>();
                    row.put("Distance", step.getJSONObject(i).getJSONObject("distance").getString("text"));
                    list.add(row);
                }

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

正确的问题是我想如何显示 Arraylist List 值并将其放入 TextView 调用 jarak

4

1 回答 1

0

您可以将您的列表更改为

ArrayList<HashMap<String, String>>

当您从

step.getJSONObject(i).getJSONObject("distance").getString("text")

为了得到它,你可以使用(假设你的 textview 被称为 jarak)

for(HashMap<String,String> map : list) {
     for(Entry<String, String> entry : map.entrySet()) {
         jarak.setText(entry.getKey() + ", " + entry.getValue());
     }
}

希望有帮助

于 2013-10-30T17:10:59.217 回答