Android——“i 分享”APP开发Day04

在前一天已经建好了存放内容的表,也在QueryDiscover.java中实现了对info 表的查询,接下来就是在Android端的“发现”页实现分页加载Info表的功能

  1. 首先需要有用于动态加载数据的卡片布局,在这里用的是比较简单的实现方案——ListView。使用该方案首先在之前就已经建好并测试过的“发现”页(discover_tab_content.xml)添加ListView,添加后的代码如下:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ebebeb">
    <LinearLayout android:gravity="center_vertical"
        android:orientation="horizontal" android:id="@+id/title_bar"
        android:background="@drawable/title_bg_night" android:layout_width="fill_parent"
        android:layout_height="35.0dip">
        <ImageView android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:src="@drawable/app_icon" />
        <LinearLayout android:gravity="center_vertical"
            android:layout_width="0.0dip" android:layout_height="wrap_content"
            android:layout_weight="1.0">
            <TextView android:textSize="16.0sp" android:textColor="@color/titleTextColor"
                android:singleLine="true" android:id="@+id/myTitle"
                android:layout_width="fill_parent" android:ellipsize="end"
                android:layout_height="wrap_content" android:layout_marginLeft="2.0dip"
                android:text="@string/app_name" />
        </LinearLayout>


        <ImageButton android:id="@+id/back_button"
            android:layout_gravity="center" android:background="@color/transparent"
            android:layout_width="60.0dip" android:layout_height="29.0dip"
            android:layout_marginRight="5.0dip" android:src="@drawable/exit" />
    </LinearLayout>

  <!--  这里是最开始用于测试的元素
  <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:orientation="vertical" >

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:src="@drawable/tab_icon_two" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:padding="10dp"
            android:text="这是发现界面"
            android:textSize="20sp" />
    </LinearLayout>-->
    <LinearLayout
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="15dp"
        android:paddingRight="15dp"
        android:orientation="vertical"
        android:paddingTop="50dp">
       <!-- <TextView
            android:id="@+id/test_discover_tab"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_marginVertical="30dp"

            android:text="测试信息反馈"
            android:textColor="#B3B3B3"
            android:gravity="center"
            />-->
        <ListView
            android:id="@+id/discover_listView"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:dividerHeight="15dp"/>
    </LinearLayout>
</RelativeLayout>

        2.创建activity_find_list_item.xml,该布局是用于展示从数据库中读取的内容,在版本1.0里,计划在卡片中放内容标题和内容简述这两个字段,至于图片和音乐播放的样式暂时先隐藏,后期再实现这些数据的显示,该文件的代码如下:

<?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:background="@drawable/list_card_style"
        android:padding="20dp"
        android:orientation="vertical">
    <!--    <TextView
            android:id="@+id/newstitle"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"/>
        <TextView
            android:id="@+id/newscontent"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"/>-->

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/cardTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:textSize="18sp"
            android:textColor="#000000"
            android:text="我的数据" />

        <ImageView
            android:id="@+id/cardImg"
            android:layout_width="20dp"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:src="@drawable/my_tab_list2"
            />
    </RelativeLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="10dp"
        android:background="#000000"/>

    <TextView
        android:id="@+id/cardContent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:textColor="#000000"
        android:text="内容"/>

<!--   分享为图片/图书类型则显示-->
    <ImageView
        android:id="@+id/cardContent_pic"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/logo"
        android:visibility="gone"/>

    <!--   分享为音乐类型则显示-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:gravity="center"
        android:visibility="gone">

        <TextView
            android:id="@+id/cardTitle_music"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:textSize="18sp"
            android:textColor="#000000"
            android:text="演员——薛之谦" />

        <ImageView
            android:id="@+id/cardImg_musicBac"
            android:layout_width="20dp"
            android:layout_height="wrap_content"
            android:src="@drawable/my_tab_list2"
            />
    </LinearLayout>

    </LinearLayout>

      3. 因为要实现分页加载,所以需要一个用于加载数据的Button,在这里先创建一个布局文件activity_find_loadmore.xml实现加载Button,代码如下:

<?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:gravity="center">
    <Button
        android:id="@+id/loadMoreButton"
        android:layout_marginTop="4dp"
        android:layout_marginBottom="4dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#00000000"
        android:text="查看更多..."
        />
</LinearLayout>

       4.在正式处理数据前,还需要创建一个bean文件,用于存放和获取从数据库中读取的内容。首先我创建了一个com.example.bean包,在该包下面创建一个Class文件FindInfo.java,具体就是实现对象属性的设置与获取,而该对象的属性包括info表的所有字段,完整代码如下:

package com.example.bean;

public class FindInfo {
    String infoId;    //内容ID
    String infoTitle;   //内容标题
    String infoDescribe;   //内容简述
    String infoDetail;   //内容详情

    Integer type;    //类型:0表示日记,1表示趣事
    Integer support;   //点赞数

    String infoAuthor;  //作者


    public String getInfoId() {
        return infoId;
    }
    public void setInfoId(String infoId) {
        this.infoId = infoId;
    }


    public String getInfoTitle() {
        return infoTitle;
    }
    public void setInfoTitle(String infoTitle) {
        this.infoTitle = infoTitle;
    }

    public String getInfoDescribe() {
        return infoDescribe;
    }
    public void setInfoDescribe(String infoDescribe) {
        this.infoDescribe = infoDescribe;
    }

    public String gettype() { return infoDetail; }
    public void setInfoDetail(String infoDetail) {
        this.infoDetail = infoDetail;
    }

    public Integer getType() { return type; }
    public void setType(Integer type) { this.type = type; }

    public Integer getSupport() { return support; }
    public void setSupport(Integer support) { this.support = support; }

    public String getInfoAuthor() {
        return infoAuthor;
    }
    public void setInfoAuthor(String infoAuthor) { this.infoAuthor = infoAuthor; }
}

       5.有了上述四个文件,就可以开始编辑之前写好的DiscoverTabFragment.java文件了,在这里获取数据库的内容并显示到“发现页”,在这里使用的是比较基础的BaseAdapter——自己写构造体和方法,然后在getview中返回view到列表项绑定,实现后台数据与UI的关联

  • 首先是要从后台服务获取内容,参数是请求的页面和每页显示的数据数,在进行一次请求之后执行请求页数加1的操作,在这部分比较关键的就是将返回的字符串转为JsonArray,这部分的实现放在了loadDataFromDataBase()方法中,具体代码如下

 

/**
 * 查询数据库中的数据
 */
private JSONArray loadDataFromDataBase(){

    //Toast.makeText(getActivity(),"保存",Toast.LENGTH_SHORT).show();
    StringBuilder stringBuilder = new StringBuilder();
    BufferedReader buffer = null;
    HttpURLConnection connGET = null;

    try {
        String LoginUrl = baseUrl+"QueryDiscover?page="+page+"&count="+count;
        URL url = new URL(LoginUrl);
        connGET = (HttpURLConnection) url.openConnection();
        connGET.setConnectTimeout(5000);
        connGET.setRequestMethod("GET");
        if (connGET.getResponseCode() == 200) {
            buffer = new BufferedReader(new InputStreamReader(connGET.getInputStream()));
            for (String s = buffer.readLine(); s != null; s = buffer.readLine()) {
                stringBuilder.append(s);
            }

            //返回测试信息
            JSONArray jsonArray = new JSONArray(stringBuilder.toString());
         /*   testTxt.setText(baseUrl+"QueryDiscover?page="+page+"&count="+count);*/
            //获取到的数据,对Json进行解析
            page = page+1;  //一次成功请求后更新请求页面
            buffer.close();

            return jsonArray;
        }else{
            Toast.makeText(getActivity(),"非200", Toast.LENGTH_LONG).show();
        }
    } catch (Exception e) {
        e.printStackTrace();
        Toast.makeText(getActivity(), "get 提交 err.." + e.toString(), Toast.LENGTH_LONG).show();
    }
    return null;
}
  • 接下来就需要将返回的数据取出来,存入FindInfo对象中,并将所有的对象存放到List<FindInfo>中,以方便将数据放入适配器显示。在这部分比较关键的就是从JsonArray读取出每个键对应的值,我把该功能放在public List<FindInfo> initSetDataToBean(String detail)方法中,具体代码如下:
