列表数据显示

//activity_main

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.bwie.test.day_02.MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="商品列表"/>
    <com.handmark.pulltorefresh.library.PullToRefreshListView
        xmlns:ptr="http://schemas.android.com/apk/res-auto"
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:id="@+id/refresh_list_view"
        ptr:ptrDrawable="@drawable/default_ptr_flip"
        ptr:ptrAnimationStyle="flip"
        ptr:ptrHeaderBackground="#383838"
        ptr:ptrHeaderTextColor="#FFFFFF" >
    </com.handmark.pulltorefresh.library.PullToRefreshListView>

</LinearLayout>


//image_layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:orientation="horizontal">
    <ImageView
        android:id="@+id/image_item"
        android:layout_width="100dp"
        android:layout_height="100dp" />

    <LinearLayout
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <TextView
            android:id="@+id/image_title"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"/>
        <TextView
            android:id="@+id/image_price"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"/>
    </LinearLayout>

</LinearLayout>


//text_layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">
    <TextView
        android:id="@+id/text_title"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"/>
    <TextView
        android:id="@+id/text_price"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"/>

</LinearLayout>


//MainActivity

public class MainActivity extends AppCompatActivity {
    private PullToRefreshListView resh_list;
    private ILoadingLayout startLabels;
    private List<GoogsBean.DataBean> list = new ArrayList<>();
    private int pag=1;
    private MyAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        resh_list = (PullToRefreshListView) findViewById(R.id.refresh_list_view);

        resh_list.setMode(PullToRefreshBase.Mode.BOTH);
        initData();
        startLabels = resh_list.getLoadingLayoutProxy(true, false);
        startLabels.setPullLabel("下拉刷新");
        startLabels.setRefreshingLabel("正在拉");
        startLabels.setReleaseLabel("放开刷新");
        ILoadingLayout endLabels = resh_list.getLoadingLayoutProxy(false, true);
        endLabels.setPullLabel("上拉刷新");
        endLabels.setRefreshingLabel("正在载入...");
        endLabels.setReleaseLabel("放开刷新...");

        resh_list.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
               refresh();
              list.clear();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                initData();
                pag++;
            }
        });
    }

    private void initData() {
        NetUtil.getData(MainActivity.this, "http://120.27.23.105/product/getProducts?pscid=39&page="+pag, new JsonStringCallaBack() {
            @Override
            public void getJsonString(String json) {
                Toast.makeText(MainActivity.this,json,Toast.LENGTH_SHORT).show();
                Gson gson = new Gson();
                GoogsBean googsBean = gson.fromJson(json, GoogsBean.class);
                list.addAll(googsBean.getData());
                setAdapter();
                resh_list.onRefreshComplete();
            }
        });
    }

    private void refresh() {
        NetUtil.getData(MainActivity.this, "http://120.27.23.105/product/getProducts?pscid=39&page=1", new JsonStringCallaBack() {
            @Override
            public void getJsonString(String json) {
                Gson gson = new Gson();
                GoogsBean googsBean = gson.fromJson(json, GoogsBean.class);
                list.addAll(0,googsBean.getData());
                setAdapter();
                resh_list.onRefreshComplete();
            }
        });
    }

    private void setAdapter() {
        if(adapter==null){
            adapter = new MyAdapter(MainActivity.this,list);
            resh_list.setAdapter(adapter);
        }else {
            adapter.notifyDataSetChanged();
        }
    }
}


