1. 程式人生 > >網路請求 + 使用子執行緒更新資料 + Asynctask實現非同步執行 + Gson解析

網路請求 + 使用子執行緒更新資料 + Asynctask實現非同步執行 + Gson解析

//主頁面MainActivity
public class MainActivity extends FragmentActivity {

private ViewPager pager;
private RadioGroup radioGroup;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    findViewById( R.id.radioButton).setBackgroundColor(Color.RED);
    findViewById( R.id.radioButton2).setBackgroundColor(Color.GREEN);
    pager = findViewById(R.id.pager);
    radioGroup = findViewById(R.id.radiogroup);
    //預設選中第一個
    radioGroup.check(radioGroup.getChildAt(0).getId());
    //設定頁面滑動資料

    ArrayList<Fragment> list=new ArrayList<Fragment>();
    FragListview fragListview=new FragListview();
    FragGridView fragGridView=new FragGridView();
    list.add(fragListview);
    list.add(fragGridView);
    ///設定介面卡
    pager.setAdapter(new MyFragmentAdapter(getSupportFragmentManager(),list));
    //按鈕跟著頁面走
    pager. addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int i, float v, int i1) {

        }

        @Override
        public void onPageSelected(int i) {
            //當頁面發生改變 按鈕也要跟著變
            radioGroup.check(radioGroup.getChildAt(i).getId());
        }

        @Override
        public void onPageScrollStateChanged(int i) {

        }
    });
    //頁面跟著按鈕改變
    radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            //根據點選按鈕改變頁面
            switch (checkedId){
                case  R.id.radioButton:
                    findViewById( R.id.radioButton).setBackgroundColor(Color.RED);
                    findViewById( R.id.radioButton2).setBackgroundColor(Color.GREEN);
                    pager.setCurrentItem(0);
                    break;
                case  R.id.radioButton2:
                    findViewById( R.id.radioButton).setBackgroundColor(Color.GREEN);
                    findViewById( R.id.radioButton2).setBackgroundColor(Color.RED);
                    pager.setCurrentItem(1);
                    break;
            }
        }
    });

}

}
//2.FragListView 使用Gson解析
public class FragListview extends Fragment {

private ListView listView;

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fraglistview, container, false);
    listView = view.findViewById(R.id.listview);
    //解析網路資料
    new Thread() {
        @Override
        public void run() {
            super.run();
            //請求資料
            String s = HttpUtile.requestHttpGet("https://api.apiopen.top/musicRankings");
            //解析
            Gson gson = new Gson();
            JsonListBean listBean = gson.fromJson(s, JsonListBean.class);
            List<JsonListBean.ResultBean> list = listBean.getResult();
            //子執行緒處理資料完畢
            //更新ui
            Message message = new Message();
            message.what = 0;
            message.obj = list;
            handler.sendMessage(message);
        }
    }.start();


    return view;
}

Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        switch (msg.what) {
            case 0:
                List<JsonListBean.ResultBean> list = (List<JsonListBean.ResultBean>) msg.obj;
                //展示到listview上
                listView.setAdapter(new MyAdapter(list,getActivity()));
                break;

        }
    }
};

}

//3.FragGridView網路格式
public class FragGridView extends Fragment implements MyAsyncTask.Callbacks {

private GridView grid;

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    View view=inflater.inflate(R.layout.fraggradview,container,false);
    grid = view.findViewById(R.id.grid);
    //請求資料
    MyAsyncTask task=new MyAsyncTask();
    task.setCallbacks(this);
    task.execute("https://api.apiopen.top/musicRankings");
    return view;
}

@Override
public String getData(String string) {
    //解析
    Gson gson = new Gson();
    JsonListBean listBean = gson.fromJson(string, JsonListBean.class);
    List<JsonListBean.ResultBean> list = listBean.getResult();
    grid.setAdapter(new MyAdapter(list,getActivity()));
    Toast.makeText(getActivity(),string,Toast.LENGTH_LONG).show();
    return null;
}

}

