(imitating the headline APP project) 6. The clicked news list text is grayed out and pulled down to refresh and scroll to load the news data

Article catalog

1, Clicked news list text is grayed out

design sketch

Realization ideas

  • Create list click event use the database to store the clicked news data ID, and determine whether there is corresponding news data ID in the database to make the text gray (viewed).

Import ORM Lite database class dependency

implementation 'com.j256.ormlite:ormlite-android:5.0'

Using ORM Lite to create database and table

Create database class MyDbHelper

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

import java.sql.SQLException;

public class MyDbHelper extends OrmLiteSqliteOpenHelper {
    //Create database
    public MyDbHelper(Context context) {
        super(context, "new", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
        //Create table
        try {
            TableUtils.createTable(connectionSource,NewInfo.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {

    }
}

Create news entity class NewInfo in database

import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;

//Defining news entity class in database
@DatabaseTable(tableName = "news_table")
public class NewInfo {
    @DatabaseField(columnName = "id",generatedId = true)
    public Integer id;
    @DatabaseField(columnName = "newsId")
    public Integer newsId;//The newId in the table indicates that it has been read, otherwise it is not read
    public NewInfo(Integer newsId) {//Call by yourself, newsId is the news id of NewListData
        this.newsId = newsId;
    }
    public NewInfo() {//Framework call

    }
    @Override
    public String toString() {
        return "NewInfo{" +
                "id=" + id +
                ", newId=" + newsId +
                '}';
    }
}

Page transaction coding

List click event

//9. Click the monitor list
    private void onliseners() {
        //9.1 click monitor
        pullToRefreshListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //Since the pullToRefreshListView itself is one, start with 1
                NewListData.DataBean.NewsBean bean = adapter.getListData().get(position-1);
//                Toast.makeText(getContext(),"id="+bean.id,Toast.LENGTH_SHORT).show();
                //9.2 save with database
                MyDbHelper myDbHelper = new MyDbHelper(getContext());
                Dao<NewInfo, Integer> dao = null;
                try {
                    //dao is the object with the method of adding, deleting, modifying and checking
                    dao = myDbHelper.getDao(NewInfo.class);
                    List<NewInfo> list = dao.queryForEq("newsId",bean.id);//select statement 
                    if(list == null||list.size()==0) {//Execute an insert statement
                        dao.create(new NewInfo(bean.id));
                    }
                    System.out.println(dao.queryForAll().toString());
                    //9.6 call notifyDataSetChanged method of adapter to update data
                    adapter.notifyDataSetChanged();
                } catch (SQLException e) {
                    e.printStackTrace();
                }

            }
        });
    }

Judge whether the list content has been clicked in getView

  //Determine whether the list content has been clicked
            boolean isExist = false;
            try {
                isExist = queryIdInDb(newsBean.id);
            } catch (SQLException e) {
                e.printStackTrace();
            }
            if(type==0){//A picture
            //Add isExist parameter to judge whether it has been clicked
                return setDataToOneView(convertView, newsBean,isExist);
            }else {//Three figures
                return setDataToThreeView(convertView, newsBean,isExist);
            }

Create the queryIdInDb method to query whether the current news exists in the database

 //9.3 query whether the current news exists in the database
        MyDbHelper myDbHelper;
        Dao<NewInfo,Integer> dao;
    private boolean queryIdInDb(int id) throws SQLException {

        if (myDbHelper == null){
            myDbHelper= new MyDbHelper(getContext());

                dao = myDbHelper.getDao(NewInfo.class);

        }
        List<NewInfo> list = dao.queryForEq("newsId",id);
        if(list == null ||list.size()==0){
            return false;//It means that there is no database and you have not clicked
        }else {
            return true;
        }
    }

Change the color of the title and date according to whether there is a database table

holderOne.date.setTextColor(isExist? Color.GRAY : Color.BLACK);
            holderOne.title.setTextColor(isExist? Color.GRAY : Color.BLACK);

2, Pull down refresh and scroll load news data

design sketch

Realization ideas

