我正在尝试从SQLite中检索表的row_count。我用来执行此任务的代码冻结了我的应用程序。这完全在后端运行,MainUI线程中没有任何内容。但是,我也得到了ANR错误。
这是我的代码,我在这里调用方法 -
public class del_person extends Activity{
String[] images = {};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.del_person);
final adapter info = new adapter(this);
// new del_person_Dup(null).execute();
new Task(info).execute((Void)null);
}
}
class Task extends AsyncTask<Void, Void, Void> {
String[] images = {};
adapter mAdapter;
Task(adapter adapter) {
mAdapter = adapter;
}
@Override
protected Void doInBackground(Void... params) {
// the code from the Runnable using the mAdapter instead of info.
Log.v("distinctrowcount() is:",""+mAdapter.distinctrowcount()+"");
Log.v("started del_person.java","started del_person.java");
for (int i=0;i<mAdapter.distinctrowcount();i++)
{
Log.v ("This is the "+i+"th iteration","This is the "+i+"th iteration");
images[i] =mAdapter.getPersonList(i+1);
Log.v("Persons",images[i]);
}
return null;
}
}
我也尝试过使用AsyncTask。但是,我也无法摆脱这一点。
这是来自适配器类的我的distinctrowcount():
adapter.java:
public int distinctrowcount()
{
int rc = 0;
try {
open();
rc = mDbHelper.getdistinctrc();
close();
}
catch (Exception e)
{
e.printStackTrace();
}
return rc;
}
helper.java - getdistinctrc():
public int getdistinctrc() {
// TODO Auto-generated method stub
SQLiteDatabase myDB;
int values = 0;
int distinct_count = 0;
try {
myDB=this.openDataBase();
Cursor c=myDB.rawQuery("select count (DISTINCT FileName) from Photos;",null);
if (c != null ) {
String h = "";
while(c.moveToFirst()){
distinct_count = c.getInt(0);
// h = c.getString(c.getColumnIndex("COUNT(*)"));
}
}
if(c != null)
{
c.close();
myDB.close();
}
}catch(SQLException sqle){
throw sqle;
}
return distinct_count;
}
AsyncTask代码:
class Task extends AsyncTask<Void, Void, Void> {
String[] images = {};
adapter mAdapter;
Task(adapter adapter) {
mAdapter = adapter;
}
@Override
protected Void doInBackground(Void... params) {
// the code from the Runnable using the mAdapter instead of info.
Log.v("distinctrowcount() is:",""+mAdapter.distinctrowcount()+"");
Log.v("started del_person.java","started del_person.java");
for (int i=0;i<mAdapter.distinctrowcount();i++)
{
Log.v ("This is the "+i+"th iteration","This is the "+i+"th iteration");
images[i] =mAdapter.getPersonList(i+1);
Log.v("Persons",images[i]);
}
return null;
}
}
除了Runnable()和AsyncTask之外,还有其他更好的方法来实现吗?请帮我一些示例代码。
提前致谢。
答案 0 :(得分:1)
您当前的代码不会在后台线程上运行这些数据库查询。使用AsyncTask
代替:
static class Task extends AsyncTask<Void, Void, Void> {
adapter mAdapter;
Task(adapter adapter) {
mAdapter = adapter;
}
@Override
protected Void doInBackground(Void... params) {
// the code from the Runnable using the mAdapter instead of info.
return null;
}
在Activity
的{{1}}中你会使用类似的内容:
onCreate()