我想要的是什么:
我有ListView。
在fly中将数据加载到ListView(当用户滚动listView时)。数据来自SQLite表。
但是当SQLite表结束时 - 以JSON格式从GitHub API获取新数据。
然后将此数据保存到SQLite表,然后在lisview中显示新项目。
我该怎么做?提前致谢!
答案 0 :(得分:2)
您的自定义ListView类。
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.AbsListView;
/**
* Created by ozgur on 11/3/15 at 4:48 PM.
*/
public class ListView extends android.widget.ListView implements AbsListView.OnScrollListener {
private boolean inEndOfList = false;
private ListViewListener listViewListener;
public ListView(Context context) {
super(context);
init(context);
}
public ListView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public ListView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
@Override
public void onScrollStateChanged(AbsListView absListView, int scrollState) {
//Log("onScrollStateChanged(..), scrollState =" + scrollState);
}
@Override
public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
int tot = firstVisibleItem + visibleItemCount;
if(tot >= totalItemCount) {
if(!inEndOfList) {
Log("onScroll, end of list");
inEndOfList = true;
if(listViewListener != null)
listViewListener.onEndOfList();
}
} else
inEndOfList = false;
}
private void init(Context context) {
this.setOnScrollListener(this);
}
private void Log(String str) {
Log.d("ListView", str);
}
public void setListViewListener(ListViewListener listViewListener) {
this.listViewListener = listViewListener;
}
public static interface ListViewListener {
public void onEndOfList() ;
}
}
在您的活动中,实现ListView.ListViewListener
private ArrayList<Object> listObjects = new ArrayList<>();
int limit = 20;
int offset = 0;
private ListView customListView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_your);
initYourViews();
customListView.setListViewListener(this);
}
@Override
public void onEndOfList() {
this.offset += 10 + limit;
this.initData();
}
private void initData() {
new AsyncTask<Void, Void, ArrayList<Object> /* or whatever */>() {
@Override
protected ArrayList<Object> doInBackground(Void... voids) {
ArrayList<Object> temp = YourSqLiteController.getData(limit, offset);
if(temp.size == 0 /* assume db data consumed, get from REST API*/) {
temp = YourApi.getData();
}
}
@Override
protected void onPostExecute(ArrayList<Object> temp){
if(temp != null && temp.size() > 0)
listObjects.addAll(temp);
update();
}
}.execute();
}
private void update(){
this.listAdapter.notifyDataSetChanged(); /* your adapter */
}