  • Drop down refresh: 1. Clear the collection. 2. Add data. 3. Refresh the list. 4. Turn off waiting.
  • Scroll load: 1. Do not empty the collection. 2. Add data. 3. Refresh the list. 4. Turn off waiting.

Add a class to MyApi to get the url address of the next page

public interface MyApi {
    //Annotations and methods constitute implementation classes
    @GET("home.json")
    public Call<ResponseData> getType();
    @GET("10007/list_1.json")
    public  Call<NewListData> getNewList();
    //Get next page url address
    @GET
    public  Call<NewListData> getMoreData( @Url String loadMoreUrl);//Make baseurl address and variable into new address
}

Page transaction coding

Add rollover and dropdown refresher

   //10. Pull down refresh and scroll load
  private void setDataToView(NewListData.DataBean data) {
      //10.1 judge whether the control is empty. Only when it is empty can it be initialized
      if(pullToRefreshListView == null){
          //Find space
          pullToRefreshListView = fragmentView.findViewById(R.id.pull_listview);
          //Assign an adapter
          adapter = new NewListAdapter(data.news);
          pullToRefreshListView.setAdapter(adapter);
          //List click gray event
          onliseners();
          //10.2 add a scrolling and dropdown refresh listener to the list
          onlistenerspull(pullToRefreshListView);
      }

  }

Drop down refresh

