2011-05-02 64 views
0

你好我一直在尝试调整一个永不结束的listview使用JSON数据,而不是一个数组,我知道连接到服务器的代码,并拉回数据的工作,因为我已经测试了它自己的,但这段代码我得到的UnknownHostException内,没有任何人有任何想法是错误的... .. thnaksAndroid滚动自动增长列表视图

public class NeverEndingList extends ListActivity { 


//how many to load on reaching the bottom 
int itemsPerPage = 15; 
boolean loadingMore = false;  
int rowsSTART = 0; 
int rowsEND = itemsPerPage; 
ArrayList<String> myListItems; 
ArrayAdapter<String> adapter; 

//For test data :-) 
Calendar d = Calendar.getInstance(); 


/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) {  
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.listplaceholder); 



    //This will hold the new items 
    myListItems = new ArrayList<String>(); 
    adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, myListItems); 




    //add the footer before adding the adapter, else the footer will nod load! 
    View footerView = ((LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.listfooter, null, false); 
    this.getListView().addFooterView(footerView); 

    //Set the adapter 
    this.setListAdapter(adapter); 
    //Here is where the magic happens 
    this.getListView().setOnScrollListener(new OnScrollListener(){ 

     //useless here, skip! 
     @Override 
     public void onScrollStateChanged(AbsListView view, int scrollState) {} 

     //dumdumdum   
     @Override 
     public void onScroll(AbsListView view, int firstVisibleItem, 
       int visibleItemCount, int totalItemCount) { 


      //what is the bottom iten that is visible 
      int lastInScreen = firstVisibleItem + visibleItemCount;    

      //is the bottom item visible & not loading more already ? Load more ! 
      if((lastInScreen == totalItemCount) && !(loadingMore)){     
       Thread thread = new Thread(null, loadMoreListItems); 
       thread.start(); 
      } 
     } 
    }); 



    //Load the first 15 items 
    Thread thread = new Thread(null, loadMoreListItems); 
    thread.start(); 

} 


//Runnable to load the items 

private Runnable loadMoreListItems = new Runnable() { 
    JSONArray jArray=null; 
    @Override 
    public void run() { 
     //Set flag so we cant load new items 2 at the same time 
     loadingMore = true; 
     //Reset the array that holds the new items 
     myListItems = new ArrayList<String>(); 
     //Simulate a delay, delete this on a production environment! 
     try { Thread.sleep(1000); 
     } catch (InterruptedException e) {} 

     try 
     { 
     new Thread(new Runnable() 
     { 
      public void run() 
       { 
        Looper.prepare(); 
      int xx=0; 
      Map<String, String> params = new HashMap<String, String>(); 
      //params.put("X", String.valueOf(rowsSTART)); 
      //params.put("Y", String.valueOf(rowsEND)); 
      params.put("X", "10"); 
      params.put("Y", "5"); 

      InputStream is = null; 
      String result = ""; 
      // loop round dynamic array of parameters 
      ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>(); 
      Iterator<String> it = params.keySet().iterator(); 
      while(it.hasNext()) 
      { 
       String key=(String)it.next(); 
       String value=(String)params.get(key); 
       postParameters.add(new BasicNameValuePair(key,value)); 
      } 

      try{ 

       HttpClient httpclient = new DefaultHttpClient(); 
       HttpPost httppost = new HttpPost("http://www.phoneinternational.biz/proccityLimit.php");      
       httppost.setEntity(new UrlEncodedFormEntity(postParameters)); 
       HttpResponse response = httpclient.execute(httppost); 
       HttpEntity entity = response.getEntity(); 
       //InputStream is = entity.getContent(); 
       is = entity.getContent(); 
      }catch(Exception e){ 
       Log.e("log_tag", "X1:: "+e.toString()); 
      // if (DEBUG_LOG) { Log.e("log_tag", "ProcessHTTPRequest:Error in http connection "+e.toString()); } 
      } 
      //Toast.makeText(getApplicationContext(), "HERE2", 10).show(); 


      //convert response to string 
      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(); 
       result=sb.toString(); 
      }catch(Exception e){ 
       Log.e("log_tag", "X2:: "+e.toString()); 
      // if (DEBUG_LOG) { Log.e("log_tag", "ProcessHTTPRequest:Error converting result "+e.toString()); } 
      } 

      try { 
      jArray = new JSONArray(result); 
      for(int i=0;i<jArray.length();i++){ 
        JSONObject json_data = jArray.getJSONObject(i); 
        myListItems.add(json_data.getString("city")); 
      } 
      } 
      catch (Exception e) {Log.e("log_tag", "X3:: "+e.toString()); } 
     // return(null); 
      } 
    //   catch(Exception e) { } 
       // Looper.loop(); 


      //   } 

       }).start(); 
       } 
    //  } 
       catch (Exception e) { 
        Log.e("log_tag", "X3:: "+e.toString()); 
       //  if (DEBUG_LOG) { Log.e("WorldDialer:loadData",e.getMessage(),e); } 
       } 

       //Done! now continue on the UI thread 
    try { 

    } 
    catch (Exception e) {Log.e("log_tag", "X3:: "+e.toString()); } 
    // return(null); 
    runOnUiThread(returnRes); 
    } 

}; 


