簡體   English   中英

在TextView上打印數組值(Android)

[英]Printing array values on a textview (android)

我正在嘗試在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上打印所有成員?

我希望將新值打印在新值下

因此,如果要將所有目標打印到TextView最有效的方法是使用例如StringBuffer創建完整的String,該字符串最終將分配給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;

最后從已經在UI Thread上運行並允許更新的onPostExecute()方法更新TextView

yourTextView.setText(result.toString());

注意:

不要忘記,通過使用Java命名約定,方法的簽名應以小寫字母開頭,而不應以大寫字母開頭。

嘗試這個:

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

您必須如圖所示更新UI線程上的TextView ,因為JSON響應是從與AsyncTask不同的線程中接收到的,否則將收到CalledFromTheWrongThreadException

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM