我有一個有趣的問題給你。我在Android中有一個函數,它通過從遠程服務器加載列表視圖來與UI進行交互。正如預期的那樣,這使得我的應用程序非常緩慢。在android中創建一個函數異步/線程
隨着代碼的最低金額,我怎麼把這個功能在自己的線程或同步任務,同時仍然允許它像一個正常的功能
它沒有非常有效的執行。我只需要用盡可能少的代碼就可以做到這一點。
try
{ //getjson file
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
InputStream instream = resEntityGet.getContent();
BufferedReader str = new BufferedReader(new InputStreamReader(
instream));
String ans = new String("");
build = new String("");
while ((ans = str.readLine()) != null) {
build = build + ans;
}
//parse json file
JSONObject total = new JSONObject(build);
JSONArray prices = null;
if (!total.isNull("title")){
Prices = title.getJSONArray("title"));}
ArrayList<data> newArray = new ArrayList<data>();
for(int i=0;i<Prices.length();i++)
{
JSONObject price = null;
price = Prices.getJSONObject(i);
data name = new data (price.getString("StoreName"),price.getString("price"),price.getString("Link"));
newArray.add(name);
}
stockArr = new data[newArray.size()];
stockArr = newArray.toArray(stockArr);
//add to listview
ListView listView = (ListView) findViewById(R.id.mylist);
listadapter adapter = new listadapter(this,R.layout.listview_item_row, stockArr);
listView.setAdapter(adapter);
}
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(),e.toString(), 10).show();
}
「隨着代碼的最低金額」 - 所以是不玩'代碼Golf',IMNSHO – lenik
發佈您的代碼的地方。理想情況下,您應該訪問遠程服務器,獲取數據,在後臺解析數據並更新onPostExecute中的適配器。另外,如果你想要中間更新,你可以使用onProgressUpdate,當分析巨大的響應時很有用 – Atrix1987
你剛說的哪些東西是可跳過的? – gaara87