1. 程式人生 > >判斷網路獲取+資料庫+頁面展示

判斷網路獲取+資料庫+頁面展示

Activity頁面切換


public class MainActivity extends AppCompatActivity {

    private ViewPager pager;
    private RadioGroup group;
    private ArrayList<Fragment> list;
    private Dao dao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        dao = new Dao(this);
        pager = (ViewPager) findViewById(R.id.pager);
        group = (RadioGroup) findViewById(R.id.group);
        group.check(group.getChildAt(0).getId());
        list = new ArrayList<Fragment>();
        list.add(new Fragment01());
        list.add(new Fragment02());
        list.add(new Fragment03());


        pager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {

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

            @Override
            public Fragment getItem(int i) {
                return list.get(i);
            }
        });
        pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {
                group.check(group.getChildAt(i).getId());
            }

            @Override
            public void onPageSelected(int i) {

            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
        group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId){
                    case R.id.radio0:
                        pager.setCurrentItem(0);
                        break;
                    case R.id.radio1:
                        pager.setCurrentItem(1);
                        break;
                    case R.id.radio2:
                        pager.setCurrentItem(2);
                        break;
                }
            }
        });
    }

    public Dao getDao(){
      return  dao;
    };
}

ImageLoader框架
image依賴 :compile ‘com.nostra13.universalimageloader:universal-image-loader:1.9.5’
繼承 Application
一定記得要匯入依賴,一定記得要匯入依賴,一定記得要匯入依賴

public class MApp extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        ImageLoaderConfiguration build = new ImageLoaderConfiguration.Builder(this).build();
        ImageLoader instance = ImageLoader.getInstance();
        instance.init(build);
    }
}

判斷網路是否連結 使用AsyncTask

public class Fragment01 extends Fragment {
    String urlString = "http://api.expoon.com/AppNews/getNewsList/type/1/p/1";
    private TextView text;
    private List<Bean.DataBean> list;
    private Dao dao;
    private ListView listvv;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment01, container, false);
        text = (TextView) view.findViewById(R.id.text);
        dao = ((MainActivity) getActivity()).getDao();
        if (NutilStateutil.iscoon(getActivity())) {
            listvv = (ListView)view.findViewById(R.id.listvv);

            new MyAnacs().execute(urlString);

        } else {
            text.setText("我沒有網");
            Toast.makeText(getActivity(), "我沒有網", Toast.LENGTH_LONG).show();
        }

        return view;
    }

    private class MyAnacs extends AsyncTask<String, Void, String> {

        private long insert;

        @Override
        protected String doInBackground(String... strings) {
            String jsonString = NutUtil.getJson(strings[0]);

            return jsonString;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Gson gson = new Gson();
            Bean fromJson = gson.fromJson(s, Bean.class);
            list = fromJson.getData();
            listvv.setAdapter(new BaseAdapter() {
                @Override
                public int getCount() {
                    return list.size();
                }

                @Override
                public Object getItem(int position) {
                    return list.get(position);
                }

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

                @Override
                public View getView(int position, View convertView, ViewGroup parent) {
                    ViewHolder holder = null;
                    if(convertView == null){
                        convertView = View.inflate(getActivity(),R.layout.item,null);
                        holder = new ViewHolder();
                        holder.ids = (TextView) convertView.findViewById(R.id.ids);
                        holder.title = (TextView) convertView.findViewById(R.id.title);
                        holder.url = (ImageView) convertView.findViewById(R.id.url);
                        convertView.setTag(holder);
                    }else{
                        holder =(ViewHolder)convertView.getTag();
                    }
                    holder.ids.setText(list.get(position).getNews_id());
                    holder.title.setText(list.get(position).toString().trim());
                    ImageLoader instance = ImageLoader.getInstance();
                    instance.displayImage(list.get(position).getPic_url(),holder.url);
                    return convertView;
                }
                class ViewHolder{
                    TextView ids;
                    TextView title;
                    ImageView url;
                }
            });
            Log.e("Yxx", "資料json__list" + list.size());
            for (int i = 0; i < list.size(); i++) {
                ContentValues values = new ContentValues();
                values.put("ids", list.get(i).getNews_id());
                values.put("title", list.get(i).getNews_summary());
                insert = dao.insert("student", null, values);
            }
            Log.e("Yxx", "資料json__" + insert);
        }
    }
}

判斷網路 在清單檔案一定要記得寫許可權


public class NutilStateutil {
    public static boolean iscoon(Context context) {
        boolean available = false;
        ConnectivityManager systemService = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = systemService.getActiveNetworkInfo();
        if (networkInfo != null) {
            available = networkInfo.isAvailable();
        }

        return available;
    }
}

網路讀取工具類

public class NutUtil {
    public static String getJson(String urlString) {

        URL url = null;
        try {
            url = new URL(urlString);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            int responseCode = httpURLConnection.getResponseCode();
            if(responseCode == 200){
                InputStream inputStream = httpURLConnection.getInputStream();
                InputStreamReader streamReader = new InputStreamReader(inputStream);
                BufferedReader reader = new BufferedReader(streamReader);

                StringBuffer buffer = new StringBuffer();
                String temp = "";
                if((temp = reader.readLine())!=null){
                    buffer.append(temp);
                }
                return buffer.toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }
}

listview優化

public class MyAdapter extends BaseAdapter {

    private Context context;
    private ArrayList<baaa> list1;
    //String urlBitmap="http://img.my.csdn.net/uploads/201407/26/1406383265_8550.jpg";

    public MyAdapter(Context context, ArrayList<baaa> list1) {
        this.context = context;
        this.list1 = list1;
    }

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

    @Override
    public Object getItem(int position) {
        return list1.get(position);
    }

    @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.ids = (TextView) convertView.findViewById(R.id.ids);
            holder.title = (TextView) convertView.findViewById(R.id.title);
            holder.url = convertView.findViewById(R.id.url);
            convertView.setTag(holder);
        }else{
            holder =(ViewHolder)convertView.getTag();
        }
        holder.ids.setText(list1.get(position).getId());
        holder.title.setText(list1.get(position).getTitle());
        ImageLoader instance = ImageLoader.getInstance();
        instance.displayImage(list1.get(position).getImage_url(),holder.url);
        return convertView;
    }

    class ViewHolder{
        TextView ids;
        TextView title;
        ImageView url;
    }
}

清單檔案

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.yxx.yxx1130_lianxi">

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <application
        android:name=".Nutil.MApp"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>