将字符串值分配给来自AsyncTask的onPostExecute方法的活动字符串变量不起作用

时间:2018-01-13 11:45:49

标签: java android string android-asynctask

我创建了一个似乎工作正常的REST API(我使用Postman测试了感兴趣的GET请求)。

我正在努力使用AsyncTask从Android应用程序发出相同的请求。希望将AsyncTask生成的字符串值分配给Android活动中的字符串变量。

我使用Toast来查看doInBackground方法的字符串输出,该方法被传递给AsyncTask的onPostExecute方法,以确保对API的调用正常并且工作正常。

当我将AsyncTask的字符串输出分配给Activity类中定义的字符串变量时,问题就出现了。执行AsyncTask之后,我使用Toast来查看字符串变量的值,它反映了在onPostExecute方法中执行的赋值。

我现在将分享我正在使用的代码,希望你能帮助我找到我可能出错的地方。单击按钮后,我打算执行验证AsyncTask并为emailValid分配值。

鉴于下面的代码,我可以用最直接的方式提出问题:“为什么吐司2显示而吐司1不是?”

提前感谢您的协助。

public class JoinActivity extends AppCompatActivity implements View.OnClickListener
{
    EditText email_et;
    Button join_b;

    String emailValid;

    @Override
    protected void onCreate(Bundle savedInstance)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_join);
        emailValid = "No";
        join_b = (Button) findViewById(R.id.aj_join_b);
        join_b.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) 
    {
        email_et = (EditText) findViewById(R.id.et_aj_email_address);
        new JoinActivity.validate().execute(email_et.getText().toString());
        // Toast 1 here:
        Toast.makeText(getApplicationContext(), emailValid, 
            Toast.LENGTH_LONG).show();
    }

    private class validate extends AsyncTask<String, Void, String> 
    {
        @Override
        protected String doInBackground(String... params) 
        {
            // ... GET request produces string with either yes or no i.e. outcome
            return outcome;
        }
        @Override
        protected void onPostExecute (String s) 
        {
            // Toast 2 here:
            Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
            emailValid = s;
            super.onPostExecute(s);
        }
    }
}

根据要求,下面粘贴了doInBackground方法的详细信息。该方法实际上返回了一些XML。我原来的问题是“一个字符串变量是”是“或”否“”是我尝试简化设置。正如我之前提到的,在onPostExecute中显示Toast中的字符串可正常显示从doInBackground发送的participantXML:

@Override
protected String doInBackground(String... params) {
    InputStream inputStream;
    String emailAddress = params[0];
    String outcome = null;
    HttpURLConnection httpURLConnection = null;
    BufferedReader bufferedReader = null;
    try
    {
        URL url = new URL("http://10.0.2.2:8080/project_name/webresources/entity.participant/email");
        httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setRequestMethod("GET");
        httpURLConnection.setRequestProperty("Accept", "application/xml");
        httpURLConnection.addRequestProperty("Email-address", emailAddress);
        httpURLConnection.connect();
        inputStream = httpURLConnection.getInputStream();
        StringBuffer stringBuffer = new StringBuffer();
        if (inputStream == null) {
            return null;
        }
        bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            stringBuffer.append(line + "\n");
        }
        if (stringBuffer.length() == 0) {
            return participantXML;
        }
        participantXML = stringBuffer.toString();
    } catch (ProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (httpURLConnection != null) {
            httpURLConnection.disconnect();
        }
        if (bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    validEmailAddress = participantXML;
    return participantXML;
}

1 个答案:

答案 0 :(得分:0)

user3691697对这个问题的回答:How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?完成了这个伎俩。我在执行任务时创建了任务对象(myTask),然后用它将结果分配给变量,如下所示:

AsyncTask myTask = new JoinActivity.validate.execute(email_et.getText()。toString());

emailValid = myTask.get()。toString();

Toast消息确认作业有效!感谢Pulak和LeoNeo的帮助。