【发布时间】:2013-02-15 03:35:33
【问题描述】:
与我之前关于 ANR 问题 (Android - Strings.xml versus text files. Which is faster?) 的问题有关。
我尝试按照受访者的建议使用 AsyncTask,但我现在不知所措。
我需要将一个字符串从我的菜单活动传递给 Asynctask,但这真的让我很困惑。我已经搜索和学习了 5 个小时,但仍然无法做到。
这是我的代码的 sn-p:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
/** Create an option menu from res/menu/items.xml */
getMenuInflater().inflate(R.menu.items, menu);
/** Get the action view of the menu item whose id is search */
View v = (View) menu.findItem(R.id.search).getActionView();
/** Get the edit text from the action view */
final EditText txtSearch = ( EditText ) v.findViewById(R.id.txt_search);
/** Setting an action listener */
txtSearch.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
final EditText txtSearch = ( EditText ) v.findViewById(R.id.txt_search);
String enhancedStem = txtSearch.getText().toString();
TextView databaseOutput = (TextView)findViewById(R.id.textView8);
new AsyncTaskRunner().execute();
// should I put "enhancedStem" inside execute?
}
});
return super.onCreateOptionsMenu(menu);
}
这是异步部分:已更新
public class AsyncTaskRunner extends AsyncTask<String, String, String> {
String curEnhancedStem;
private ProgressDialog pdia;
public AsyncTaskRunner (String enhancedStem)
{
this.curEnhancedStem = enhancedStem;
}
@Override
protected void onPreExecute() {
// Things to be done before execution of long running operation. For
// example showing ProgessDialog
super.onPreExecute();
pdia = ProgressDialog.show(secondactivity.this, "" , "Searching for words");
}
@Override
protected String doInBackground(String... params) {
if(curEnhancedStem.startsWith("a"))
{
String[] wordA = getResources().getStringArray(R.array.DictionaryA);
String delimiter = " - ";
String[] del;
TextView databaseOutput1 = (TextView)findViewById(R.id.textView8);
for (int wordActr = 0; wordActr <= wordA.length - 1; wordActr++)
{
String wordString = wordA[wordActr].toString();
del = wordString.split(delimiter);
if (curEnhancedStem.equals(del[0]))
{
databaseOutput1.setText(wordA[wordActr]);
pdia.dismiss();
break;
}
else
databaseOutput1.setText("Word not found!");
}
}
return null;
}
@Override
protected void onProgressUpdate(String... text) {
// Things to be done while execution of long running operation is in
// progress. For example updating ProgessDialog
}
@Override
protected void onPostExecute(String result) {
// execution of result of Long time consuming operation
}
}
现在可以检索了。我看到它显示正在寻找的单词,但它突然终止了。 也许是因为,就像你提到的那样,UI 的东西应该在执行后完成。 如果是这种情况,我应该在 doInBackground() 部分返回什么,然后传递 onPostExecute()?
(非常感谢大家!我现在已经接近正常工作了!)
【问题讨论】:
-
我根本不是想成为一个杀手,但这段代码确实离正常工作还差得远。从 doInBackground 方法内部对 textView 的引用将失败。除了从 UI 线程之外,您无法触摸 UI。我确定这不是您想听到的,但是,既然您对这些东西的工作原理有了更多了解,您可能想暂停一下,阅读 Android 架构,然后重新开始。
-
是的!我已经阅读并研究了一些关于 Asynctask 的内容,并且该问题已经得到解决。谢谢你的提醒! :)
标签: android string android-asynctask parameter-passing