AsyncTask 异步任务 + json 解析 网络数据
2016-08-30 22:05
453 查看
package com.qf.day07_asynctask_04; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.List; import android.app.Activity; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ProgressBar; import android.widget.Spinner; import android.widget.Toast; public class MainActivity extends Activity { private ProgressBar progressBar; private Spinner spinner; private MyTask myTask; private String path = "http://m2.qiushibaike.com/article/list/suggest?page=1"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); progressBar = (ProgressBar) findViewById(R.id.progress_id); spinner = (Spinner) findViewById(R.id.spinner_id); } // 按钮点击事件 public void clickButton(View v) { switch (v.getId()) { case R.id.start: // 开启异步任务, 下载内容 myTask = new MyTask(); myTask.execute(path); break; case R.id.stop: // 停止异步任务 myTask.cancel(true); break; } } /** * 自定义异步任务, 加载数据(json) * * @author Administrator * */ public class MyTask extends AsyncTask<String, Integer, List<String>> { @Override protected void onPreExecute() { // TODO 事前方法, 初始化工作 super.onPreExecute(); // 进度条显示 progressBar.setVisibility(View.VISIBLE); // 当前的进度值=0 progressBar.setProgress(0); } @Override protected List<String> doInBackground(String... params) { // TODO 后台运行, 执行耗时的操作 try { // 向网络获取数据json URL url = new URL(params[0]); HttpURLConnection conn = (HttpURLConnection) url .openConnection(); conn.setRequestMethod("GET"); // 请求数据时不能以压缩的方式返回 conn.setRequestProperty("Accept-Encoding", "identity"); conn.connect(); if (conn.getResponseCode() == 200) { InputStream is = conn.getInputStream(); // 得到数据的总长度 long maxLen = conn.getContentLength(); Log.i("info", "maxLen = " + maxLen); // 得到数据当前的加载长度 long curLen = 0; // 读取数据 byte[] buffer = new byte[1024]; int len = 0; StringBuilder sBuilder = new StringBuilder(); while ((len = is.read(buffer)) != -1) { sBuilder.append(new String(buffer, 0, len)); // 计算当前加载的进度值 百分比 // int progress = (int)(当前加载的长度 *100 / 总长度); curLen += len; int progress = (int) (curLen * 100 / maxLen); // 异步更新进度条(onProgressUpdate(Integer... values)) publishProgress(progress); Thread.sleep(500); } // 解析数据,并且返回 return ParseJson.parseJson(sBuilder.toString()); } } catch (Exception e) { // TODO: handle exception } return null; } @Override protected void onProgressUpdate(Integer... values) { // TODO 实时更新进度 super.onProgressUpdate(values); // 实时更新进度条 progressBar.setProgress(values[0]); } @Override protected void onPostExecute(List<String> result) { // TODO 事后方法: 更新UI super.onPostExecute(result); // 进度条消失 progressBar.setVisibility(View.GONE); // 通过适配器, 将获取到的数据填充到Spinner中 if (result != null && result.size() > 0) { // 控件 spinner // 数据源 result // 适配器 ArrayAdapter<String> adapter = new ArrayAdapter<String>( MainActivity.this, android.R.layout.simple_spinner_item, result); spinner.setAdapter(adapter); } else { Toast.makeText(MainActivity.this, "网络异常", Toast.LENGTH_LONG) .show(); } } } }
package com.qf.day07_asynctask_04; import java.util.ArrayList; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * 解析json数据 * @author Administrator * */ public class ParseJson { public static List<String> parseJson(String jsonStr) throws JSONException { List<String> data = new ArrayList<String>(); if(jsonStr!=null) { JSONObject jsonObject = new JSONObject(jsonStr); JSONArray jsonArray = jsonObject.getJSONArray("items"); for(int i=0;i<jsonArray.length();i++) { JSONObject jsonObject2 = jsonArray.getJSONObject(i); String content = jsonObject2.getString("content"); data.add(content); } } return data; } }
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <Button android:id="@+id/start" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="获取数据" android:onClick="clickButton" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/stop" android:text="停止获取" android:layout_toRightOf="@id/start" android:onClick="clickButton" /> <ProgressBar android:layout_width="match_parent" android:layout_height="20dp" android:id="@+id/progress_id" android:layout_below="@id/start" android:layout_marginTop="20dp" style="?android:attr/progressBarStyleHorizontal" android:visibility="gone" /> <Spinner android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/spinner_id" android:layout_below="@id/progress_id" android:layout_marginTop="20dp" /> </RelativeLayout>
相关文章推荐
- Android数据解析之JSON,网络编程之URL,异步任务AsyncTask讲解
- 【Android学习笔记系列】AsyncTask、BaseAdapter整合异步加载用例(通过解析JSON格式数据加载网络图片内容)
- Android之异步任务AsyncTask解析Json数据
- Android之异步任务AsyncTask解析XML数据
- Android Studio利用异步任务AsyncTask发送post请求获取json数据
- Android Studio利用异步任务AsyncTask发送post请求获取json数据
- 08、异步任务AsyncTask及JSON解析
- IOS-网络(HTTP请求、同步请求、异步请求、JSON解析数据)
- Android--使用原生技术实现ListView(原生技术实现网络异步请求,解析json数据)
- 异步任务访问服务端数据,解析json
- AsyncTask异步任务加载网络数据
- Android异步任务AsyncTask使用解析 获取网络图片
- 异步任务AsyncTask及JSON解析
- 使用异步任务加载网络上json数据并加载到ListView中
- 异步任务AsyncTask及JSON解析
- Android Studio利用异步任务AsyncTask发送post请求获取json数据
- Android 利用异步任务AsyncTask发送post请求获取json数据
- android结合异步任务,动态加载图片,Json解析数据展示在ListView,并且实现按日期分类展示,借口回调
- 异步任务加载网络数据——AsyncTask使用
- 使用AsyncTask异步加载类进行访问网络数据json的理解和用法