我正在尝试在列表视图滚动结束时获取Sqlite数据库表的总记录数。但主要问题是第一次计数是否准确。当我再次滚动结束计数是增量。假设我有181个记录总计数,并再次滚动到最后得到计数是362,再次滚动得到543,... 724,... 905等等。为什么不像181那样得到恒定值。有人帮我解决它?
这是我的代码,用于获取Constant类
中的记录总数public final class Constant
{
public static SQLiteDatabase db;
public static MyDbHelper dbhelper;
public static int GetLocalPages(Context context)
{
dbhelper = new MyDbHelper(context);
dbhelper.onOpen(db);
String query = "select count(*) from ALL_Post";
db = dbhelper.getWritableDatabase();
Cursor c = db.rawQuery(query, null);
if (c.moveToFirst())
{
totalRowCount += c.getInt(0);
Log.e("11111 ", " totalRowCount = " + totalRowCount);
}
if(totalRowCount < 50)
{
num= 1 ;
Log.e("22222 "," num= " + num);
}
if(totalRowCount > 50)
{
num= totalRowCount / 50;
Log.e("33333 ", " num= " + num);
}
if(totalRowCount % 50> 0)
{
num += 1;
Log.e("44444 ", " num = " + num );
}
return num ;
}
}
这是我的listView scrollListener方法
listView.setOnScrollListener(new AbsListView.OnScrollListener()
{
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {}
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount)
{
lastInScreen = firstVisibleItem + visibleItemCount;
//Log.e("","lastInScreen="+lastInScreen);
if(lastInScreen == totalItemCount)
{
Toast.makeText(getApplicationContext(), "Your Last Item." + lastInScreen , Toast.LENGTH_SHORT).show();
int values= Constant.GetLocalPages(getApplicationContext());
Log.e("", "values=" + values);
}
}
});
答案 0 :(得分:1)
不确定如何定义totalRowCount
。但它看起来像一个定义的类变量,并且每次调用GetLocalPages(Context)
时都会保持递增。这解释了这种行为。
答案 1 :(得分:1)
指定totalRowCount = 0; 在调用数据库方法之前......
为什么你想要每卷都? 这是你的数据库的数量...并且不会在滚动时改变。 你只需要一次。
答案 2 :(得分:1)
你可以试试这个,
只需更改代码..
public final class Constant
{
public static SQLiteDatabase db;
public static MyDbHelper dbhelper;
public static int GetLocalPages(Context context)
{
dbhelper = new MyDbHelper(context);
dbhelper.onOpen(db);
int num =0;
String query = "select count(*) from ALL_Post";
db = dbhelper.getWritableDatabase();
Cursor c = db.rawQuery(query, null);
num =c.getCount();
return num ;
}
}
听众也有一些感情......
listView.setOnScrollListener(new AbsListView.OnScrollListener()
{
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {}
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount)
{
lastInScreen = firstVisibleItem + visibleItemCount;
//Log.e("","lastInScreen="+lastInScreen);
if(lastInScreen == totalItemCount)
{
Toast.makeText(getApplicationContext(), "Your Last Item." + lastInScreen , Toast.LENGTH_SHORT).show();
int values = 0;
values= Constant.GetLocalPages(getApplicationContext());
Log.e("", "values=" + values);
}
}
});
我希望这会对你有所帮助。