-1

嗨,我正在编写一个 android 应用程序以从 url 获取信息并将其显示在 ListView 中。一切都运作良好。但是显示视图需要很长时间,因为我从onCreate()方法上的 url 读取文件。

  1. 我想从 URL 异步读取,所以视图响应时间不会受到损害。
  2. 我正确使用 ProgressBar 吗?

    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;
       }
    
    } 
    
4

2 回答 2

2

应该使用 AsyncTask 将繁重的工作从 UI 线程中移开。http://developer.android.com/reference/android/os/AsyncTask.html

于 2012-07-29T05:43:05.083 回答
0

我认为您应该使用可运行的。演示代码:

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);

试试看。^-^

于 2012-07-29T05:39:45.873 回答