我正在尝试从 SQL 数据库中读取数据。我认为我的代码是正确的,但有些我无法在文本框中显示。当我使用函数compareData()
时,应用程序才会关闭。
(我有不同的警报。我想阅读所有这些警告并显示他们的身份和姓名。)
这是我的代码:
public class RingAlarm extends Activity {
TextView texto;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.ring_alarm);
texto = (TextView) findViewById(R.id.textView1);
texto.setText(compareData());
}
public String compareData(){
String result = "";
String str1 = "";
String str2 = "";
String[] columns = new String[]{Database.COLUMN_ALARM_ID, Database.COLUMN_ALARM_NAME};
Cursor cursor = Database.getDatabase().query(Database.ALARM_TABLE, columns, null, null, null, null, null);
while(cursor.moveToNext()){
str1 = str1 + cursor.getString(0);
str2 = str2 + cursor.getString(1);
result = result + str1 + " - " + str2 + "\n";
}
cursor.close();
return result;
}
}
答案 0 :(得分:0)
您不应该在主UI线程上执行数据库I / O,因为这会导致应用程序挂起并崩溃。
使用AsyncTask是您正在做的最简单的解决方案。 AsyncTask允许您执行更长时间运行的任务,例如在后台查询数据库或网络I / O而不会中断UI。
以下代码将您的compareData()方法合并到AsyncTask的doInBackground()方法中。然后可以使用doInBackground()返回的结果在onPostExecute方法中设置TextView。所有计算都应该在doInBackground()中完成,UI对象应该在onPostExecute()中设置。要在onCreate()中执行此任务,您只需实例化该任务并调用.execute()。
public class RingAlarm extends Activity {
TextView texto;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.ring_alarm);
MyTask myTask = new MyTask();
myTask.execute();
}
private class MyTask extends AsyncTask<Void, Void, String> {
/**
* The system calls this to perform work in a worker thread and
* delivers it the parameters given to AsyncTask.execute()
*/
@Override
protected String doInBackground(Void... params) {
String result = "";
String str1 = "";
String str2 = "";
String[] columns = new String[]{Database.COLUMN_ALARM_ID, Database.COLUMN_ALARM_NAME};
Cursor cursor = Database.getDatabase().query(Database.ALARM_TABLE, columns, null, null, null, null, null);
while(cursor.moveToNext()){
str1 = str1 + cursor.getString(0);
str2 = str2 + cursor.getString(1);
result = result + str1 + " - " + str2 + "\n";
}
cursor.close();
return result;
}
/**
* The system calls this to perform work in the UI thread and delivers
* the result from doInBackground()
*/
@Override
protected void onPostExecute(String result) {
texto = (TextView) findViewById(R.id.textView1);
texto.setText(result);
}
}
}
此链接完整解释了AsyncTask的工作原理:http://developer.android.com/reference/android/os/AsyncTask.html
希望这有帮助!