//MyHelper

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

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {

        //创建表
        sqLiteDatabase.execSQL("create table jsoncache(id integer primary key autoincrement,json text not null,url text not null)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }
}


//JsonDao

public class JsonDao {
    private MyHelper myHelper;

    public JsonDao(Context context) {
      myHelper = new MyHelper(context);
    }

    public void insertJson(String json,String url){

        SQLiteDatabase database = myHelper.getWritableDatabase();
        //现根据url删除json
        database.delete("jsoncache","url = ?",new String[]{url});

        //再去添加
        ContentValues values = new ContentValues();
        values.put("json",json);
        values.put("url",url);

        database.insert("jsoncache",null,values);
        //关闭
        database.close();
    }

    /**
     * 查询数据库的操作....根据传入url获取存的json字符串
     */
    public String getJson(String url){

        SQLiteDatabase writableDatabase = myHelper.getWritableDatabase();

        Cursor cursor = writableDatabase.query("jsoncache", new String[]{"json"}, "url = ?", new String[]{url}, null, null, null);

        if (cursor.moveToNext()){
            String json = cursor.getString(cursor.getColumnIndex("json"));

            return json;
        }

        return null;
    }
}


adapter文件夹下//MyAdapter

public class MyAdapter extends BaseAdapter {
    private static final int IMAGE =0 ;
    private static final int TEXTM = 1;
    private Context context;
    private List<GoogsBean.DataBean> list;
    public MyAdapter(Context context, List<GoogsBean.DataBean> list) {
        this.context = context;
        this.list= list;
    }

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

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

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

    @Override
    public int getViewTypeCount() {
        return 2;
    }

    @Override
    public int getItemViewType(int position) {
        if(position%2==0){
            return IMAGE;
        }
        return TEXTM;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        if(getItemViewType(i)==IMAGE){
            ImageHolder imageHolder;
            if(view==null){
                imageHolder = new ImageHolder();
                view = View.inflate(context, R.layout.image_layout,null);
                imageHolder.imageView = view.findViewById(R.id.image_item);
                imageHolder.title = view.findViewById(R.id.image_title);
                imageHolder.price = view.findViewById(R.id.image_price);
                view.setTag(imageHolder);
            }else {
                imageHolder = (ImageHolder) view.getTag();
            }
                imageHolder.title.setText(list.get(i).getTitle());
                imageHolder.price.setText(list.get(i).getPrice()+"");
                String[] split = list.get(i).getImages().split("\\|");
                ImageLoader.getInstance().displayImage(split[0],imageHolder.imageView, ImageUtil.getOption());

        }else {
            if (getItemViewType(i) == TEXTM) {
                TextHolder textHolder;
                if (view == null) {
                    textHolder = new TextHolder();
                    view = View.inflate(context, R.layout.text_layout, null);
                    textHolder.title = view.findViewById(R.id.text_title);
                    textHolder.price = view.findViewById(R.id.text_price);
                    view.setTag(textHolder);
                } else {
                    textHolder = (TextHolder) view.getTag();
                }
                textHolder.title.setText(list.get(i).getTitle());
                textHolder.price.setText(list.get(i).getPrice() + "");

            }
        }
        return view;
    }

    class ImageHolder{
        ImageView imageView;
        TextView title,price;
    }

    class TextHolder{
        TextView title,price;
    }
}


util文件夹下//ImageApplication

public class ImageApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        ImageUtil.initConfig(this);
    }
}


//ImageUtil

public class ImageUtil  {
    public static void initConfig(Context context) {

        File cacheDir = new File(Environment.getExternalStorageDirectory(), "cache");  //缓存文件夹路径

        if (!cacheDir.exists()) {
            cacheDir.mkdirs();
        }

        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
                .threadPoolSize(3)
                .threadPriority(Thread.NORM_PRIORITY - 2) // default 设置当前线程的优先级
                .tasksProcessingOrder(QueueProcessingType.FIFO) // default
                .denyCacheImageMultipleSizesInMemory()
                .memoryCache(new LruMemoryCache(2 * 1024 * 1024)) //可以通过自己的内存缓存实现
                .memoryCacheSize(2 * 1024 * 1024)  // 内存缓存的最大值
                .memoryCacheSizePercentage(13) // default
                .diskCache(new UnlimitedDiskCache(cacheDir))
                // .diskCache(new UnlimitedDiscCache(cacheDir)) // default 可以自定义缓存路径
                //UnlimitedDiskCache(cacheDir)
                .diskCacheSize(50 * 1024 * 1024) // 50 Mb sd(本地)缓存的最大值
                .diskCacheFileCount(100)  // 可以缓存的文件数量
                // default为使用HASHCODEUIL进行加密命名, 还可以用MD5(new Md5FileNameGenerator())加密
                .diskCacheFileNameGenerator(new HashCodeFileNameGenerator())
                .imageDownloader(new BaseImageDownloader(context)) // default
                .imageDecoder(new BaseImageDecoder(true)) // default
                .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default
                .writeDebugLogs() // 打印debug log
                .build(); //开始构建

        ImageLoader.getInstance().init(config);
    }