  @Override
            public void onPullDownToRefresh(final PullToRefreshBase<ListView> refreshView) {
                //drop-down 
                //Request succeeded
                retrofit.create(MyApi.class).getNewList().enqueue(new Callback<NewListData>() {
                    @Override
                    public void onResponse(Call<NewListData> call, Response<NewListData> response) {
                        //10.5 address to save next page
                        loadMoreUrl = response.body().data.more;
                        //10.4: after requesting data to the server, first clear the collection, then add data, then refresh the list, turn off waiting
                        if(adapter!=null){
                            adapter.getListData().clear();//empty
                            adapter.getListData().addAll(response.body().data.news);
                            adapter.notifyDataSetChanged();//Refresh
                            //End refresh
                            refreshView.onRefreshComplete();
                            Toast.makeText(getContext(),"Page refreshed",Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<NewListData> call, Throwable t) {


                    }
                });

Scroll load

@Override
            public void onPullUpToRefresh(final PullToRefreshBase<ListView> refreshView) {
                //roll
                //10.4 the next page of data in the address area of loadMoreUrl needs to be used for rolling load
                retrofit.create(MyApi.class).getMoreData(loadMoreUrl).enqueue(new Callback<NewListData>() {
                    @Override
                    public void onResponse(Call<NewListData> call, Response<NewListData> response) {
                        if(adapter!=null){
                            adapter.getListData().addAll(response.body().data.news);
                            adapter.notifyDataSetChanged();
                            refreshView.onRefreshComplete();
                            Toast.makeText(getContext(),"Next page data displayed",Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<NewListData> call, Throwable t) {

                    }
                });

Total code

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.administrator.zhjrtt.R;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.j256.ormlite.dao.Dao;
import com.xzit.bean.NewListData;
import com.xzit.db.MyDbHelper;
import com.xzit.db.NewInfo;
import com.xzit.fragment.BaseFragment;
import com.xzit.net.MyApi;

import java.sql.SQLException;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

//1. Inherit BaseFragment
public class Page1Fragment extends BaseFragment {
   // 10.5 define a variable to save the url address of the next page
   private  String loadMoreUrl= null;
   // 2. Rewrite getMyView
    //3. Layout list
    View fragmentView;
    @Override
    protected View getMyView() {
        //4. Load layout
        fragmentView = View.inflate(getContext(), R.layout.fragment_new_list,null);
        return fragmentView;
    }
    //5. Request server data

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        //6. Execution request
        retrofit.create(MyApi.class).getNewList().enqueue(new Callback<NewListData>() {
            @Override
            public void onResponse(Call<NewListData> call, Response<NewListData> response) {
                //Pass the requested data to the view
                setDataToView(response.body().data);
                //10.5 address to save next page
                loadMoreUrl = response.body().data.more;
            }


            @Override
            public void onFailure(Call<NewListData> call, Throwable t) {

            }
        });
    }
    //7. Display
    PullToRefreshListView pullToRefreshListView;
    NewListAdapter adapter;
    //10. Pull down refresh and scroll load
    private void setDataToView(NewListData.DataBean data) {
        //10.1 judge whether the control is empty. Only when it is empty can it be initialized
        if(pullToRefreshListView == null){
            //Find space
            pullToRefreshListView = fragmentView.findViewById(R.id.pull_listview);
            //Assign an adapter
            adapter = new NewListAdapter(data.news);
            pullToRefreshListView.setAdapter(adapter);
            //List click gray event
            onliseners();
            //10.2 add a scrolling and dropdown refresh listener to the list
            onlistenerspull(pullToRefreshListView);
        }

    }

    private void onlistenerspull(PullToRefreshListView pullToRefreshListView) {
        //10.3 set the mode to BOTH
        pullToRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
        pullToRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {

            @Override
            public void onPullDownToRefresh(final PullToRefreshBase<ListView> refreshView) {
                //drop-down 
                //Request succeeded
                retrofit.create(MyApi.class).getNewList().enqueue(new Callback<NewListData>() {
                    @Override
                    public void onResponse(Call<NewListData> call, Response<NewListData> response) {
                        //10.5 address to save next page
                        loadMoreUrl = response.body().data.more;
                        //10.4: after requesting data to the server, first clear the collection, then add data, then refresh the list, turn off waiting
                        if(adapter!=null){
                            adapter.getListData().clear();//empty
                            adapter.getListData().addAll(response.body().data.news);
                            adapter.notifyDataSetChanged();//Refresh
                            //End refresh
                            refreshView.onRefreshComplete();
                            Toast.makeText(getContext(),"Page refreshed",Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<NewListData> call, Throwable t) {


                    }
                });

            }

            @Override
            public void onPullUpToRefresh(final PullToRefreshBase<ListView> refreshView) {
                //roll
                //10.4 the next page of data in the address area of loadMoreUrl needs to be used for rolling load
                retrofit.create(MyApi.class).getMoreData(loadMoreUrl).enqueue(new Callback<NewListData>() {
                    @Override
                    public void onResponse(Call<NewListData> call, Response<NewListData> response) {
                        if(adapter!=null){
                            adapter.getListData().addAll(response.body().data.news);
                            adapter.notifyDataSetChanged();
                            refreshView.onRefreshComplete();
                            Toast.makeText(getContext(),"Next page data displayed",Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<NewListData> call, Throwable t) {

                    }
                });
            }
        });
    }

    //9. Click the monitor list
    private void onliseners() {
        //9.1 click monitor
        pullToRefreshListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //Since the pullToRefreshListView itself is one, start with 1
                NewListData.DataBean.NewsBean bean = adapter.getListData().get(position-1);
//                Toast.makeText(getContext(),"id="+bean.id,Toast.LENGTH_SHORT).show();
                //9.2 save with database
                MyDbHelper myDbHelper = new MyDbHelper(getContext());
                Dao<NewInfo, Integer> dao = null;
                try {
                    //dao is the object with the method of adding, deleting, modifying and checking
                    dao = myDbHelper.getDao(NewInfo.class);
                    List<NewInfo> list = dao.queryForEq("newsId",bean.id);//select statement 
                    if(list == null||list.size()==0) {//Execute an insert statement
                        dao.create(new NewInfo(bean.id));
                    }
                    System.out.println(dao.queryForAll().toString());
                    //9.6 call notifyDataSetChanged method of adapter to update data
                    adapter.notifyDataSetChanged();
                } catch (SQLException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    class ViewHolderOne{
        public TextView title;
        public TextView date;
        public ImageView image;
    }
    class ViewHolderThree extends ViewHolderOne{
        public ImageView image1;
        public ImageView image2;
    }
    //8. Define adapter
    class NewListAdapter extends BaseAdapter {
        private List<NewListData.DataBean.NewsBean> listData;

        public List<NewListData.DataBean.NewsBean> getListData() {
            return listData;
        }

        public NewListAdapter(List<NewListData.DataBean.NewsBean> list) {
            listData = list;
        }

        @Override
        public int getViewTypeCount() {
            //Two views are returned, one is one diagram and the other is three diagram
            return 2;
        }

        @Override
        public int getItemViewType(int position) {
            NewListData.DataBean.NewsBean bean = listData.get(position);
            if(bean.type==0){
                //A picture
                return 0;//R.layout.item_new_one.xml
            }else {
                //Three figures
                return 1;////R.layout.item_new_three.xml
            }

        }

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

        @Override
        public Object getItem(int position) {
            return null;
        }

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

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolderOne holderOne = null;
            ViewHolderThree holderThree = null;
            //get data
            NewListData.DataBean.NewsBean newsBean = listData.get(position);
            //Judge whether the current view is one diagram or three diagrams
            int type = getItemViewType(position);
            //Determine whether the list content has been clicked
            boolean isExist = false;
            try {
                isExist = queryIdInDb(newsBean.id);
            } catch (SQLException e) {
                e.printStackTrace();
            }
            if(type==0){//A picture
                return setDataToOneView(convertView, newsBean,isExist);
            }else {//Three figures
                return setDataToThreeView(convertView, newsBean,isExist);
            }

        }

        @NonNull
        private View setDataToThreeView(View convertView, NewListData.DataBean.NewsBean newsBean, boolean isExist) {
            ViewHolderThree holderThree;
            if(convertView == null){
                convertView = View.inflate(getContext(),R.layout.item_new_three,null);
                holderThree = new ViewHolderThree();
                holderThree.title = convertView.findViewById(R.id.item_title_three);
                holderThree.date = convertView.findViewById(R.id.item_date_three);
                holderThree.image = convertView.findViewById(R.id.item_image1_three);
                holderThree.image1 = convertView.findViewById(R.id.item_image2_three);
                holderThree.image2 = convertView.findViewById(R.id.item_image3_three);
                convertView.setTag(holderThree);
            }else {
                holderThree = (ViewHolderThree) convertView.getTag();
            }
            holderThree.title.setText(newsBean.title);
            holderThree.date.setText(newsBean.pubdate);
            String imageUrl= "http://192.168.31.114:8080"+newsBean.listimage;
            String imageUrl1= "http://192.168.31.114:8080"+newsBean.listimage1;
            String imageUrl2= "http://192.168.31.114:8080"+newsBean.listimage2;
            Glide.with(getContext()).load(imageUrl).into(holderThree.image);
            Glide.with(getContext()).load(imageUrl1).into(holderThree.image1);
            Glide.with(getContext()).load(imageUrl2).into(holderThree.image2);
            //9.4 change the color of the title and date according to whether there is a database table
            holderThree.date.setTextColor(isExist? Color.GRAY : Color.BLACK);
            holderThree.title.setTextColor(isExist? Color.GRAY : Color.BLACK);
            return convertView;
        }

        //When the view is a picture
        @NonNull
        private View setDataToOneView(View convertView, NewListData.DataBean.NewsBean newsBean, boolean isExist) {
            ViewHolderOne holderOne;
            if(convertView ==null){
                //When the view is not reused
                convertView = View.inflate(getContext(),R.layout.item_new_one,null);
                holderOne = new ViewHolderOne();
                holderOne. title = convertView.findViewById(R.id.item_title);
                holderOne. date = convertView.findViewById(R.id.item_date);
                holderOne. image = convertView.findViewById(R.id.item_image);
                convertView.setTag(holderOne);
            }else {//View reuse
                holderOne= (ViewHolderOne) convertView.getTag();
            }


            holderOne. title.setText(newsBean.title);
            holderOne. date.setText(newsBean.pubdate);
            String imageUrl= "http://192.168.31.114:8080"+newsBean.listimage;
            Glide.with(getContext()).load(imageUrl).into(holderOne.image);
            //9.4 change the color of the title and date according to whether there is a database table
            holderOne.date.setTextColor(isExist? Color.GRAY : Color.BLACK);
            holderOne.title.setTextColor(isExist? Color.GRAY : Color.BLACK);
            return convertView;
        }

    }
    //9.3 query whether the current news exists in the database
        MyDbHelper myDbHelper;
        Dao<NewInfo,Integer> dao;
    private boolean queryIdInDb(int id) throws SQLException {

        if (myDbHelper == null){
            myDbHelper= new MyDbHelper(getContext());

                dao = myDbHelper.getDao(NewInfo.class);

        }
        List<NewInfo> list = dao.queryForEq("newsId",id);
        if(list == null ||list.size()==0){
            return false;//It means that there is no database and you have not clicked
        }else {
            return true;
        }
    }
}

Tags: Database Android Retrofit Java

Posted on Thu, 04 Jun 2020 05:33:21 -0700 by lalov1