【问题标题】:How do you return a variable from AsyncTask to OnCreate() in Activity如何在 Activity 中将变量从 AsyncTask 返回到 OnCreate()
【发布时间】:2015-10-21 01:37:16
【问题描述】:

问题/错误:

我正在努力将一个变量从 doInBackground 方法传递到我的 OnCreate()。老实说,我不敢相信我有这么多问题。

目标:

将一个字符串从 doInBackground 中的 AsyncTask 方法传递给 OnCreate,我想将一个字符串传递给一个 Textview。并用字符串 setTextView。

我的理解:

我已经厌倦了在 doInBackground 和 AsyncTask 方法中创建简单的方法并在我的 onCreate() 中调用它。但是,变量始终为空。我相信我错过了理解 onCreate() 的一个方面。

主要活动:-我想在 textView 中设置变量“ValueNeeded”

public class OutboxActivity extends ListActivity {
…. 
…

public void onCreate(Bundle savedInstanceState) {  
….

//AsyncTask method 
new LoadOutbox().execute();

    textView = (TextView) findViewById(R.id.textView6);
    textView.setText("ValueNeeded);

    Log.d("response", "TOUR NAME: " + ValueNeeded) );

  …….

AsyncTask - 包含 doInBackground

 class LoadOutbox extends AsyncTask<String, String, String> 
   {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        ….
    }

doInBackground - String ValueNeeded 是我需要传递给 onCreate() 的变量

   protected String doInBackground(String... args) 
    {
  ..CODE THAT GETS VALUE IS IN HERE...

   //ValueNeeded Is
    ValueNeeded = c.getString(TAG_TOUR);


        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

【问题讨论】:

  • 从 doInBackground 返回字符串并将其设置在 onPostExecute() 中。 onPostExecute() 是你绑定结果的地方。

标签: java android variables methods android-asynctask


【解决方案1】:

您必须在onPostExecute 中进行,而不是在doInBackground 中进行。只需输入onPostExecutetextView.setText("ValueNeeded);

您的问题不是“理解 onCreate() 的一个方面”而是“理解 AsyncTask 的一个方面”

【讨论】:

    【解决方案2】:

    您的 onCreate 需要快速。 AsyncTask 的重点是在另一个线程中做一些事情,以便 onCreate 可以运行。

    实现 onPostExecute(...) 并填写结果。您的 onCreate 可能需要某种“正在加载...”消息来向用户表明您正在获取数据。

    【讨论】:

      【解决方案3】:
      protected String doInBackground(String... args) {
         ..CODE THAT GETS VALUE IS IN HERE...
         //ValueNeeded Is
         ValueNeeded = c.getString(TAG_TOUR);
         // return your value needed here
         return ValueNeeded;
      }
      
      protected void onPostExecute(String result) {
         super.onPostExecute(result);
         // this result parameter has the value what you return in doInBackground
         // now it has valueNeeded
      
         // set that value to your textview
         textView.setText("ValueNeeded);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-22
        • 2019-02-06
        • 1970-01-01
        • 1970-01-01
        • 2015-07-23
        • 2013-06-30
        相关资源
        最近更新 更多