Java 从URL异步获取数据
嗨,我正在编写一个android应用程序,以便从url获取信息并在列表视图中显示。一切都很顺利。但是显示视图需要很长时间,因为我从Java 从URL异步获取数据,java,android,url,view,Java,Android,Url,View,嗨,我正在编写一个android应用程序,以便从url获取信息并在列表视图中显示。一切都很顺利。但是显示视图需要很长时间,因为我从onCreate()方法上的url读取文件 我希望异步读取URL,这样就不会影响视图响应时间 我是否正确使用ProgressBar public class cseWatch extends Activity { TextView txt1 ; Button btnBack; ListView listView1; /** Calle
onCreate()
方法上的url读取文件
public class cseWatch extends Activity {
TextView txt1 ;
Button btnBack;
ListView listView1;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.searchresult);
Button btnBack=(Button) findViewById(R.id.btn_bck);
btnBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent MyIntent1 = new Intent(v.getContext(),cseWatchMain.class);
startActivity(MyIntent1);
}
});
ArrayList<SearchResults> searchResults = GetSearchResults();
//after loaded result hide progress bar
ProgressBar pb = (ProgressBar) findViewById(R.id.progressBar1);
pb.setVisibility(View.INVISIBLE);
final ListView lv = (ListView) findViewById(R.id.listView1);
lv.setAdapter(new MyCustomBaseAdapter(cseWatch.this, searchResults));
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Object o = lv.getItemAtPosition(position);
SearchResults fullObject = (SearchResults)o;
Toast.makeText(cseWatch.this, "You have chosen: " + " " + fullObject.getName(), Toast.LENGTH_LONG).show();
}
});
}//end of onCreate
private ArrayList<SearchResults> GetSearchResults(){
ArrayList<SearchResults> results = new ArrayList<SearchResults>();
SearchResults sr;
InputStream in;
try{
txt1 = (TextView) findViewById(R.id.txtDisplay);
txt1.setText("Sending request...");
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://www.myurl?reportType=CSV");
HttpResponse response = httpclient.execute(httpget);
in = response.getEntity().getContent();
txt1.setText("parsing CSV...");
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
try {
String line;
reader.readLine(); //IGNORE FIRST LINE
while ((line = reader.readLine()) != null) {
String[] RowData = line.split(",");
sr = new SearchResults();
String precent = String.format("%.2g%n",Double.parseDouble(RowData[12])).trim();
double chng=Double.parseDouble(RowData[11]);
String c;
if(chng > 0){
sr.setLine2Color(Color.GREEN);
c="▲";
}else if(chng < 0){
sr.setLine2Color(Color.rgb(255, 0, 14));
c="▼";
}else{
sr.setLine2Color(Color.rgb(2, 159, 223));
c="-";
}
sr.setName(c+RowData[2]+"-"+RowData[1]);
DecimalFormat fmt = new DecimalFormat("###,###,###,###.##");
String price = fmt.format(Double.parseDouble(RowData[6])).trim();
String tradevol = fmt.format(Double.parseDouble(RowData[8])).trim();
sr.setLine1("PRICE: Rs."+price+" TRADE VOL:"+tradevol);
sr.setLine2("CHANGE:"+c+RowData[11]+" ("+precent+"%)");
results.add(sr);
txt1.setText("Loaded...");
// do something with "data" and "value"
}
}
catch (IOException ex) {
Log.i("Error:IO",ex.getMessage());
}
finally {
try {
in.close();
}
catch (IOException e) {
Log.i("Error:Close",e.getMessage());
}
}
}catch(Exception e){
Log.i("Error:",e.getMessage());
new AlertDialog.Builder(cseWatch.this).setTitle("Watch out!").setMessage(e.getMessage()).setNeutralButton("Close", null).show();
}
return results;
}
}
public类cseWatch扩展活动{
TextView txt1;
按钮btnBack;
列表视图列表视图1;
/**在首次创建活动时调用*/
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.searchresult);
按钮btnBack=(按钮)findViewById(R.id.btn\u bck);
btnBack.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
//TODO自动生成的方法存根
Intent MyIntent1=新的Intent(v.getContext(),cseWatchMain.class);
星触觉(MyIntent1);
}
});
ArrayList searchResults=GetSearchResults();
//加载结果后隐藏进度条
ProgressBar pb=(ProgressBar)findViewById(R.id.progressBar1);
pb.setVisibility(视图不可见);
最终ListView lv=(ListView)findViewById(R.id.listView1);
lv.setAdapter(新的MyCustomBaseAdapter(cseWatch.this,searchResults));
lv.setOnItemClickListener(新的OnItemClickListener(){
@凌驾
公共视图单击(适配器视图a、视图v、内部位置、长id){
对象o=lv.getItemAtPosition(位置);
SearchResults fullObject=(SearchResults)o;
Toast.makeText(cseWatch.this,“您已经选择了:”+“”+fullObject.getName(),Toast.LENGTH_LONG.show();
}
});
}//onCreate结束
私有ArrayList GetSearchResults(){
ArrayList结果=新建ArrayList();
搜索结果sr;
输入流输入;
试一试{
txt1=(TextView)findViewById(R.id.txtDisplay);
setText(“发送请求…”);
DefaultHttpClient httpclient=新的DefaultHttpClient();
HttpGet HttpGet=新的HttpGet(“http://www.myurl?reportType=CSV");
HttpResponse response=httpclient.execute(httpget);
in=response.getEntity().getContent();
setText(“解析CSV…”);
BufferedReader reader=新的BufferedReader(新的InputStreamReader(in));
试一试{
弦线;
reader.readLine();//忽略第一行
而((line=reader.readLine())!=null){
String[]RowData=line.split(“,”);
sr=新的搜索结果();
String-precent=String.format(“%.2g%n”,Double.parseDouble(RowData[12])).trim();
double chng=double.parseDouble(RowData[11]);
字符串c;
如果(变化>0){
高级setline2颜色(颜色为绿色);
c=”▲";
}else if(chng<0){
sr.setLine2Color(Color.rgb(255,0,14));
c=”▼";
}否则{
高级setLine2Color(Color.rgb(2159223));
c=“-”;
}
sr.setName(c+RowData[2]+“-”+RowData[1]);
DecimalFormat fmt=新的DecimalFormat(“#####,###,###,##,###”);
String price=fmt.format(Double.parseDouble(RowData[6])).trim();
字符串tradevol=fmt.format(Double.parseDouble(RowData[8])).trim();
sr.setLine1(“价格:卢比”+价格+交易量:”+交易量);
sr.setLine2(“变更:“+c+RowData[11]+”(“+PRENT+”)”);
结果:添加(sr);
txt1.setText(“已加载…”);
//用“数据”和“价值”做点什么
}
}
捕获(IOEX异常){
Log.i(“错误:IO”,例如getMessage());
}
最后{
试一试{
in.close();
}
捕获(IOE异常){
Log.i(“错误:关闭”,例如getMessage());
}
}
}捕获(例外e){
Log.i(“错误:,e.getMessage());
新建AlertDialog.Builder(cseWatch.this).setTitle(“小心!”).setMessage(e.getMessage()).setNeutralButton(“关闭”,null).show();
}
返回结果;
}
}
我认为你应该使用一个可运行的。 演示代码:
final ListView lv = (ListView) findViewById(R.id.listView1);
Handler handler = new Handler(app.getMainLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
lv.setAdapter(new MyCustomBaseAdapter(cseWatch.this, searchResults));
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Object o = lv.getItemAtPosition(position);
SearchResults fullObject = (SearchResults)o;
Toast.makeText(cseWatch.this, "You have chosen: " + " " + fullObject.getName(), Toast.LENGTH_LONG).show();
}
});
}
}, 1000);
final ListView lv=(ListView)findviewbyd(R.id.listView1);
Handler=newhandler(app.getMainLooper());
handler.postDelayed(新的Runnable(){
@凌驾
公开募捐{
lv.setAdapter(新的MyCustomBaseAdapter(cseWatch.this,searchResults));
lv.setOnItemClickListener(新的OnItemClickListener(){
@凌驾
公共视图单击(适配器视图a、视图v、内部位置、长id){
对象o=lv.getItemAtPosition(位置);
SearchResults fullObject=(SearchResults)o;
Toast.makeText(cseWatch.this,“您已经选择了:”+“”+fullObject.getName(),Toast.LENGTH_LONG.show();
}
});
}
}, 1000);
试试看。^-^应使用AsyncTask将heavylifting从UI线程移开