//初始化将详情设置到FindInfo bean中
public List<FindInfo> initSetDataToBean(String detail){
    List<FindInfo> findInfo = new ArrayList<FindInfo>();
    try {
        JSONArray detailJsonArray = new JSONArray(detail);
        for (int i = 0; i < detailJsonArray.length(); i++) {
            FindInfo items = new FindInfo();

            JSONObject temp = (JSONObject) detailJsonArray.get(i);

            String infoId = temp.getString("infoId");    //内容ID
            String infoTitle = temp.getString("infoTitle");   //内容标题
            String infoDescribe = temp.getString("infoDescribe");   //内容简述
            String infoDetail = temp.getString("infoDetail");   //内容详情
            Integer type = temp.getInt("infoType");    //类型:0表示日记,1表示趣事
            Integer support = temp.getInt("infoSupport");   //点赞数
            String infoAuthor = temp.getString("infoAuthor");  //作者

            items.setInfoId(infoId);
            items.setInfoTitle(infoTitle);
            items.setInfoDescribe(infoDescribe);
            items.setInfoDetail(infoDetail);
            items.setType(type);
            items.setSupport(support);
            items.setInfoAuthor(infoAuthor);

            findInfo.add(items);
        }
        return findInfo;

    }catch (JSONException e){
        Toast.makeText(getActivity(), "initSetDataToBean异常 err.." + e.toString(), Toast.LENGTH_LONG).show();
        return null;
    }
}
  •  除了上述的两个方法,还需要将数据传到UI显示组件中,该部分就是BaseAdapter的主要工作了,具体代码如下:
/**
 * 将一组数据传到ListView等UI显示组件
 */

class PaginationAdapter extends BaseAdapter {

    List<FindInfo> newsItems;

    public PaginationAdapter(List<FindInfo> newsitems){
        this.newsItems = newsitems;
    }

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

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

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


    //在这里将Item设置到每个卡片
    @Override
    public View getView(int position, View view, ViewGroup parent) {
        if(view == null){
            view = getLayoutInflater().inflate(R.layout.activity_find_list_item, null);
        }

        //标题
        TextView tvTitle = (TextView)view.findViewById(R.id.cardTitle);
        tvTitle.setText(newsItems.get(position).getInfoTitle());

        //内容
        TextView tvContent = (TextView)view.findViewById(R.id.cardContent);
        tvContent.setText(newsItems.get(position).getInfoDescribe());

        return view;
    }

    /**
     * 添加数据列表项
     * @param infoItem
     */
    public void addNewsItem(FindInfo infoItem){
        newsItems.add(infoItem);
    }

}
  • 有了上述的方法,就可以初始化ListView适配器了,让页面在刚进入的时候就展示出第一页的十条数据

 

/**
 * 初始化ListView的适配器,即打开页面展示的数据
 */
private void initializeAdapter(){
    // 设置线程策略
    setVersion();
    JSONArray jsonArray = loadDataFromDataBase();
    try {
        JSONObject totalObject = (JSONObject)jsonArray.get(0);

        dataSize = totalObject.getInt("totalRecord");  //总记录数
        String detail= totalObject.getString("RecordDetail");   //详情

        if(initSetDataToBean(detail)!=null) {
            adapter = new PaginationAdapter(initSetDataToBean(detail));   //将详情设置到bean中
        }

    }catch (JSONException e){
        Toast.makeText(getActivity(), "initializeAdapter异常 err.." + e.toString(), Toast.LENGTH_LONG).show();
    }

}

  6.通过上述代码就可以实现页面的初始化,但是因为还需要分页加载,所以在上述的基础上还要有一个方法来实现将数据添加到适配器的操作,该方法为public void loadMoreSetDataToBean(String detail),具体代码实现如下:

//加载更多将详情设置到FindInfo bean中
public void loadMoreSetDataToBean(String detail){

    try {
        JSONArray detailJsonArray = new JSONArray(detail);

        for (int i = 0; i < detailJsonArray.length(); i++) {
            FindInfo items = new FindInfo();
            JSONObject temp = (JSONObject) detailJsonArray.get(i);
            String infoId = temp.getString("infoId");    //内容ID
            String infoTitle = temp.getString("infoTitle");   //内容标题
            String infoDescribe = temp.getString("infoDescribe");   //内容简述
            String infoDetail = temp.getString("infoDetail");   //内容详情

            Integer type = temp.getInt("infoType");    //类型:0表示日记,1表示趣事
            Integer support = temp.getInt("infoSupport");   //点赞数
            String infoAuthor = temp.getString("infoAuthor");  //作者

            items.setInfoId(infoId);
            items.setInfoTitle(infoTitle);
            items.setInfoDescribe(infoDescribe);
            items.setInfoDetail(infoDetail);
            items.setType(type);
            items.setSupport(support);
            items.setInfoAuthor(infoAuthor);

            adapter.addNewsItem(items);   //与初始化是有差异的
        }

    }catch (JSONException e){
        Toast.makeText(getActivity(), "loadMoreSetDataToBean异常 err.." + e.toString(), Toast.LENGTH_LONG).show();
    }

}

   7.最后只要将加载更多数据和更新UI的操作绑定到“加载更多”按钮的事件中就基本完成分页加载的功能了,关于DiscoverFragment.java文件的完整代码如下所示:

package com.example.discover;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.bean.FindInfo;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class DiscoverTabFragment extends Fragment implements AbsListView.OnScrollListener{
    Activity mActivity;     //存放当前的activity
    String baseUrl = "http://10.0.2.2:8080/iShareService/servlet/";   //web服务器的地址
    String imgBaseUrl = "http://10.0.2.2:8080/iShareService/images/";  //图片资源


    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View discoverLayout = inflater.inflate(R.layout.discover_tab_content, container, false);
        return discoverLayout;
    }

    private ListView listView;
    private int page = 1; //请求页数
    private int count = 10; //每次请求的数量
    private int visibleLastIndex = 0;  //最后的可视项索引
    private int visibleItemCount;    // 当前窗口可见项总数
    private int dataSize = 28;     //数据集的条数
    private DiscoverTabFragment.PaginationAdapter adapter;
    private View loadMoreView;
    private Button loadMoreButton;
    private Handler handler = new Handler();

    //返回测试信息
    /*TextView testTxt;*/

    /** Called when the activity is first created. */
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        /*setContentView(R.layout.main);*/
        loadMoreView = getLayoutInflater().inflate(R.layout.activity_find_loadmore, null);
        loadMoreButton = (Button)loadMoreView.findViewById(R.id.loadMoreButton);
        loadMoreButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                loadMoreButton.setText("正在加载中...");  //设置按钮文字
                handler.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        loadMoreData();
                        adapter.notifyDataSetChanged();
                        loadMoreButton.setText("查看更多..."); //恢复按钮文字
                    }
                },2000);

            }
        });

        //返回测试信息
       /* testTxt = (TextView)getActivity().findViewById(R.id.test_discover_tab);*/

        listView = (ListView)getActivity().findViewById(R.id.discover_listView);
        listView.addFooterView(loadMoreView);  //设置列表底部视图
        initializeAdapter();
        listView.setAdapter(adapter);
        listView.setOnScrollListener(this);
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        int itemsLastIndex = adapter.getCount()-1; //数据集最后一项的索引
        int lastIndex = itemsLastIndex + 1;
        if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE
                && visibleLastIndex == lastIndex) {
            // 如果是自动加载,可以在这里放置异步加载数据的代码
        }
    }


    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
                         int visibleItemCount, int totalItemCount) {
        this.visibleItemCount = visibleItemCount;
        visibleLastIndex = firstVisibleItem + visibleItemCount - 1;  //最后的可视项索引

        Log.e("firstVisibleItem = ",firstVisibleItem+"");
        Log.e("visibleItemCount = ",visibleItemCount+"");
        Log.e("totalItemCount = ",totalItemCount+"");


        //如果所有的记录选项等于数据集的条数,则移除列表底部视图
        if(totalItemCount == dataSize+1){
            listView.removeFooterView(loadMoreView);
            Toast.makeText(getActivity(),  "数据全部加载完!", Toast.LENGTH_LONG).show();
        }
    }
    /**
     * 查询数据库中的数据
     */
    private JSONArray loadDataFromDataBase(){

        //Toast.makeText(getActivity(),"保存",Toast.LENGTH_SHORT).show();
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader buffer = null;
        HttpURLConnection connGET = null;

        try {
            String LoginUrl = baseUrl+"QueryDiscover?page="+page+"&count="+count;
            URL url = new URL(LoginUrl);
            connGET = (HttpURLConnection) url.openConnection();
            connGET.setConnectTimeout(5000);
            connGET.setRequestMethod("GET");
            if (connGET.getResponseCode() == 200) {
                buffer = new BufferedReader(new InputStreamReader(connGET.getInputStream()));
                for (String s = buffer.readLine(); s != null; s = buffer.readLine()) {
                    stringBuilder.append(s);
                }

                //返回测试信息
                JSONArray jsonArray = new JSONArray(stringBuilder.toString());
             /*   testTxt.setText(baseUrl+"QueryDiscover?page="+page+"&count="+count);*/
                //获取到的数据,对Json进行解析
                page = page+1;  //一次成功请求后更新请求页面
                buffer.close();

                return jsonArray;
            }else{
                Toast.makeText(getActivity(),"非200", Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getActivity(), "get 提交 err.." + e.toString(), Toast.LENGTH_LONG).show();
        }
        return null;
    }

    //初始化将详情设置到FindInfo bean中
    public List<FindInfo> initSetDataToBean(String detail){
        List<FindInfo> findInfo = new ArrayList<FindInfo>();
        try {
            JSONArray detailJsonArray = new JSONArray(detail);
            for (int i = 0; i < detailJsonArray.length(); i++) {
                FindInfo items = new FindInfo();

                JSONObject temp = (JSONObject) detailJsonArray.get(i);

                String infoId = temp.getString("infoId");    //内容ID
                String infoTitle = temp.getString("infoTitle");   //内容标题
                String infoDescribe = temp.getString("infoDescribe");   //内容简述
                String infoDetail = temp.getString("infoDetail");   //内容详情
                Integer type = temp.getInt("infoType");    //类型:0表示日记,1表示趣事
                Integer support = temp.getInt("infoSupport");   //点赞数
                String infoAuthor = temp.getString("infoAuthor");  //作者

                items.setInfoId(infoId);
                items.setInfoTitle(infoTitle);
                items.setInfoDescribe(infoDescribe);
                items.setInfoDetail(infoDetail);
                items.setType(type);
                items.setSupport(support);
                items.setInfoAuthor(infoAuthor);

                findInfo.add(items);
            }
            return findInfo;

        }catch (JSONException e){
            Toast.makeText(getActivity(), "initSetDataToBean异常 err.." + e.toString(), Toast.LENGTH_LONG).show();
            return null;
        }
    }


    //加载更多将详情设置到FindInfo bean中
    public void loadMoreSetDataToBean(String detail){

        try {
            JSONArray detailJsonArray = new JSONArray(detail);

            for (int i = 0; i < detailJsonArray.length(); i++) {
                FindInfo items = new FindInfo();
                JSONObject temp = (JSONObject) detailJsonArray.get(i);
                String infoId = temp.getString("infoId");    //内容ID
                String infoTitle = temp.getString("infoTitle");   //内容标题
                String infoDescribe = temp.getString("infoDescribe");   //内容简述
                String infoDetail = temp.getString("infoDetail");   //内容详情

                Integer type = temp.getInt("infoType");    //类型:0表示日记,1表示趣事
                Integer support = temp.getInt("infoSupport");   //点赞数
                String infoAuthor = temp.getString("infoAuthor");  //作者

                items.setInfoId(infoId);
                items.setInfoTitle(infoTitle);
                items.setInfoDescribe(infoDescribe);
                items.setInfoDetail(infoDetail);
                items.setType(type);
                items.setSupport(support);
                items.setInfoAuthor(infoAuthor);

                adapter.addNewsItem(items);   //与初始化是有差异的
            }

        }catch (JSONException e){
            Toast.makeText(getActivity(), "loadMoreSetDataToBean异常 err.." + e.toString(), Toast.LENGTH_LONG).show();
        }

    }
    /**
     * 初始化ListView的适配器,即打开页面展示的数据
     */
    private void initializeAdapter(){
        // 设置线程策略
        setVersion();
        JSONArray jsonArray = loadDataFromDataBase();
        try {
            JSONObject totalObject = (JSONObject)jsonArray.get(0);

            dataSize = totalObject.getInt("totalRecord");  //总记录数
            String detail= totalObject.getString("RecordDetail");   //详情

            if(initSetDataToBean(detail)!=null) {
                adapter = new PaginationAdapter(initSetDataToBean(detail));   //将详情设置到bean中
            }

        }catch (JSONException e){
            Toast.makeText(getActivity(), "initializeAdapter异常 err.." + e.toString(), Toast.LENGTH_LONG).show();
        }

    }

    //APP如果在主线程中请求网络操作,将会抛出异常,所以需要用线程来操作网络请求
    void setVersion() {
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                .detectDiskReads()
                .detectDiskWrites()
                .detectNetwork()
                .penaltyLog()
                .build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                .detectLeakedSqlLiteObjects() //探测SQLite数据库操作
                .penaltyLog() //打印logcat
                .penaltyDeath()
                .build());
    }



    /**
     * 加载更多数据
     */
    private void loadMoreData(){
        JSONArray jsonArray = loadDataFromDataBase();   //从服务器获取资源

        try {
            JSONObject total = (JSONObject) jsonArray.get(0);
            dataSize = total.getInt("totalRecord");  //总记录数
            String detail= total.getString("RecordDetail");   //详情

            loadMoreSetDataToBean(detail);   //将更多的详情设置到bean中
        }catch (JSONException e){
            Toast.makeText(getActivity(), "loadMoreData()异常 err.." + e.toString(), Toast.LENGTH_LONG).show();
        }

//        连接数据库前的测试数据
//        int ad_count = adapter.getCount();
//        if(ad_count+count <= dataSize){
//            for(int i=ad_count+1; i<=ad_count+count; i++){
//                FindInfo item = new FindInfo();
//                item.setTitle("Title"+i);
//                item.setContent("This is News Content"+i);
//                adapter.addNewsItem(item);
//            }
//        }else{
//            for(int i=ad_count+1; i<=dataSize; i++){
//                FindInfo item = new FindInfo();
//                item.setTitle("Title"+i);
//                item.setContent("This is News Content"+i);
//                adapter.addNewsItem(item);
//            }
//        }

    }


    /**
     * 将一组数据传到ListView等UI显示组件
     */

    class PaginationAdapter extends BaseAdapter {

        List<FindInfo> newsItems;

        public PaginationAdapter(List<FindInfo> newsitems){
            this.newsItems = newsitems;
        }

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

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

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


        //在这里将Item设置到每个卡片
        @Override
        public View getView(int position, View view, ViewGroup parent) {
            if(view == null){
                view = getLayoutInflater().inflate(R.layout.activity_find_list_item, null);
            }

            //标题
            TextView tvTitle = (TextView)view.findViewById(R.id.cardTitle);
            tvTitle.setText(newsItems.get(position).getInfoTitle());

            //内容
            TextView tvContent = (TextView)view.findViewById(R.id.cardContent);
            tvContent.setText(newsItems.get(position).getInfoDescribe());

            return view;
        }

        /**
         * 添加数据列表项
         * @param infoItem
         */
        public void addNewsItem(FindInfo infoItem){
            newsItems.add(infoItem);
        }

    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值