网络请求与Fragment的使用

ackage com.ljn.myapplication.Utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * Created by HP on 2017/11/4.
 */

public class Utils {
    public static String getNetString(String str){
        try {
            URL url=new URL(str);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            int responseCode = urlConnection.getResponseCode();
            if (responseCode==200){
                InputStream is = urlConnection.getInputStream();
                BufferedReader br=new BufferedReader(new InputStreamReader(is));
                StringBuilder sb=new StringBuilder();
                String line=null;
                while ((line=br.readLine())!=null){
                    sb.append(line);
                }
                return sb.toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static Bitmap getNetBitmap(String str){
        try {
            URL url=new URL(str);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            int responseCode = urlConnection.getResponseCode();
            if (responseCode==200){
                InputStream is = urlConnection.getInputStream();
                Bitmap bitmap = BitmapFactory.decodeStream(is);
                return bitmap;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getJsonByHttpClientGet(String jsonUrl) {
        //获取httpclient对象
        DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
        //准备一个get请求
//        HttpGet httpGet = new HttpGet(jsonUrl);
        HttpPost httpPost = new HttpPost(jsonUrl);
        try {
            //得到服务器返回的数据;
            HttpResponse response = defaultHttpClient.execute(httpPost);
            //得到状态码
            int statusCode = response.getStatusLine().getStatusCode();
            if(statusCode ==200){
                //entiry 里面封装的数据;
                HttpEntity entity = response.getEntity();
                //这个result就是json字符串,剩下的就是解析工作了;
                //String result = EntityUtils.toString(entity);
                return EntityUtils.toString(entity);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 返回值 -1:没有网络  1:WIFI网络   2:net网络
     //工具类 判断网络
     */
    public static int getNetype(Context context) {
        int netType = -1;
        ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo == null) {
            return netType;
        }
        int nType = networkInfo.getType();
        if (nType == ConnectivityManager.TYPE_MOBILE) {
            netType = 2;
        } else if (nType == ConnectivityManager.TYPE_WIFI) {
            netType = 1;
        }
        return netType;
    }

}

package com.ljn.myapplication;

import android.support.annotation.IdRes;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.ljn.myapplication.Fragment.MainFragment1;
import com.ljn.myapplication.Fragment.MainFragment2;
import com.ljn.myapplication.Fragment.MainFragment3;
import com.ljn.myapplication.Fragment.MainFragment4;
import com.ljn.myapplication.Utils.Utils;

import java.net.JarURLConnection;
import java.util.ArrayList;
import java.util.List;

import static android.R.id.list;

public class MainActivity extends FragmentActivity {
//private List list=new ArrayList();
    private RadioGroup rg;
    private FragmentManager manager;
    private MainFragment1 fragment1;
    private MainFragment2 fragment2;
    private MainFragment3 fragment3;
    private MainFragment4 fragment4;

    @Override
    protected void onResume() {
        super.onResume();
        int netype = Utils.getNetype(MainActivity.this);
        if (netype == -1) {
            Toast.makeText(this, "当前网络异常,请做联网操作!", Toast.LENGTH_SHORT).show();
        } else if (netype == 1) {
            Toast.makeText(this, "当前网络正常,正在使用WiFi网络", Toast.LENGTH_SHORT).show();
        } else if (netype == 0) {
            Toast.makeText(this, "当前网络正常,正在使用运营商网络(3G/4G),请注意流量的使用", Toast.LENGTH_SHORT).show();
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        rg = findViewById(R.id.main_rg);
        //initData();
        manager = getSupportFragmentManager();
        fragment1 = new MainFragment1();
        manager.beginTransaction().add(R.id.main_fl,fragment1).commit();
        rg.setOnCheckedChangeListener(new Myoccl());
    }

    /*private void initData() {
        list.add(new MainFragment1());
        list.add(new MainFragment2());
        list.add(new MainFragment3());
        list.add(new MainFragment4());
    }*/

    private class Myoccl implements RadioGroup.OnCheckedChangeListener {

        @Override
        public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) {
            hideFragments();
            switch (i){
                case R.id.main_rb1:
                   // manager.beginTransaction().replace(R.id.main_fl,list.get(0)).commit();
                    manager.beginTransaction().show(fragment1).commit();
                    break;
                case R.id.main_rb2:
                   // manager.beginTransaction().replace(R.id.main_fl,list.get(1)).commit();
                    if (fragment2==null){
                        fragment2 = new MainFragment2();
                        manager.beginTransaction().add(R.id.main_fl,fragment2).commit();
                    }else{
                        manager.beginTransaction().show(fragment2).commit();
                    }
                    break;
                case R.id.main_rb3:
                  //  manager.beginTransaction().replace(R.id.main_fl,list.get(2)).commit();
                    if (fragment3==null){
                        fragment3 = new MainFragment3();
                        manager.beginTransaction().add(R.id.main_fl,fragment3).commit();
                    }else{
                        manager.beginTransaction().show(fragment3).commit();
                    }
                    break;
                case R.id.main_rb4:
                   // manager.beginTransaction().replace(R.id.main_fl,list.get(3)).commit();
                    if (fragment4==null){
                        fragment4 = new MainFragment4();
                        manager.beginTransaction().add(R.id.main_fl,fragment4).commit();
                    }else{
                        manager.beginTransaction().show(fragment4).commit();
                    }
                    break;
            }
        }
    }
    private void hideFragments(){
    if (fragment1!=null&&fragment1.isAdded()){
        manager.beginTransaction().hide(fragment1).commit();
    }
    if (fragment2!=null&&fragment2.isAdded()){
        manager.beginTransaction().hide(fragment2).commit();
    }
    if (fragment3!=null&&fragment3.isAdded()){
        manager.beginTransaction().hide(fragment3).commit();
    }
    if (fragment4!=null&&fragment4.isAdded()){
        manager.beginTransaction().hide(fragment4).commit();
    }
        //manager.beginTransaction().commit();
    }
}

package com.ljn.myapplication.Fragment;

import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.ljn.myapplication.Bean.TextBean;
import com.ljn.myapplication.R;
import com.ljn.myapplication.Utils.Utils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by HP on 2017/11/4.
 */

public class MainFragment1 extends Fragment {

    private ListView lv;
    private String NetString="https://api.tianapi.com/wxnew/?key=8d6e3228d25298f13af4fc40ce6c9679&num=10";
    private List list=new ArrayList();
    private MyAdapter adapter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.mainfragment1, container, false);
        lv = view.findViewById(R.id.child1_lv);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        new MyAsyncTask().execute(NetString);
        adapter = new MyAdapter();
        lv.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }

    private class MyAsyncTask extends AsyncTask{
        @Override
        protected String doInBackground(String... strings) {
            return Utils.getNetString(strings[0]);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Gson gson=new Gson();
            TextBean json = gson.fromJson(s, TextBean.class);
            List newslist = json.getNewslist();
            list.addAll(newslist);
        }
    }

    private class MyAdapter extends BaseAdapter {

        private ViewHolder vh;
        private TextView ctime;
        private TextView title;
        private TextView description;
        private ImageView img;

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

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

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

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            if (view==null){
                vh = new MainFragment1.ViewHolder();
                view = View.inflate(getActivity(), R.layout.item, null);
                view.setTag(vh);
            }else{
                 vh = (ViewHolder) view.getTag();
            }
            vh.ctime = view.findViewById(R.id.item_ctime);
            vh.title = view.findViewById(R.id.item_title);
            vh.description = view.findViewById(R.id.item_description);
            vh.img = view.findViewById(R.id.item_img);
            vh.ctime.setText(list.get(i).getCtime());
            vh.title.setText(list.get(i).getTitle());
            vh.description.setText(list.get(i).getDescription());
            new MyBitmap(vh.img).execute(list.get(i).getPicUrl());
            return view;
        }

        private class MyBitmap extends AsyncTask{
            private ImageView img;

            public MyBitmap(ImageView img) {
                this.img=img;
            }

            @Override
            protected Bitmap doInBackground(String... strings) {
                return Utils.getNetBitmap(strings[0]);
            }

            @Override
            protected void onPostExecute(Bitmap bitmap) {
                super.onPostExecute(bitmap);
                img.setImageBitmap(bitmap);
            }
        }
    }
    class ViewHolder{
        TextView ctime;
        TextView title;
        TextView description;
        ImageView img;
    }
}


你可能感兴趣的:(网络请求与Fragment的使用)