适配器和缓存原理实例

目标:读取网络接口的信息,进过json解码,将数据通过适配器填充到listview中,建立适配器时使用缓存原理

效果展现:(动态图,可能加载不了)

这里写图片描述
这里写图片描述

步骤:实例的步骤就是思路,不可打乱,我认为应先建好适配器,再获得数据,类比充电,先要有充电器,然后再充电。

1、修改主页面布局文件,主要是给日常百货图设置id,其余的与这次实例无关,这是部分代码

<ImageView
                android:id="@+id/articles_imagev"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:src="@mipmap/articles" />

2、主页面完成页面的跳转,这里也是部分代码

 public void onClick(View v) {
        switch (v.getId()) {
            case R.id.articles_imagev:
                //单纯的页面跳转
                Intent intent = new Intent(MainActivity.this,PaoPaoActivity.class);
                this.startActivity(intent);
                break;

3、修改PaoPaoActivity对应的布局文件,添加listview控件

<?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.example.administrator.paopao.activity.daily.PaoPaoActivity">

    <ListView
        android:id="@+id/paopao_lv"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </ListView>

</LinearLayout>

4、创建listview的item.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/richang_item_list_tv"
        android:layout_width="match_parent"
        android:textSize="30sp"
        android:text=""
        android:layout_height="50dp" />

</LinearLayout>

5、创建实体类,根据将要填充的数据,创建属性,构造构造方法,设置set、get方法

public class Daily {

    private int categoryId;
    private int classifyId;
    private String classifyName;

    public Daily(int categoryId, int classifyId, String classifyName) {
        this.categoryId = categoryId;
        this.classifyId = classifyId;
        this.classifyName = classifyName;
    }

    public int getCategoryId() {
        return categoryId;
    }

    public void setCategoryId(int categoryId) {
        this.categoryId = categoryId;
    }

    public int getClassifyId() {
        return classifyId;
    }

    public void setClassifyId(int classifyId) {
        this.classifyId = classifyId;
    }

    public String getClassifyName() {
        return classifyName;
    }

    public void setClassifyName(String classifyName) {
        this.classifyName = classifyName;
    }
}

6、创建适配器,这里用到缓存原理,缓存原理避免了控件的重复绑定

public class DailyAdapter extends BaseAdapter {

    private Context context;
    private List<Daily> dailyList;

    public DailyAdapter(Context context, List<Daily> dailyList) {
        this.context = context;
        this.dailyList = dailyList;
    }

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

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

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {


        View view = null;
        ViewHolder viewHolder = null;
        //先创建一个内部类,用来放定义控件,然后在if语句中判断converview是否为空,第一次应该是空的,然后绑定id
        if (convertView == null) {
            //实例化view
            view = LayoutInflater.from(context).inflate(R.layout.richang_item, null);
            viewHolder = new ViewHolder();
            viewHolder.tv = view.findViewById(R.id.richang_item_list_tv);
            //将viewHolder打包
            view.setTag(viewHolder);
        } else {
            //第二次直接判断时,converview不为空,直接执行这一步
            view = convertView;
            viewHolder = (ViewHolder) view.getTag();
        }
        //赋值
        viewHolder.tv.setText(dailyList.get(position).getClassifyName());
        return view;
    }
    //创建内部类,创建控件
    public class ViewHolder {
        TextView tv;
    }
}

7、创建自定义类,在里面创建子线程,完成API的读取,解析,然后填充到list集合中

public class HttpDemo extends AsyncTask<String,String,String>{

    private List<Daily> dailyList;
    private Context context;
    private static  final String TAG= "HttpDemo";
    private ListView listView;

    public HttpDemo(List<Daily> dailyList, Context context,ListView listView) {
        this.dailyList = dailyList;
        this.context = context;
        this.listView = listView;
    }

    @Override
    protected String doInBackground(String... strings) {

        InputStream inputStream = null;
        StringBuffer stringBuffer = new StringBuffer();
        try {
            URL url = new URL(strings[0]);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            if(httpURLConnection.getResponseCode()==200){
                inputStream = httpURLConnection.getInputStream();
            }else{
                return "network_failed";
            }
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"UTF-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            stringBuffer = new StringBuffer();
            String temp = null;
            if((temp=bufferedReader.readLine())!=null){
                stringBuffer.append(temp);
            }

            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


        return stringBuffer.toString();
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        if(s.equals("network_failed")){
            Toast.makeText(context,"联网异常",Toast.LENGTH_SHORT).show();

        }else{
            try {
                JSONObject jsonObject = new JSONObject(s);
                JSONArray jsonArray = jsonObject.getJSONArray("datas");
                for(int i = 0;i<jsonArray.length();i++){
                    JSONObject jsonObjectindex = jsonArray.getJSONObject(i);
                    //调用构造方法,创建对象,并添加到list集合中
                    Daily daily = new Daily(jsonObjectindex.getInt("category_id"),jsonObjectindex.getInt("classify_id"),jsonObjectindex.getString("classify_name"));
                    dailyList.add(daily);
                   //Log.e(TAG, "onPostExecute: "+dailyList.get(i).getClassifyName());
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        //注意这里是最后一步,在这里我先写了,为了让子线程完成解析数据后,再创建适配器,绑定适配器,要在这里进行适配器的绑定
        DailyAdapter dailyAdapter = new DailyAdapter(context,dailyList);
        listView.setAdapter(dailyAdapter);
    }
}

8、最后修改PaoPaoActivity,将日常百货的api传给子线程读取,解码。快点运次运行一下程序吧。

public class PaoPaoActivity extends AppCompatActivity {

    private ListView listView;
    private static final String TAG = "PaoPaoActivity";
    private List<Daily> dailyList = new ArrayList<>();
    //这里是日常百货得API
    private String API = "http://103.244.59.105:8014/paopaoserver/articles?params={%22page%22:1,%22page_count%22:10}";


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

        listView = findViewById(R.id.paopao_lv);

        Log.e(TAG, "onItemClick: " + API);

        HttpDemo httpDemo = new HttpDemo(dailyList, PaoPaoActivity.this, listView);
        httpDemo.execute(API);



    }
}

猜你喜欢

转载自blog.csdn.net/shaochen2015821426/article/details/79596667
今日推荐