1. 程式人生 > >Http網路請求資料解析json展示資料+網路圖片展示+資料庫+Viewpager+Fragment

Http網路請求資料解析json展示資料+網路圖片展示+資料庫+Viewpager+Fragment

1.MainActivity主頁面

package com.bwie.guoxinyu;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.RadioGroup;

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

public class MainActivity extends FragmentActivity {

    private ViewPager viewPager;
    private RadioGroup group;
    private List<Fragment> list;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //獲取資源id
        viewPager = findViewById(R.id.viewpage);
        group = findViewById(R.id.group);
        //例項化新增fragment
        list = new ArrayList<>();
        list.add(new Fragmentone());
        list.add(new Fragmenttwo());
        list.add(new FragmentThree());
        //建立介面卡
        viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int i) {
                return list.get(i);
            }

            @Override
            public int getCount() {
                return list.size();
            }
        });
        //滑動切換
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                switch (i){
                    case 0:
                        group.check(R.id.btn1);
                        break;
                    case 1:
                        group.check(R.id.btn2);
                        break;
                    case 2:
                        group.check(R.id.btn3);
                        break;

                }
            }
            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
        //點選切換
        group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId){
                    case R.id.btn1:
                        viewPager.setCurrentItem(0);
                        break;
                    case R.id.btn2:
                        viewPager.setCurrentItem(1);
                        break;
                    case R.id.btn3:
                        viewPager.setCurrentItem(2);
                        break;
                }
            }
        });
    }
}

2.Bean類

package com.bwie.guoxinyu;

import java.util.List;

public class NewBean {
    private List<DataBean> data;

    public List<DataBean> getData() {
        return data;
    }

    public void setData(List<DataBean> data) {
        this.data = data;
    }

    public static class DataBean {
  
        private String news_id;
        private String news_title;
        private String news_summary;
        private String pic_url;

        public DataBean(String news_title, String news_summary, String pic_url) {
            this.news_title = news_title;
            this.news_summary = news_summary;
            this.pic_url = pic_url;
        }

        public String getNews_id() {
            return news_id;
        }

        public void setNews_id(String news_id) {
            this.news_id = news_id;
        }

        public String getNews_title() {
            return news_title;
        }

        public void setNews_title(String news_title) {
            this.news_title = news_title;
        }

        public String getNews_summary() {
            return news_summary;
        }

        public void setNews_summary(String news_summary) {
            this.news_summary = news_summary;
        }

        public String getPic_url() {
            return pic_url;
        }

        public void setPic_url(String pic_url) {
            this.pic_url = pic_url;
        }
    }
}

3.介面卡頁面

package com.bwie.guoxinyu;

import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

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

public class NewAdaper extends BaseAdapter {
    private List<NewBean.DataBean> mData;
    private Context mContext;

    public NewAdaper(Context mContext) {
        this.mContext = mContext;
        //初始化
        mData = new ArrayList<>();
    }
    //傳遞值得方法  共外部傳值
    public void setmData(List<NewBean.DataBean> datas){
        this.mData = datas;
        notifyDataSetChanged();
    }
    //刪除的方法
    public void delData(int position){
        mData.remove(position);
        notifyDataSetChanged();
    }
    @Override
    public int getCount() {
        return mData.size();
    }

    @Override
    public NewBean.DataBean getItem(int position) {
        return mData.get(position);
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        //判斷是否為空
        if(convertView == null){
            //載入子佈局
            convertView = LayoutInflater.from(mContext).inflate(R.layout.newitem,parent,false);
            holder = new ViewHolder(convertView);
        }else{
            //複用
            holder = (ViewHolder) convertView.getTag();
        }
        //定義賦值的方法
        holder.bind(getItem(position));
        return convertView;
    }
    //暫存器
    class ViewHolder{
        TextView title;
        TextView summary;
        ImageView image;
        //獲取子佈局id的方法
        public ViewHolder(View convertView) {
            title = convertView.findViewById(R.id.title);
            summary = convertView.findViewById(R.id.summary);
            image = convertView.findViewById(R.id.image);
            convertView.setTag(this);
        }
        //賦值的方法
        public void bind(NewBean.DataBean item) {
            title.setText(item.getNews_title());
            summary.setText(item.getNews_summary());
            //NetUtil.loadImage(item.getPic_url(),image);
            //每次都繫結最新的url到image
            image.setTag(item.getPic_url());
            //當載入完成,判斷當前載入圖片的url是否和繫結的一樣
            NetUtil.loadImage(item.getPic_url(), new NetUtil.CallBack() {
                @Override
                public void loadImageSuccess(String urlImage, Bitmap bitmap) {
                    //判斷當前載入圖片的url是否和繫結的一樣
                    if(image.getTag().equals(urlImage)){
                        image.setImageBitmap(bitmap);
                    }
                }
            });
        }
    }
}

4.工具類頁面

package com.bwie.guoxinyu;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;

import com.google.gson.Gson;

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;

