異步線程AsyncTask_2示例(07)

//異步線程AsyncTask:開啓線程下載,配合Json解析,還有適配器進度條、等控件使用(07)

public class MainActivity extends Activity {
	private Spinner spinner;
	private ArrayAdapter<String> adapter;
	private ProgressBar pb;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		this.spinner = (Spinner) this.findViewById(R.id.spinner);
		String url = "http://litchiapi.jstv.com/api/GetFeeds?column=0&PageSize=20&pageIndex=1&val=100511D3BE5301280E0992C73A9DEC41";
		this.pb = (ProgressBar) this.findViewById(R.id.pb);
		new Mytask(this).execute(url);
	}

	class Mytask extends AsyncTask<String, Integer, byte[]> {
		private ProgressDialog dialog;

		public Mytask(Context context) {
			/*
			 * //這裏不用對話提示了,採用進度條 dialog = new ProgressDialog(context);
			 * dialog.setTitle("提示"); dialog.setMessage("正在下載數據!!");
			 */
		}

		@Override
		protected void onPreExecute() {
			pb.setVisibility(View.VISIBLE);// 顯示進度條
			/*
			 * dialog.show();//打開對話框 try { Thread.sleep(1000); } catch
			 * (InterruptedException e) { e.printStackTrace(); }
			 */
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			pb.setProgress(values[0]);
		}

		@Override
		protected byte[] doInBackground(String... params) {
			// 下載JSON字符串
			String url = params[0];
			HttpClient client = new DefaultHttpClient();
			HttpGet get = new HttpGet(url);
			try {
				HttpResponse response = client.execute(get);
				if (response.getStatusLine().getStatusCode() == 200) {
					long totallenth = response.getEntity().getContentLength();
					BufferedInputStream br = new BufferedInputStream(response
							.getEntity().getContent());
					ByteArrayOutputStream bos = new ByteArrayOutputStream();
					int count = 0;// 進度條每次累加更新
					int len = -1;
					byte[] buf = new byte[100];
					while ((len = br.read(buf)) != -1) {
						bos.write(buf, 0, len);
						count += len;
						// 進度條計算
						int le = (int) ((count / (double) totallenth) * 100);
						publishProgress(le);// 進度條更新
						try {
							// Thread.currentThread().sleep(100);
							Thread.sleep(10);// 數據都過小太快,睡一下
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
					br.close();
					return bos.toByteArray();
				}
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(byte[] result) {
			if (result != null) {
				List<String> list = parser(new String(result));
				adapter = new ArrayAdapter<String>(MainActivity.this,
						android.R.layout.simple_list_item_1, list);
				spinner.setAdapter(adapter);//綁定數據和適配器
			} else {
				Toast.makeText(MainActivity.this, "網絡鏈接錯誤!!",
						Toast.LENGTH_SHORT).show();
			}
			pb.setVisibility(View.GONE);// 隱藏進度條
			// dialog.dismiss();//關閉對話框
		}

		private List<String> parser(String json) {
			List<String> list = new ArrayList<String>();
			try {
				JSONObject obj = new JSONObject(json);
				JSONObject object_paramz = obj.getJSONObject("paramz");
				JSONArray array_feeds = object_paramz.getJSONArray("feeds");
				for (int i = 0; i < array_feeds.length(); i++) {
					JSONObject object = array_feeds.getJSONObject(i);
					JSONObject object_data = object.getJSONObject("data");
					list.add(object_data.getString("subject"));
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return list;
		}

	}
}

//佈局
 <ProgressBar
        android:id="@+id/pb"
        style="@android:style/Widget.ProgressBar.Horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:visibility="gone" />

    <Spinner
        android:id="@+id/spinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
相關文章
相關標籤/搜索