1. 程式人生 > >網路請求資料 banner圖片輪播和list請求資料

網路請求資料 banner圖片輪播和list請求資料

import android.graphics.Bitmap;
import com.ljn.myapplication.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

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 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 DisplayImageOptions getDisplayImageOption() { DisplayImageOptions options = new DisplayImageOptions.Builder() .showImageOnLoading(R.mipmap.ic_launcher) //設定圖片在下載期間顯示的圖片 .showImageForEmptyUri(R.mipmap.ic_launcher)//設定圖片Uri為空或是錯誤的時候顯示的圖片 .showImageOnFail(R.mipmap.ic_launcher) //設定圖片載入/解碼過程中錯誤時候顯示的圖片 .cacheInMemory(true)//設定下載的圖片是否快取在記憶體中 .cacheOnDisk(true) .considerExifParams(true) //是否考慮JPEG影象EXIF引數(旋轉,翻轉) .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)//設定圖片以如何的編碼方式顯示 .bitmapConfig(Bitmap.Config.RGB_565)//設定圖片的解碼型別// .displayer(new RoundedBitmapDisplayer(30))//是否設定為圓角,弧度為多少 // .displayer(new FadeInBitmapDisplayer(100))//是否圖片載入好後漸入的動畫時間 //.displayer(new CircleBitmapDisplayer())//顯示圓形圖片 .build(); //構建完成 return options; } }
import android.app.Application;
import android.os.Environment;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;

import java.io.File;

public class MApp extends Application {
     //繼承Application
File cacheFile= new File(Environment.getExternalStorageDirectory()+"/"+"imgages");

         @Override
public void onCreate() {
             super.onCreate();
             //初始化元件,鏈式開發思想,整個框架的引數初始化配置
ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(this)
                     .memoryCacheExtraOptions(480, 800) // default = device screen dimensions 記憶體快取檔案的最大長寬
.diskCacheExtraOptions(480, 800, null)  // 本地快取的詳細資訊(快取的最大長寬),最好不要設定這個
.tasksProcessingOrder(QueueProcessingType.FIFO) // default
.denyCacheImageMultipleSizesInMemory()
                     .memoryCache(new LruMemoryCache(2 * 1024 * 1024)) //可以通過自己的記憶體快取實現
.memoryCacheSize(2 * 1024 * 1024)  // 記憶體快取的最大值
.memoryCacheSizePercentage(13) // default
.diskCacheSize(50 * 1024 * 1024) // 50 Mb sd卡(本地)快取的最大值
.diskCacheFileCount(100)  // 可以快取的檔案數量
.diskCache(new UnlimitedDiskCache(cacheFile))//自定義快取目錄
                      // .threadPoolSize(3)//設定執行緒數
                     // default為使用HASHCODE對UIL進行加密命名, 還可以用MD5(new Md5FileNameGenerator())加密
.diskCacheFileNameGenerator(new HashCodeFileNameGenerator())
                     .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default
.writeDebugLogs() // 列印debug log
.build();

             ImageLoader.getInstance().init(configuration);

         }
}

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.ljn.myapplication.bean.NetBean;
import com.ljn.myapplication.bean.NewsBean;
import com.ljn.myapplication.bean.TextBean;
import com.ljn.myapplication.utils.Utils;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.youth.banner.Banner;

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

public class MainActivity extends AppCompatActivity {
    private String NetString="http://api.expoon.com/AppNews/getNewsList/type/1/p/1";
    private String ImageNetString="http://www.93.gov.cn/93app/data.do?channelId=0&startNum=0";
    List<NewsBean.DataBean> list=new ArrayList<NewsBean.DataBean>();
    private ListView lv;
    private MAdapter mAdapter;
    private ImageLoader instance;
    private Banner banner;
    private Handler handler=new Handler(){
        @Override
public void handleMessage(Message msg) {
            int what = msg.what;
             switch (what){
                         case 1:
                             List<TextBean.DataBean> data = (List<TextBean.DataBean>) msg.obj;
                             Log.e("TAG", data.toString() );
                             List<String> images=new ArrayList<String>();
                             List<String> titles=new ArrayList<String>();
                             for (int i=0;i<data.size();i++){
                                 images.add(data.get(i).getPic_url());
                                 titles.add(data.get(i).getNews_title());
                             }
                             banner.setImageLoader(new BImageLoader());
                             banner.setImages(images);
                             banner.setBannerTitles(titles);
                             banner.start();
                             break;

                     }
        }
    };
    @Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        instance = ImageLoader.getInstance();
        getNetData();
        initDsta();
        lv = findViewById(R.id.lv);
        banner = (Banner) findViewById(R.id.banner);
        mAdapter = new MAdapter();
        lv.setAdapter(mAdapter);
    }

    private void initDsta() {
        new Thread() {
            @Override
public void run() {
                String str = Utils.getNetString(NetString);
                Log.e("TAG", str.toString() );
                Gson gson=new Gson();
                TextBean json = gson.fromJson(str, TextBean.class);
                List<TextBean.DataBean> data = json.getData();
                Message msg=new Message();
                msg.obj=data;
                msg.what=1;
                handler.sendMessage(msg);
            }
        }.start();
    }

    public void getNetData() {
       new MAsyncTask().execute(ImageNetString);
    }
    class BImageLoader extends com.youth.banner.loader.ImageLoader{
        @Override
public void displayImage(Context context, Object obj, ImageView imageView) {

            com.nostra13.universalimageloader.core.ImageLoader imageLoaderInstance = com.nostra13.universalimageloader.core.ImageLoader.getInstance();
            imageLoaderInstance.displayImage((String) obj, imageView);

        }
    }
    private class MAsyncTask extends AsyncTask<String,Void,String> {
        @Override
protected String doInBackground(String... strings) {
            return Utils.getNetString(strings[0]);
        }

        @Override
protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Gson gson=new Gson();
            NewsBean json = gson.fromJson(s, NewsBean.class);
            List<NewsBean.DataBean> data = json.getData();
            list.addAll(data);
            mAdapter.notifyDataSetChanged();
        }
    }

    private class MAdapter extends BaseAdapter {

        private TextView TITLE;
        private TextView SUBTITLE;
        private ImageView IMAGEURL;
        private TextView FROMNAME;
        private ViewHolder vh;
        private VHolder vholder;

        @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 int getItemViewType(int position) {
            //根據圖片是否為空進行判斷
int flag=0;
            if (list.get(position).getIMAGEURL()==null&&list.get(position).getIMAGEURL()==""){
                flag=0;
            }else if (list.get(position).getIMAGEURL()!=null&&list.get(position).getIMAGEURL()!=""){
                flag=1;
            }
            return flag;
        }

        @Override
public int getViewTypeCount() {
            //getview裡有幾個佈局就寫幾
return 2;
        }


        @Override
public View getView(int i, View view, ViewGroup viewGroup) {
            int type = getItemViewType(i);
             switch (type){
                         case 0:
                             if (view==null){
                                 vholder = new VHolder();
                                 view = View.inflate(MainActivity.this, R.layout.item, null);
                                 view.setTag(vholder);
                             }else{
                                 vholder = (VHolder) view.getTag();
                             }
                             vholder.TITLE = view.findViewById(R.id.item_TITLE);
                             vholder.SUBTITLE = view.findViewById(R.id.item_SUBTITLE);
                             vholder.FROMNAME = view.findViewById(R.id.item_FROMNAME);
                             vholder.TITLE.setText(list.get(i).getTITLE());
                             vholder.SUBTITLE.setText(list.get(i).getSUBTITLE());
                             vholder.FROMNAME.setText(list.get(i).getFROMNAME());
                             break;
                         case 1:
                             if (view==null){
                                 vh = new ViewHolder();
                                 view = View.inflate(MainActivity.this, R.layout.item, null);
                                 view.setTag(vh);
                             }else{
                                 vh = (ViewHolder) view.getTag();
                             }
                             vh.TITLE = view.findViewById(R.id.item_TITLE);
                             vh.SUBTITLE = view.findViewById(R.id.item_SUBTITLE);
                             vh.IMAGEURL = view.findViewById(R.id.item_IMAGEURL);
                             vh.FROMNAME = view.findViewById(R.id.item_FROMNAME);
                             vh.TITLE.setText(list.get(i).getTITLE());
                             vh.SUBTITLE.setText(list.get(i).getSUBTITLE());
                             vh.FROMNAME.setText(list.get(i).getFROMNAME());
                             instance.displayImage(list.get(i).getIMAGEURL(),vh.IMAGEURL,Utils.getDisplayImageOption());
                             break;
                     }
            return view;
        }
    }
    class ViewHolder{
         TextView TITLE;
         TextView SUBTITLE;
         ImageView IMAGEURL;
         TextView FROMNAME;
    } class VHolder{
         TextView TITLE;
         TextView SUBTITLE;
         TextView FROMNAME;
    }
}

//網路狀態
<uses-permission android:name="android.permission.INTERNET" />
//sd讀寫許可權
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
application裡配置
android:name=".MApp"
//配置依賴
compile 'com.google.code.gson:gson:2.2.4'//Gson
compile 'com.youth.banner:banner:1.4.9' //圖片輪播
compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'//圖片框架