//Since we cant update our UI from a thread this Runnable takes care of that! 
private Runnable returnRes = new Runnable() { 
    @Override 
    public void run() {   
     rowsSTART = rowsEND; 

     //Loop thru the new items and add them to the adapter 
     if(myListItems != null && myListItems.size() > 0){ 
      for(int i=0;i<myListItems.size();i++) 
       adapter.add(myListItems.get(i)); 
     } 

     //Update the Application title 
     rowsEND += itemsPerPage; 

     setTitle(" List start: " + String.valueOf(rowsSTART) + " items END:" + String.valueOf(rowsEND)); 

     //Tell to the adapter that changes have been made, this will cause the list to refresh 
     adapter.notifyDataSetChanged(); 

     //Done loading more. 
     loadingMore = false; 
    } 

}; 




// 
// connect to webserver and retrieve data 
// 
public String loadData(String URL, Map<String, String> params) 
{ 
    InputStream is = null; 
    String result = ""; 
    // loop round dynamic array of parameters 
    ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>(); 
    Iterator<String> it = params.keySet().iterator(); 
    while(it.hasNext()) 
    { 
     String key=(String)it.next(); 
     String value=(String)params.get(key); 
     postParameters.add(new BasicNameValuePair(key,value)); 
    } 


    try{ 
     HttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httppost = new HttpPost(URL); 
     httppost.setEntity(new UrlEncodedFormEntity(postParameters)); 
     HttpResponse response = httpclient.execute(httppost); 
     HttpEntity entity = response.getEntity(); 
     // InputStream is = entity.getContent(); 
     is = entity.getContent(); 
    }catch(Exception e){ 
    // if (DEBUG_LOG) { Log.e("log_tag", "ProcessHTTPRequest:Error in http connection "+e.toString()); } 
    } 



    //convert response to string 
    try{ 
     BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); 
     StringBuilder sb = new StringBuilder(); 
     String line = null; 
     while ((line = reader.readLine()) != null) { 
      Toast.makeText(getApplicationContext(),line,10).show(); 
       sb.append(line + "\n"); 
     } 
     is.close(); 
     result=sb.toString(); 
    }catch(Exception e){ 
    // if (DEBUG_LOG) { Log.e("log_tag", "ProcessHTTPRequest:Error converting result "+e.toString()); } 
    } 
    return result; 
} 

回答

0

您需要使用处理程序确定

你让线程运行当evrything完成后,你可以打电话给hadler,它将更新UI

你的情况,如果你plase到哈德勒呼叫上可运行的loadMoreListItems

调用亨德勒使用这些:

handler.sendEmptyMessage(0); 

处理程序

private Handler handler = new Handler() { 
//af is your adpater these makes update to the UI :D 
af.notifyDataSetChanged(); 
} 
+0

你好subspider感谢您的答复,你可以给我更详细的如何做到这一点。真的,我想要做的是这样的:http://androidboss.com/load-listview-in-background-asynctask/但所有的例子似乎使用预定义的x项目数组,但是这打败了对象我正在尝试做什么,我不知道他们有多少物品来自网络?谢谢伊恩 – Ian 2011-05-04 10:06:35