json解析網路傳值
阿新 • • 發佈:2019-02-15
//這裡是引導頁的程式碼
public class MainActivity extends AppCompatActivity { //這裡有個R 報錯 cannot resolve symbol'R' 這個在File 下 invalidate caches Ressart 裡點 cle 然後重啟就好了 private ViewPager viewpager; private Button button; private int[] pics=new int[]{R.drawable.m4,R.drawable.m5,R.drawable.m6}; privateSharedPreferences config; private int time=5; Handler han=new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); if(time>0){ time--; han.sendEmptyMessageDelayed(0, 1000); }else if(time==0){ SharedPreferences.Editor edit = config.edit(); edit.putBoolean("flag",true); edit.commit(); Intent intent=new Intent(MainActivity.this, MainActivity2.class); startActivity(intent); finish(); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); viewpager = (ViewPager) findViewById(R.id.viewpager); button = (Button) findViewById(R.id.button); config = getSharedPreferences("config", MODE_PRIVATE); boolean boolean1 = config.getBoolean("flag", false); if(boolean1){ //跳轉程式 Intent intent=new Intent(MainActivity.this, MainActivity2.class); startActivity(intent); finish(); } //設定資料介面卡 viewpager.setAdapter(new MyPagerAdapter(this, pics)); viewpager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { if(position==pics.length-1){ button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { daojishi(); } }); } } @Override public void onPageScrollStateChanged(int state) { } }); } private void daojishi() { new Thread(){ public void run() { }; }.start(); han.sendEmptyMessageDelayed(0, 1000); } }
//這是跳轉過來的activity 裡面有json解析的方法
public class MainActivity2 extends AppCompatActivity { private ListView listview; private List<bbb> listb=new ArrayList<>(); private List<Gsonjiexi.DataBean> lists=new ArrayList<>(); private MAdapter mAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); listview = (ListView) findViewById(R.id.listview); mAdapter = new MAdapter(); initData(); } private void initData() { new MAsyncTaskString().execute("http://api.expoon.com/AppNews/getNewsList/type/1/p/1"); } class MAdapter extends BaseAdapter{ @Override public int getCount() { return lists.size(); } @Override public Object getItem(int i) { return lists.get(i); } @Override public long getItemId(int i) { return i; } @Override public View getView(int i, View containerView, ViewGroup viewGroup) { View view = View.inflate(MainActivity2.this, R.layout.layout, null); ImageView iv = (ImageView) view.findViewById(R.id.imageview); TextView name = (TextView) view.findViewById(R.id.name); TextView title = (TextView) view.findViewById(R.id.title); //把圖片url傳遞給asyncTask new MAsyncTaskImage(iv).execute(lists.get(i).getPic_url()); name.setText(lists.get(i).getNews_summary()); title.setText(lists.get(i).getNews_title()); return view; } } class MAsyncTaskImage extends AsyncTask<String, Void, Bitmap> { ImageView iv; public MAsyncTaskImage(ImageView imageView) { this.iv = imageView; } //這個是請求網路之前的呼叫的方法,也是最先呼叫的方法,可以初始化一些ui等;這個方法是在主執行緒裡執行的 @Override protected void onPreExecute() { super.onPreExecute(); } /** * String... strings--->這個是可變引數; * 這個方法是在後臺執行的,不能更新ui,是子執行緒 * 這個方法的返回值會返回給 */ @Override protected Bitmap doInBackground(String... strings) { return new NetWorkUtils().getNetImage(strings[0]); } /** * 這個方法是執行在主執行緒的 * 當doInBackground執行完, 會自動回撥這個方法,來更新ui; * @param bitmap */ @Override protected void onPostExecute(Bitmap bitmap) { super.onPostExecute(bitmap); iv.setImageBitmap(bitmap); } //主執行緒可以更新ui; @Override protected void onProgressUpdate(Void... values) { super.onProgressUpdate(values); } } //寫json返回字串 class MAsyncTaskString extends AsyncTask<String, Void, String> { //這個是請求網路之前的呼叫的方法,也是最先呼叫的方法,可以初始化一些ui等;這個方法是在主執行緒裡執行的 @Override protected void onPreExecute() { super.onPreExecute(); } /** * String... strings--->這個是可變引數; * 這個方法是在後臺執行的,不能更新ui,是子執行緒 * 這個方法的返回值會返回給 */ /** * 呼叫urlconnectiong獲取json字串 * @param strings * @return */ @Override protected String doInBackground(String... strings) { return new NetWorkUtils().getNetString(strings[0]); } /** * 這個方法是執行在主執行緒的 * 當doInBackground執行完, 會自動回撥這個方法,來更新ui; */ @Override protected void onPostExecute(String netString) { super.onPostExecute(netString); Gson gson = new Gson(); Gsonjiexi student = gson.fromJson(netString, Gsonjiexi.class); lists = student.getData(); listview.setAdapter(mAdapter); } //主執行緒可以更新ui; @Override protected void onProgressUpdate(Void... values) { super.onProgressUpdate(values); } } }
//json解析 寫個類然後把json包弄進來然後按 alt+s 要沒那個架包就ctrl+alt+s下面有
//個Plugins之後在搜尋裡搜個GsonFormat就OK了
//viewpager 介面卡
public class MyPagerAdapter extends PagerAdapter { private Context context; private int[] pics; public MyPagerAdapter(Context context, int[] pics) { this.context = context; this.pics = pics; } @Override public int getCount() { return pics.length; } @Override public boolean isViewFromObject(View view, Object object) { return view==object; } @Override public void destroyItem(ViewGroup container, int position, Object object) { // super.destroyItem(container, position, object); container.removeView((View) object); } @Override public Object instantiateItem(ViewGroup container, int position) { ImageView imageView=new ImageView(context); imageView.setBackgroundResource(pics[position]); container.addView(imageView); return imageView; } }
//獲取網路資源的類
public class NetWorkUtils { private int responseCode; /** * 獲取圖片並返回; * @param urlString * @return */ public Bitmap getNetImage(String urlString){ try { //得到URL物件,這個物件可以開啟連線 URL url = new URL(urlString); //開啟連線,HttpURLConnection:是URLConnection的子類;子類的方法比較多;都用子類 HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection(); //伺服器返回的狀態碼 int responseCode = urlConnection.getResponseCode(); //請求成功 if (responseCode == 200){ InputStream inputStream = urlConnection.getInputStream(); //BitmapFactory類封裝了好多關於圖片處理的方法; Bitmap bitmap = BitmapFactory.decodeStream(inputStream); return bitmap; }else { Log.e("wzq請求圖片","responseCode:"+ responseCode); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } /** * 請求json字串, * @param urlString url * @return json字串 */ public String getNetString(String urlString){ try { //得到URL物件,這個物件可以開啟連線 URL url = new URL(urlString); //開啟連線,HttpURLConnection:是URLConnection的子類;子類的方法比較多;都用子類 HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection(); //伺服器返回的狀態碼 int responseCode = urlConnection.getResponseCode(); //請求成功 if (responseCode == 200){ InputStream inputStream = urlConnection.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder stringBuilder = new StringBuilder(); String stringTemp = ""; while ((stringTemp = bufferedReader.readLine()) != null) { stringBuilder.append(stringTemp); } String result = stringBuilder.toString(); Log.e("wzq請求json", "result:" + result); return result; }else { Log.e("wzq","responseCode:"+ responseCode); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } }