我是Android新手,很难在没有UI冻结的情况下实现以下代码。我试图使用一个新的线程,但它在循环结束时没有给出反馈(至少我不知道如何获得它)。我的代码看起来像这样(摘录):
public class FilterSettingsActivity extends AppCompatActivity {
private String SMSMsgs = "";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_filter_settings);
listSMSs(false);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.action_preview:
listSMSs(true);
//execute after loop completetion
Intent i = new Intent(FilterSettingsActivity.this, PreviewSmsActivity.class);
i.putExtra("SMSMsgs",SMSMsgs);
startActivity(i);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void listSMSs(Boolean write){
Cursor cur = getContentResolver().query(uriSMS, null, getSelection(fromDate,toDate,thread_id),getArgs(fromDate,toDate,thread_id),"thread_id");
String sms = cur.getCount()+" SMS found";
if(write==true) {
// this code stucks UI
while (cur.moveToNext()) {
Long d = Long.parseLong(cur.getString(cur.getColumnIndex("date"))); //for retrieve readable date, time
String PhoneNumber = cur.getString(cur.getColumnIndex("address"));
SMSMsgs += "At :"+ millisToDate(d) +" From :" + getContactName(FilterSettingsActivity.this,PhoneNumber)+" "+ cur.getString(cur.getColumnIndex("address"))+" : " + "\n"
+ cur.getString(cur.getColumnIndex("body"))+"\n"+"\n";
}
}
final TextView textView = (TextView) findViewById(R.id.tvStatus);
textView.setText(sms);
}
}
任何人都可以帮助解决如何在Cursor查询上实现AsyncTask或新线程吗?谢谢。
编辑:这里的问题是游标必须位于asynctask类中,并且必须从外部函数和活动中接收多个参数(字符串,字符串数组)以完成其工作。代码示例中未提供这些函数和活动。如果字符串数组可以在doInBackground函数中作为参数传递,则引用的解决方案适用,否则此问题不重复。
答案 0 :(得分:0)
您可以使用CursorLoader
来实现此功能,负责异步加载数据
参考此https://developer.android.com/reference/android/content/CursorLoader.html
http://www.theappguruz.com/blog/use-android-cursorloader-example