public class NetUtil {
    //網路請求資料的方法
    public static String setRquest(String urlStr){
        String json = "";
        try {
            //開啟url地址
            URL url = new URL(urlStr);
            //開啟連線
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            //設定請求方式
            urlConnection.setRequestMethod("GET");
            //設定超時
            urlConnection.setReadTimeout(5000);
            urlConnection.setConnectTimeout(5000);
            //設定請求碼
            int responseCode = urlConnection.getResponseCode();
            if(responseCode == 200){
                json = stream2String(urlConnection.getInputStream());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }
    //將位元組流轉換為字元流
    private static String stream2String(InputStream inputStream) throws IOException {
        InputStreamReader isr = new InputStreamReader(inputStream);
        BufferedReader br = new BufferedReader(isr);
        StringBuilder builder = new StringBuilder();
        for (String tmp = br.readLine();tmp!=null;tmp = br.readLine()){
            builder.append(tmp);
        }
        return builder.toString();
    }
    //解析json的方法 返回bean
    public static <E> E setRquest(String urlStr,Class clazz){
        String rquest = setRquest(urlStr);
        E e = (E) new Gson().fromJson(rquest, clazz);
        return e;
    }
    //載入圖片的方法
    public static Bitmap loadImage(String urlImage){
        Bitmap bitmap =null;
        try {
            //開啟url地址
            URL url = new URL(urlImage);
            //開啟連線
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            //設定請求方式
            urlConnection.setRequestMethod("GET");
            //設定超時
            urlConnection.setReadTimeout(5000);
            urlConnection.setConnectTimeout(5000);
            //設定請求碼
            int responseCode = urlConnection.getResponseCode();
            if(responseCode == 200){
                //將讀取出來的內容存入bitmap
               bitmap = BitmapFactory.decodeStream(urlConnection.getInputStream());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }
    //定義介面
    public interface CallBack{
        public void loadImageSuccess(String urlImage,Bitmap bitmap);
    }
    //獲取圖片的方法
    public static void loadImage(final String urlImage, final CallBack callBack){
        new AsyncTask<String,Void,Bitmap>(){
            @Override
            protected Bitmap doInBackground(String... strings) {
                return NetUtil.loadImage(strings[0]);
            }

            @Override
            protected void onPostExecute(Bitmap bitmap) {
                callBack.loadImageSuccess(urlImage,bitmap);
            }
        }.execute(urlImage);
    }
}

5.資料庫建立表頁面

package com.bwie.guoxinyu;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class SqliteHelper extends SQLiteOpenHelper {
    public SqliteHelper( Context context) {
        super(context, "New.db", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        //建立表
        db.execSQL("create table news(id integer primary key autoincrement," +
                "news_title text," +
                "news_summary text," +
                "pic_url text)");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}

6.資料庫方法頁面增刪改查

package com.bwie.guoxinyu;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

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

public class NewDao {

    private final SqliteHelper helper;
    private final SQLiteDatabase sb;

    public NewDao(Context context){
        //建立資料庫
        helper = new SqliteHelper(context);
        sb = helper.getReadableDatabase();
    }
    //新增
    public void add(String news_title,String news_summary,String pic_url){
        ContentValues values = new ContentValues();
        values.put("news_title",news_title);
        values.put("news_summary",news_summary);
        values.put("pic_url",pic_url);
        sb.insert("news",null,values);
    }
    //查詢
    public List<NewBean.DataBean> select(){
        Cursor news = sb.query("news", null, null, null, null, null, null);
        List<NewBean.DataBean> list = new ArrayList<>();
        while (news.moveToNext()){
            String news_title = news.getString(news.getColumnIndex("news_title"));
            String news_summary = news.getString(news.getColumnIndex("news_summary"));
            String pic_url = news.getString(news.getColumnIndex("pic_url"));
            NewBean.DataBean bean = new NewBean.DataBean(news_title,news_summary,pic_url);
            list.add(bean);
        }
        return list;
    }
    //刪除
    public void delete(String news_title){
        sb.delete("news","news_title = ?",new String[]{news_title});
    }
}

7.Fragment內容頁面

package com.bwie.guoxinyu;

import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
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.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;

public class Fragmentone extends Fragment {

    private ListView listView;
    private NewAdaper mAdaper;
    private NewDao dao;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //載入佈局
        View view = inflater.inflate(R.layout.fragmentone, container, false);
        //獲取資源id
        listView = view.findViewById(R.id.lv_list);
        //建立介面卡
        mAdaper = new NewAdaper(getActivity());
        listView.setAdapter(mAdaper);
        dao = new NewDao(getActivity());
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //長按刪除
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                dao.delete(mAdaper.getItem(position).getNews_title());
                mAdaper.delData(position);
                return true;
            }
        });
        infoDta();
    }

    private String urlStr = "http://api.expoon.com/AppNews/getNewsList/type/1/p/1";

    @SuppressLint("StaticFieldLeak")
    private void infoDta() {
        new AsyncTask<String, Void, List<NewBean.DataBean>>() {
            @Override
            protected List<NewBean.DataBean> doInBackground(String... strings) {
                List<NewBean.DataBean> data = new ArrayList<>();
                //迴圈陣列 將資料新增到集合中
                for (String url : strings) {
                    NewBean bean = NetUtil.setRquest(url, NewBean.class);
                    data.addAll(bean.getData());
                }
                //判斷資料庫是否有資料,沒有資料向資料庫新增資料
                if (dao.select().size() == 0) {
                    for (NewBean.DataBean d : data) {
                        String news_title = d.getNews_title();
                        String news_summary = d.getNews_summary();
                        String pic_url = d.getPic_url();
                        //新增資料庫
                        dao.add(news_title, news_summary, pic_url);
                    }
                }
                //查詢資料庫
                List<NewBean.DataBean> select = dao.select();
                return select;
            }

            @Override
            protected void onPostExecute(List<NewBean.DataBean> dataBeans) {
                mAdaper.setmData(dataBeans);
            }
        }.execute(urlStr);
    }
}