我有一个有趣的问题要问你。我在 Android 中有一个函数,它通过从远程服务器加载带有数据的列表视图来与 ui 交互。正如预期的那样,这使我的应用程序非常缓慢。
使用最少的代码,我如何将这个函数放在它自己的线程或同步任务上,同时仍然允许它像普通函数一样执行
它不是非常有效。我只需要用尽可能少的代码来做到这一点。
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();
}