你好我一直在尝试调整一个永无止境的listview来使用JSON数据而不仅仅是一个数组,我知道连接到服务器的代码和拉回数据的工作方式,因为我已经自己测试了它,但是在这段代码中我得到一个UnknownhostException,有没有人知道出了什么问题...... thnaks ..
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 :(得分:0)
你需要使用处理程序确定
当evrything完成后你运行线程你jus调用将更新UI的hadler
如果您在runnable loadMoreListItems
打电话给hendler使用这些:
handler.sendEmptyMessage(0);
处理程序
private Handler handler = new Handler() {
//af is your adpater these makes update to the UI :D
af.notifyDataSetChanged();
}