    public static DisplayImageOptions getOption() {

        DisplayImageOptions options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.mipmap.ic_launcher) // 设置图片下载期间显示的图片
                .showImageForEmptyUri(R.mipmap.ic_launcher) // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.mipmap.ic_launcher) // 设置图片加载或解码过程中发生错误显示的图片
                .resetViewBeforeLoading(true)  // default 设置图片在加载前是否重置、复位
                .delayBeforeLoading(1000)  // 下载前的延迟时间
                .cacheInMemory(true) // default  设置下载的图片是否缓存在内存中
                .cacheOnDisk(true) // default  设置下载的图片是否缓存在SD卡中
                .imageScaleType(ImageScaleType.EXACTLY_STRETCHED) // default 设置图片以如何的编码方式显示
                .bitmapConfig(Bitmap.Config.RGB_565) // default 设置图片的解码类型
                .build();

        return options;
    }
}


//JsonStringCallaBack

package com.bwie.test.util;

public interface JsonStringCallaBack {
    public void getJsonString(String json);
}


//NetUtil

public class NetUtil {
    public static void getData(Context context, final String path, final JsonStringCallaBack callaBack) {

        AsyncTask<Void, Void, String> asyncTask = new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... voids) {
                try {
                    URL url = new URL(path);

                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                    connection.setRequestMethod("GET");
                    connection.setReadTimeout(5000);
                    connection.setConnectTimeout(5000);

                    int responseCode = connection.getResponseCode();
                    if (responseCode == 200){
                        InputStream inputStream = connection.getInputStream();

                        String json = streamToString(inputStream,"utf-8");

                        return json;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(String json) {
                //异步拿回这个json,交给具体解析的那个类
                callaBack.getJsonString(json);
            }
        };
        asyncTask.execute();
    }

    private static String streamToString(InputStream inputStream, String charset) {
        try {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream,charset);

            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String s = null;
            StringBuilder builder = new StringBuilder();
            while ((s = bufferedReader.readLine()) != null){
                builder.append(s);
            }

            bufferedReader.close();
            return builder.toString();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return  null;
    }
}


bean文件夹下//GoogsBean

public class GoogsBean {
    private String msg;
    private String code;
    private String page;
    private List<DataBean> data;

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getPage() {
        return page;
    }

    public void setPage(String page) {
        this.page = page;
    }

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

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

    public static class DataBean {
        private double bargainPrice;
        private String createtime;
        private String detailUrl;
        private String images;
        private int itemtype;
        private int pid;
        private double price;
        private int pscid;
        private int salenum;
        private int sellerid;
        private String subhead;
        private String title;

        public double getBargainPrice() {
            return bargainPrice;
        }

        public void setBargainPrice(double bargainPrice) {
            this.bargainPrice = bargainPrice;
        }

        public String getCreatetime() {
            return createtime;
        }

        public void setCreatetime(String createtime) {
            this.createtime = createtime;
        }

        public String getDetailUrl() {
            return detailUrl;
        }

        public void setDetailUrl(String detailUrl) {
            this.detailUrl = detailUrl;
        }

        public String getImages() {
            return images;
        }

        public void setImages(String images) {
            this.images = images;
        }

        public int getItemtype() {
            return itemtype;
        }

        public void setItemtype(int itemtype) {
            this.itemtype = itemtype;
        }

        public int getPid() {
            return pid;
        }

        public void setPid(int pid) {
            this.pid = pid;
        }

        public double getPrice() {
            return price;
        }

        public void setPrice(double price) {
            this.price = price;
        }

        public int getPscid() {
            return pscid;
        }

        public void setPscid(int pscid) {
            this.pscid = pscid;
        }

        public int getSalenum() {
            return salenum;
        }

        public void setSalenum(int salenum) {
            this.salenum = salenum;
        }

        public int getSellerid() {
            return sellerid;
        }

        public void setSellerid(int sellerid) {
            this.sellerid = sellerid;
        }

        public String getSubhead() {
            return subhead;
        }

        public void setSubhead(String subhead) {
            this.subhead = subhead;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值