2014-09-21 74 views
0

我有一個問題,這不是很大,但對用戶來說是不好的。 該應用程序基本上獲取用戶對某個地方的輸入,並且當用戶單擊該按鈕時,帶有參數位置的Google API的URL將被髮送到AsyncTask,並通過HttpGet發送該URL並返回JSONArray與所需的一切。問題是,當我點擊按鈕和互聯網並不好,按鈕似乎「凍結」是這樣的:執行AsyncTask時如何不影響UI?

button freezed http://oi62.tinypic.com/34hfa4i.jpg

我的活動代碼如下:

public class MainActivity extends Activity{ 

    ... 

    protected void onCreate(Bundle savedInstanceState){...} 

    public void onResume()} 

     btnSearch.setOnClickListener(new View.OnClickListener(){ 
      @Override 
      public void onClick(View v){ 
       String search = txtSearch.getText().toString(); 

       try{ 
        List<Location> locations = new SearchTask(MainActivity.this).execute(strSearch).get(); 

        if(locations != null){ 
         ArrayAdapter<Location> adapter = new ArrayAdapter<Location>(MainActivity.this, android.R.layout.simple_list_item_1, locations); 
         listView.setAdapter(adapter); 

         ... 

        } 
       } 
      } 
     } 
    } 
} 

我的AsyncTask類代碼如下:

public class SearchTask extends AsyncTask<String, Void, List<Location>>{ 

    ... 

    protected List<Location> doInBackground(String... params){ 
     if(isNetworkAvailable()){ 
      HttpGet httpGet = null; 
      HttpClient client = null; 
      HttpResponse response = null; 
      StringBuilder builder = null; 

      try{ 
       String param = URLDecoder.decode(params[0], "UTF-8").replace(" ", "%20"); 
       httpGet = new HttpGet("http://maps.googleapis.com/maps/api/geocode/json?address=" + param + "&sensor=false"); 
       client = new DefaultHttpClient(); 
       builder = new StringBuilder(); 
      } 
      catch(UnsupportedEncodingException e){ 
       Log.i("Error", e.getMessage()); 
      } 

      try{ 
       response = client.execute(httpGet); 
       HttpEntity entity = response.getEntity(); 
       InputStream stream = entity.getContent(); 
       BufferedReader br = new BufferedReader(new InputStreamReader(stream, "UTF-8")); 
       int val; 

       while((val = br.read()) != -1){ 
        builder.append((char) val); 
       } 
      } 
      catch(IOException e){ 
       Log.i("Error", e.getMessage()); 
      } 

      JSONObject jsonObject = new JSONObject(); 

      List<Location> listLocation = new ArrayList<Location>(); 

      int countJson = 0; 

      try{ 
       jsonObject = new JSONObject(builder.toString()); 

       JSONArray jArray = jsonObject.getJSONArray("results"); 
       countJson = jArray.length(); 

       for(int i = 0; i < countJson; i++){ 
        Location location = new Location(); 

        String formattedAddress = ((JSONArray) jsonObject.get("results")).getJSONObject(i).getString("formatted_address"); 

        double lat = ((JSONArray) jsonObject.get("results")).getJSONObject(i).getJSONObject("geometry").getJSONObject("location").getDouble("lat"); 

        double lng = ((JSONArray) jsonObject.get("results")).getJSONObject(i).getJSONObject("geometry").getJSONObject("location").getDouble("lng"); 

        location.setFormattedAddress(formattedAddress); 
        location.setLat(lat); 
        location.setLng(lng); 

        listLocation.add(location); 
       } 
      } 
      catch(JSONException e){ 
       Log.i("Error", e.getMessage()); 
      } 

      return listLocation; 
     } 
     else{ 
      return null; 
     } 
    } 

    @Override 
    protected void onPreExecute(){ 
     super.onPreExecute(); 

     progress = new ProgressDialog(context); 
     progress.setMessage("Loading..."); 
     progress.show(); 
    } 

    @Override 
    protected void onPostExecute(List<Location> result){ 
     super.onPostExecute(); 

     progress.dismiss(); 
    } 

    private boolean isNetworkAvailable(){ 
     ConnectivityManager connManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); 
     NetworkInfo info = connManager.getActiveNetworkInfo(); 
     return info != null && info.isConnected(); 
    } 
} 

ListView與EditView和Button的xml相同。

有沒有一種方法來改善它,以使UI不像這樣行爲?

謝謝!

回答

0

試試這個:

btnSearch.setOnClickListener(new View.OnClickListener(){ 
    @Override 
    public void onClick(View v){ 
     String search = txtSearch.getText().toString();  
     new SearchTask(MainActivity.this).execute(strSearch); 
    } 
} 

@Override 
protected void onPostExecute(List<Location> locations){ 
    if(locations != null){ 
     ArrayAdapter<Location> adapter = new ArrayAdapter<Location>(MainActivity.this, android.R.layout.simple_list_item_1, locations); 
     listView.setAdapter(adapter); 
    } 
     progress.dismiss(); 
} 
+0

是的,它的伎倆。非常感謝! – 2014-09-21 20:01:19