0

我正在尝试在 textView 中打印目标地址及其与原点的距离。但是,我不断收到错误或只显示最后一个值。我不想更新文本视图,我希望在新值下打印新值这是我的代码

public class MainActivity extends Activity {
        private static final String TAG_ROWS = "rows";
    private static final String TAG_ELEMENTS = "elements";
    private static final String TAG_DISTANCE = "distance";
    private static final String TAG_VALUE = "value";
    private static final String TAG_ADDRESS = "destination_addresses";
    String Addresses[]= {"2906+west+Broadway+Vancouver+BC","4750+Kingsway+Burnaby+BC","2633+Sweden+Way+110+Richmond","943+Marine+Dr+North+Vancouver","4567+Lougheed+Hwy+Burnaby"};

    String data;
    HttpClient client;
    double minDistance=0;
    static JSONObject jObj = null;
    String destination_addresses;
    JSONArray rows;
    String destination;
    String distanceStr;
    String[] value_destination;
    String value;
    final static String URL= "http://maps.googleapis.com/maps/api/distancematrix/json?";
    TextView result;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);
                result = (TextView) findViewById(R.id.text1);
                result.setText("Distace from the location" + destination + " is :" + distanceStr );

          new TestGoogleMaps().execute("");

        }
        public class TestGoogleMaps extends AsyncTask<String, Void, String>{
                @Override
                protected String doInBackground(String... params) {
                        // TODO Auto-generated method stub
                        try {
                    try {
                        ClosestObject();
                    } catch (ClientProtocolException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                finally {

                }
                        return null;
                }
                @Override
                protected void onPostExecute(String resuls) {
                        // TODO Auto-generated method stub
                        super.onPostExecute(resuls);
                 }
        }
        public void ClosestObject() throws JSONException, ClientProtocolException, IOException {

        // Creating JSON Parser instance
    StringBuilder url = new StringBuilder(URL);
    client=new DefaultHttpClient();
    for (int index=0; index<Addresses.length; index++){
    String str_parameters = "origins="+ URLEncoder.encode("1359+Richards+Street+Vancouver+BC","UTF-8")+"&destinations="+ URLEncoder.encode(Addresses[index],"UTF-8")+"&mode=driving&language="+ URLEncoder.encode("en-FR","UTF-8")+"&sensor=false";
    System.out.println("URL URl :: "+url+str_parameters);
   HttpGet get = new HttpGet(url+str_parameters);
   get.setHeader("Accept", "application/json");
   get.setHeader("Content-type", "application/json");
    HttpResponse r = client.execute(get);
    HttpEntity en = r.getEntity();
    data = EntityUtils.toString(en);
   System.out.println("ClosestObject Response :: "+data);


    try {
           jObj = new JSONObject(data);

            destination = jObj.getString("destination_addresses");
            // printing the destination and checking wheather parsed correctly
            Log.v("Destination", destination);

            JSONArray jarRow = jObj.getJSONArray("rows");
            for(int i=0;i<jarRow.length(); i++){
                // creating an object first
                JSONObject ElementsObj = jarRow.getJSONObject(i);
                // and getting the array out of the object
                JSONArray jarElements = ElementsObj.getJSONArray("elements");
                for(int j=0; j<jarElements.length(); j++){
                    JSONObject distanceObj = jarElements.getJSONObject(j).getJSONObject("distance");
                    distanceStr = distanceObj.getString("value");
                    Log.v("finally getting distance : ", distanceStr);

                }           }

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

        }     

        }
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
                // Inflate the menu; this adds items to the action bar if it is present.
                getMenuInflater().inflate(R.menu.main, menu);
                return true;
        }

}

如何在我的 TextView 上打印所有成员?

4

2 回答 2

1

我希望在新值下打印新值

因此,如果您想以TextView最有效的方式打印所有目的地,例如使用StringBuffer创建最终分配给您的 TextView 的整个字符串。

我建议您将 ClosestObject 方法的返回类型更改为 StringBuffer(或 Builder),并在循环中将数据附加到它。还将 AsyncTask 的第三个参数更改为 StringBuffer。

伪代码:

@Override
protected StringBuffer doInBackround() {
    ...
    StringBuffer buff = ClosestObject();
    return buff;
}

在您的 ClosestObject 方法中:

StringBuffer buff = new StringBuffer();
for (int i = 0; i < arr.length(); i++) {
   // getting values from JSON
   buff.append(value).append("\n"); // buff.append(value1 + "," + value2 + "\n")
}
...
return buff;

最后更新您TextView的 onPostExecute() 方法,该方法已经在 UI 线程上运行并允许更新。

yourTextView.setText(result.toString());

笔记:

不要忘记,通过 Java 中的命名约定,方法的签名应该以小写字母开头,而不是大写字母。

于 2013-04-02T21:30:06.500 回答
0

试试这个:

MainActivity.this.runOnUiThread(new Runnable() {
    public void run() {
        result.setText(result.getText().toString() + "\n" + distanceStr);
    }
});

如图所示,您必须更新TextViewUI 线程上的 ,因为 JSON 响应是在与您的 不同的线程中接收的AsyncTask,否则您将收到CalledFromTheWrongThreadException.

于 2013-04-02T21:27:24.090 回答