//4.HttpUtile
public class HttpUtile {
/**
* 請求資料GET請求
*/
public static String requestHttpGet(String strUrl) {

    try { //設定url
        URL url = new URL(strUrl);

        //獲取HttpURLConnection
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        //設定為get請求
        connection.setRequestMethod("GET");
        //設定連線主機超時時間
        connection.setConnectTimeout(5000);
        //設定從主機讀取資料超時
        connection.setReadTimeout(5000);
        //獲取請求碼(來判斷網路請求是否正確)
        int code = connection.getResponseCode();

        //判斷請求是否成功
        if (code == HttpURLConnection.HTTP_OK) {
            //如果資料請求成功
            //就獲取資料
            InputStream stream = connection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "utf-8"));
            //拼接字串
            StringBuilder builder = new StringBuilder();
            //把資料讀取從成字串
            String str = "";
            while ((str = reader.readLine()) != null) {
                //把一行行資料拼接成一行資料
                builder.append(str);
            }
            //返回拼接後的資料
            return builder.toString();

        }
        //關閉連線
        connection.disconnect();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

public static Bitmap httpGETImage(String string) {
    try {
        //設定URL
        URL url = new URL(string);
        //得到HttpURLConnection
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        //連線超時時間
        connection.setConnectTimeout(5000);
        //讀取超時
        connection.setReadTimeout(5000);
        //獲取請求碼 一般情況下200是成功
        int code = connection.getResponseCode();
        //判斷請求碼是否 請求成功
        if (code == HttpURLConnection.HTTP_OK) {
            //得到資料
            InputStream stream = connection.getInputStream();
            // 如果是圖片
            Bitmap bitmap = BitmapFactory.decodeStream(stream);

            return bitmap;
        }
        connection.disconnect();

    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}



  //post請求
    public static String httpPost(String str1, String str2) {
//        http://apis.juhe.cn/cook/query   ?    key=&menu=蛋炒飯
        try {
            //設定url
            URL url = new URL(str1);
            //獲取HttpURLConnection
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            //設定為post請求
            connection.setRequestMethod("POST");
            //使用寫入和讀取(post請求必須要寫這個倆)
            connection.setDoOutput(true);
            connection.setDoInput(true);
            //
            PrintWriter writer = new PrintWriter(connection.getOutputStream());
            writer.write(str2);// key=  &menu=蛋炒飯
            writer.flush();
            ;//重新整理
            //判斷是否成功
            int code = connection.getResponseCode();
            if (code == 200) {
                //讀取資料
                InputStream stream = connection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "utf-8"));
                //拼接字串
                StringBuilder builder = new StringBuilder();
                String s = "";
                //讀取資料
                while ((s = reader.readLine()) != null) {
                    //拼接字串
                    builder.append(s);
                }
                return builder.toString();
            }
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

//5.MyAsyncTask
public class MyAsyncTask extends AsyncTask<String ,Void,String> {
@Override
protected String doInBackground(String… strings) {
return HttpUtile.requestHttpGet(strings[0]);
}

@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);
    callbacks.getData(s);

}
public  interface  Callbacks{
      String getData(String string);
}
private  Callbacks callbacks;

public void setCallbacks(Callbacks callbacks) {
    this.callbacks = callbacks;
}

}

//6.MyFragmentAdapter
public class MyFragmentAdapter extends FragmentPagerAdapter {
private ArrayList< Fragment> list;

public MyFragmentAdapter(FragmentManager fm, ArrayList<Fragment> list) {
    super(fm);
    this.list = list;
}

@Override
public Fragment getItem(int i) {
    return list.get(i);
}

@Override
public int getCount() {
    return list.size();
}

}

7.MyAdapter
public class MyAdapter extends BaseAdapter {
private List<JsonListBean.ResultBean> list;
private Context context;

public MyAdapter(List<JsonListBean.ResultBean> list, Context context) {
    this.list = list;
    this.context = context;
}

@Override
public int getCount() {
    return list.size();
}

@Override
public Object getItem(int position) {
    return null;
}

@Override
public long getItemId(int position) {
    return 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder = null;
    if (convertView == null) {
        convertView = View.inflate(context, R.layout.item, null);
        holder = new ViewHolder();
        holder.text =  convertView.findViewById(R.id.text);
        holder.image =  convertView.findViewById(R.id.image);
        convertView.setTag(holder);
    }
    else {
        holder= (ViewHolder) convertView.getTag();
    }
    JsonListBean.ResultBean resultBean  = list.get(position);
    holder.text.setText(resultBean.getName());

// holder.image.setImageBitmap( );
ImageLoader.getInstance().displayImage( resultBean.getPic_s444(), holder.image);
return convertView;
}

class ViewHolder {
    TextView text;
    ImageView image;
}

}

****8.App****

public class App extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        //配置屬性
        DisplayImageOptions options = new DisplayImageOptions.Builder() .build();
        //設定imageloader
        ImageLoaderConfiguration loader = new ImageLoaderConfiguration.Builder(this)
                .defaultDisplayImageOptions(options)//設定配置屬性
                .build();

        //        獲得例項
        ImageLoader imageLoader = ImageLoader.getInstance();
//        初始化
        imageLoader.init(loader);
    }
}