使用Spinner和AsyncTask 下載數據綁定到Spinner

 

功能:一個Spinner 從網絡上下載數據 而後綁定到Spinner
//記得配置聯網權限android

一、在佈局界面佈局 activity_main.xmljson

代碼api

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
   android:orientation="vertical">網絡

    <Spinner
        android:id="@+id/spinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />
    <Button
        android:id="@+id/bt_download"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="下載數據"
        android:onClick="downLoad"
        />
   
     <ProgressBar
        android:id="@+id/pb"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        style="?android:attr/progressBarStyleHorizontal"
        android:visibility="gone"
        />ide

</LinearLayout>工具

----------------------------------------佈局

二、MainActivity 類this

代碼url

public class MainActivity extends Activity {
private Spinner sp;
private ArrayAdapter<String> adapter;
private ProgressBar pb;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  this.sp = (Spinner) this.findViewById(R.id.spinner);
  this.pb = (ProgressBar) this.findViewById(R.id.pb);
 }
 
//按鈕 事件監聽
 public void downLoad(View view){
  String url = "http://litchiapi.jstv.com/api/GetFeeds?column=0&PageSize=20&pageIndex=1&val=100511D3BE5301280E0992C73A9DEC41";
  new MyAsyncTask().execute(url);
 }
 class MyAsyncTask extends AsyncTask<String, Integer, byte[]>{xml

//  private ProgressDialog dialog;
//  public MyAsyncTask(Context context) {
//   dialog = new ProgressDialog(context);
//   dialog.setTitle("舒適提示");
//   dialog.setMessage("數據下載中,請稍等...");
//   dialog.setIcon(R.drawable.ic_launcher);
//  }
  @Override
  protected void onPreExecute() {
   super.onPreExecute();
   //dialog.show();
//當按下按鈕後 就啓動工具類 而後顯示進度條
   pb.setVisibility(View.VISIBLE);
  }
  @Override
    protected void onProgressUpdate(Integer... values) {
     super.onProgressUpdate(values);
//更新進度條
     pb.setProgress(values[0]);
    }
  @Override
  protected byte[] doInBackground(String... params) {
   String url = params[0];
   HttpGet get = new HttpGet(url);
   HttpClient client = new DefaultHttpClient();
   try {
    HttpResponse response = client.execute(get);
    long totalLength = response.getEntity().getContentLength();
    byte[] b = new byte[1024];
    int count = 0;
    int len = 0;
    if(response.getStatusLine().getStatusCode() == 200){
     BufferedInputStream bis = new BufferedInputStream(response.getEntity().getContent());
     ByteArrayOutputStream bos = new ByteArrayOutputStream();
     while((len = bis.read(b)) != -1){
       bos.write(b, 0, len);
       bos.flush();
       count+=len;
       int l = (int)((count/(double)totalLength)*100);
       publishProgress(l);
      
     }
     bis.close();
     
     return bos.toByteArray();
    }
   } catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   return null;
  }
  @Override
  protected void onPostExecute(byte[] result) {
   if(result != null){
//下載完數據 就使用json解析 下載的數據
   List<String> list = jsonMethod(new String(result,0,result.length));
//把解析好的數據丟到ArrayAdapter適配器裏
   adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1,list);
//把適配器綁定到Spinner裏
   sp.setAdapter(adapter);
   }else{
    Toast.makeText(MainActivity.this, "數據下載失敗!", Toast.LENGTH_SHORT).show();
   }
   //dialog.dismiss();
   pb.setVisibility(View.GONE);
  }

 } public List<String> jsonMethod(String string) {  List<String> list = new ArrayList<String>();  try {   JSONObject object = new JSONObject(string);   JSONObject object_paramz = object.getJSONObject("paramz");   JSONArray object_feeds = object_paramz.getJSONArray("feeds");   for(int i = 0;i<object_feeds.length();i++){    JSONObject object_data = object_feeds.getJSONObject(i).getJSONObject("data");    String data = object_data.getString("subject");    list.add(data);   }  } catch (JSONException e) {   // TODO Auto-generated catch block   e.printStackTrace();  }  return list; }}

相關文章
相關標籤/搜索