无网络状态下显示 缓存数据 <缓存到SD卡中>

来源:互联网 发布:js源码 编辑:程序博客网 时间:2024/06/06 06:19

这是与第三方库xListView 一起使用 实现下拉刷新,上拉加载的 功能

如果:不想使用 xListView的话可以话 可以把xListView 改成 ListView ##

public class MainActivity extends AppCompatActivity implements XListView.IXListViewListener {    private XliAdapter adapter;    private XListView xListView;    private  boolean index=true;    private  int   ind=0;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        xListView = (XListView) findViewById(R.id.xlist);        //允许加载更多        xListView.setPullLoadEnable(true);        //xlistview的 监听        xListView.setXListViewListener(this);        network();    }    //下拉更新    @Override    public void onRefresh() {        index=true;        ind+=5;        gethttpurl("http://apis.juhe.cn/cook/query?key=7f5fe6023517b145df5d07dfe6d266a6&menu=红烧肉&pn="+ind+"&rn=5");        //停止刷新        xListView.stopRefresh(true);    }    //上拉加载    @Override    public void onLoadMore() {        index=false;        ind+=5;       gethttpurl("http://apis.juhe.cn/cook/query?key=7f5fe6023517b145df5d07dfe6d266a6&menu=红烧肉&pn="+ind+"&rn=5");       //停止刷新        xListView.stopLoadMore();    } //判断网络的状态 public static boolean netWorkState(Context context){            ConnectivityManager service = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);            NetworkInfo info = service.getActiveNetworkInfo();            if (info!=null){                return info.isAvailable();            }            return false;        }    //判断网络状态    public void network(){        if (netWorkState(this)){            gethttpurl("http://apis.juhe.cn/cook/query?key=7f5fe6023517b145df5d07dfe6d266a6&menu=红烧肉&pn=1&rn=6");        }else {            Bean bean = nonetwork();            Bean.ResultBean result = bean.getResult();            List<Bean.ResultBean.DataBean> data = result.getData();            XliAdapter adapter = new XliAdapter(MainActivity.this, data);            xListView.setAdapter(adapter);            adapter.notifyDataSetChanged();        }    }    //网络获取资源    public void  gethttpurl(final String path){        new AsyncTask<String, Void, String>() {            private ProgressDialog progressDialog;    //进度条            @Override            protected void onPreExecute() {                super.onPreExecute();                progressDialog = new ProgressDialog(MainActivity.this);                progressDialog.setMessage("玩命加载中.......");                progressDialog.show();            }//更新UI操作            @Override            protected void onPostExecute(String s) {                super.onPostExecute(s);                progressDialog.dismiss();                if (s!=null){                    Gson gson = new Gson();                    Bean bean = gson.fromJson(s, Bean.class);                    Bean.ResultBean result = bean.getResult();                    List<Bean.ResultBean.DataBean> data = result.getData();                    if (adapter==null){                        adapter = new XliAdapter(MainActivity.this,data);                        xListView.setAdapter(adapter);                    }else {                        adapter.loaderimage(data,index);                    }                    adapter.notifyDataSetChanged();                }            }//完成耗时操作            @Override            protected String doInBackground(String... params) {                String path=params[0];                try {                    URL url = new URL(path);                    HttpURLConnection connection= (HttpURLConnection) url.openConnection();                    connection.setRequestMethod("GET");                    connection.setConnectTimeout(5000);                    int code = connection.getResponseCode();                    if (code==200){                        InputStream inputStream = connection.getInputStream();                        //使用的是工具类  将流 转换 成                        String altertype = ConversionStream.getAltertype(inputStream);                        //获取的 数据 写入 sd卡                        File file = new File(Environment.getExternalStorageDirectory(), "asd.txt");                        FileOutputStream stream = new FileOutputStream(file);                        stream.write(altertype.getBytes());                        stream.flush();                        stream.close();                        return altertype;                    }                } catch (MalformedURLException e) {                    e.printStackTrace();                } catch (IOException e) {                    e.printStackTrace();                }             return null;            }        }.execute(path);    }    //解析sd卡下的 gson串    public Bean nonetwork(){        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){            File file = new File(Environment.getExternalStorageDirectory(), "asd.txt");            try {                StringBuffer buffer = new StringBuffer();                FileInputStream stream = new FileInputStream(file);                //使用的是工具类  将流 转换 成                String altertype = ConversionStream.getAltertype(stream);                Gson gson = new Gson();                Bean bean = gson.fromJson(altertype, Bean.class);                return bean;            } catch (FileNotFoundException e) {                e.printStackTrace();            } catch (IOException e) {                e.printStackTrace();            }        }        return null;    }}

Adapter 适配器

public class XliAdapter extends BaseAdapter {    Context context;    List<Bean.ResultBean.DataBean> data;    private ViewHodler hodler;    private final DisplayImageOptions options;    public XliAdapter(Context context, List<Bean.ResultBean.DataBean> data) {        this.context = context;        this.data = data;        //是否缓存----->注意 :无网状态下想要获取图片显示在listview上就要写 这个缓存        options = new DisplayImageOptions.Builder()                .cacheInMemory(true)                .cacheOnDisk(true)                .build();    }    public void loaderimage(List<Bean.ResultBean.DataBean> lists,boolean index){        for (Bean.ResultBean.DataBean databean :lists){            if (index){                //下拉                data.add(0,databean);            }else {                data.add(databean);            }        }    }    @Override    public int getCount() {        return data.size();    }    @Override    public Object getItem(int position) {        return data.get(position);    }    @Override    public long getItemId(int position) {        return position;    }    @Override    public View getView(int position, View convertView, ViewGroup parent) {        if (convertView==null){            convertView=View.inflate(context, R.layout.list_view,null);            hodler = new ViewHodler();            hodler.image= (ImageView) convertView.findViewById(R.id.image);            hodler.name= (TextView) convertView.findViewById(R.id.name);            convertView.setTag(hodler);        }else {            hodler= (ViewHodler) convertView.getTag();        }        hodler.name.setText(data.get(position).getSteps().get(0).getStep());        //使用ImageLoader获取图片        ImageLoader.getInstance().displayImage(data.get(position).getSteps().get(0).getImg(),hodler.image,options);        return convertView;    }    static  class ViewHodler{        ImageView image;        TextView name;    }}

使用 ImageLoader获取图片

public class Loader extends Application{    @Override    public void onCreate() {        super.onCreate();        File cacheDir=StorageUtils.getCacheDirectory(this);        ImageLoaderConfiguration configuration= new ImageLoaderConfiguration.Builder(this)                .memoryCacheExtraOptions(480, 800) // default = device screen dimensions                .diskCacheExtraOptions(480, 800, null)                .threadPoolSize(3) // default                .threadPriority(Thread.NORM_PRIORITY - 1) // default                .tasksProcessingOrder(QueueProcessingType.FIFO) // default                .denyCacheImageMultipleSizesInMemory()                .memoryCache(new LruMemoryCache(2 * 1024 * 1024))                .memoryCacheSize(2 * 1024 * 1024)                .memoryCacheSizePercentage(13) // default                .diskCache(new UnlimitedDiskCache(cacheDir)) // default                .diskCacheSize(50 * 1024 * 1024)                .diskCacheFileCount(100)                .diskCacheFileNameGenerator(new HashCodeFileNameGenerator()) // default                .imageDownloader(new BaseImageDownloader(this)) // default                .imageDecoder(new BaseImageDecoder(true)) // default                .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default                .writeDebugLogs()                .build();        ImageLoader.getInstance().init(configuration);    }}
原创粉丝点击