Android - 将字符串传递给 Asynctask?

标签 android string android-asynctask parameter-passing

与我之前关于 ANR 问题 ( Android - Strings.xml versus text files. Which is faster? ) 的问题相关。

我尝试按照受访者的建议使用 AsyncTask,但我现在不知所措。

我需要将一个字符串从我的菜单 Activity 传递到一个 Asynctask,但这让我很困惑。我已经搜索和学习了 5 个小时,但仍然做不到。

这是我的代码 fragment :

@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()?

(非常感谢大家!我现在快要让这项工作正常进行了!)

最佳答案

这就是问题所在,它们在您声明它们的方法中是本地的,然后您声明了一个无法访问它们的 AsyncTask 类。如果 AsyncTask 是菜单 Activity 的内部类,那么您可以将它们声明为成员变量。

public class MenuActivity extends Activity
{
     String enhancedStem;
     ....

如果它是一个单独的类,那么您可以在您的 Async 类中创建一个构造函数并将变量传递给构造函数。

public class AsyncTaskRunner extends AsyncTask<String, String, String> {
  String curEnhancedStem;
  private ProgressDialog pdia;

  public void AsyncTaskRunner (String variableName)
{
     this.curEnhancedStem = variableName;
}

并称它为

 AsyncTaskRunner newTask = new AsyncTaskRunner(enhancedStem);
 newTask.execute();

此外,您不能在 doInBackground 中执行 UI 操作,因此需要在 Activity 类或您的其中一个类中进行更改Async 类中的其他方法,例如 onPostExecute()(如果它是内部类)。否则,您可以将一个值传回您的菜单 Activity 以更新您的 TextView

编辑

您仍在尝试使用此更改 doInBackground() 中的 UI

TextView databaseOutput1 = (TextView)findViewById(R.id.textView8);

然后当您调用 setText() 时再次调用。这需要放在您的 onPostExecute() 中,但随后您需要将您的 TextView 的引用传递给 AsyncTask。您可以从 onPostExecute() 返回要设置文本的 String 并将其设置在 Activity 中。希望这有帮助

关于Android - 将字符串传递给 Asynctask?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15144103/

相关文章:

android - ActionBar,来自 Android 2.3.3 Layout XML with Fragments

android - 如何在 seekBar 到达末尾时捕获事件

java - 我想在 XML 中的 CDATA 内发送 <br> 标记。哪个未在 XSD 内得到验证

android - 从textview中获取文本以在android中的字符串中显示

java - android 无法加载本地json数据

java - 如何检查首选项是否存在

java - 是否可以在 Android 中注册 java 安全提供程序?

java - StringBuilder中append的参数是一个新的String对象,会不会被垃圾回收?

android - 如何在recyclerview gridlayout中使用notifydatasetchanged

java - 更改异步任务中的接口(interface)(正确的方法)