Adapter and Caching Principle Example

Goal: read the information of the network interface, decode the json, fill the data into the listview through the adapter, and use the caching principle when establishing the adapter

Effect display: (dynamic image, may not be loaded)

write picture description here
write picture description here

Steps: The steps of the example are the ideas and cannot be disrupted. I think that the adapter should be built first, and then the data should be obtained. By analogy with charging, there must be a charger first, and then charging.

1. Modify the main page layout file, mainly to set the id for the daily department store map, the rest has nothing to do with this instance, this is part of the code

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

2. The main page completes the page jump, here is also some code

 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. Modify the layout file corresponding to PaoPaoActivity and add a listview control

<?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. Create item.xml of listview

<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. Create an entity class, create attributes according to the data to be filled, construct construction methods, and set set and get methods

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. Create an adapter. The caching principle is used here. The caching principle avoids repeated binding of controls

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. Create a custom class, create a sub-thread in it, complete the reading and parsing of the API, and then fill it into the list collection

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. Finally, modify PaoPaoActivity, and pass the api of daily department store to the sub-thread to read and decode. Hurry up and run the program.

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);



    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325533697&siteId=291194637