从内部类访问私有变量(AsyncTask)

时间:2015-08-08 20:50:55

标签: android android-asynctask inner-classes outer-classes

我有一个问题,我试图从doInBackground的{​​{1}}方法访问外部类的私有变量,这是一个内部类。这里有完整的代码。

AsyncTask

}

我尝试访问的变量是布尔变量public class MessageHandler { private Contact receiver; private String senderFacebookId; private String message; private final String TAG = "MessageHandler"; private Context context; boolean sentResult; public MessageHandler(Contact receiver, String senderFacebookId, String message, Context context) { this.receiver = receiver; this.senderFacebookId = senderFacebookId; this.message = message; this.context=context; this.sentResult = false; } public void send(){ Log.i(TAG, "Sending message to " + receiver.getName() + " receiver id: " + receiver.getFacebook_id() + " sender id: " + senderFacebookId + " message: " + message); new SenderAsync().execute(senderFacebookId,message, receiver.getFacebook_id()); if(this.sentResult==true){ Toast toast = Toast.makeText(this.context, "Message Sent", Toast.LENGTH_LONG); toast.show(); }else{ Toast toast = Toast.makeText(this.context, "ERROR: Message not Sent", Toast.LENGTH_LONG); toast.show(); } } private class SenderAsync extends AsyncTask<String,String,String> { @Override protected void onPreExecute(){ super.onPreExecute(); } @Override protected void onPostExecute(String s) { super.onPostExecute(s); } @Override protected String doInBackground(String... params) { HttpClient client = new DefaultHttpClient(); try { List<NameValuePair> parameter = new ArrayList<>(1); parameter.add(new BasicNameValuePair("regId", "empty")); parameter.add(new BasicNameValuePair("sender_id", params[0])); parameter.add(new BasicNameValuePair("receiver_facebook_id", params[2])); parameter.add(new BasicNameValuePair("message", params[1])); String paramString = URLEncodedUtils.format(parameter, "utf-8"); HttpGet get = new HttpGet(ProfileFragment.SERVER_URL_SEND_MESSAGE+"?"+paramString); Log.i(TAG, paramString); HttpResponse resp = client.execute(get); System.out.println("SREVER RESPONSE " + resp.getStatusLine().getStatusCode()); //THIS IS THE VARIABLE THAT I WANT TO ACCESS if(resp.getStatusLine().getStatusCode()==200){ MessageHandler.this.sentResult = true; } } catch (IOException e) { Log.i(TAG,"Error :" + e.getMessage()); } return null; } } 。我也打印出服务器的响应,它总是200.即使我删除了if条件并且我在任何情况下都将它设置为true,看起来这条代码行永远不会执行而且变量没有被访问,所以它总是错误的。

4 个答案:

答案 0 :(得分:2)

异步任务的全部意义在于它是异步的。如果执行任务,则不会在下一行代码中返回结果。为了评估结果,您应该使用onPostExecute回调方法。

@Override
protected void onPostExecute(String s) {
    if(sentResult==true){
        Toast toast = Toast.makeText(this.context, "Message Sent", Toast.LENGTH_LONG);
        toast.show();
    }else{
        Toast toast = Toast.makeText(this.context, "ERROR: Message not Sent", Toast.LENGTH_LONG);
        toast.show();
    }
}

此外,如果您要更改方法签名,您甚至不需要外部变量。

private class SenderAsync extends AsyncTask<String,String,Boolean> {
@Override
protected void onPostExecute(Boolean sent) {
    if(sent == true){
        Toast toast = Toast.makeText(this.context, "Message Sent", Toast.LENGTH_LONG);
        toast.show();
    }else{
        Toast toast = Toast.makeText(this.context, "ERROR: Message not Sent", Toast.LENGTH_LONG);
        toast.show();
    }
}

@Override
protected Boolean doInBackground(String... params) {
    try {
        ...
        if (resp.getStatusLine().getStatusCode() == 200) {
            return true;
        }
    }
    catch (IOException e) {

    }

    return false;
}

答案 1 :(得分:0)

为SenderAsync创建构造函数;

public SenderAsync(Context context,String senderId,String msg,Contact receiver)

这样称呼它;

new SenderAsync(senderFacebookId,message,receiver.getFacebook_id())。execute();

您需要在onPostExecute中获得结果。     void onPostExecute(String returnedValue)     {     //在这里运行你想要的if语句     }

答案 2 :(得分:0)

在您告诉AsyncTask执行其工作后,您正试图验证sentResult。 AsyncTask并行地在单独的线程上执行它必须执行的操作。所以在完成之前,sentResult不会改变。

我建议将Toast逻辑放在onPostExecute中。

答案 3 :(得分:0)

您正在使用AsyncTask错误。 AsyncTask应该在 onPostExecute()中返回结果,并且您的UI应该有一个单独的方法 onPostExecute()调用(因此是异步名称)。对于你想要完成的事情,你应该这样做:

public void send() {
    new SenderAsync().execute(senderFacebookId,message, receiver.getFacebook_id());
}

public void processResult(boolean result) {
  String resultMsg = result ? "Message Sent" : "ERROR: Message not Sent";
  Toast.makeText(this.context, resultMsg, Toast.LENGTH_LONG).show();
}

private class SenderAsync extends AsyncTask<String, String, Boolean> {
  ...
  @Override
    protected String doInBackground(String... params) {
      ...
      try {
        ...
        return (resp.getStatusLine().getStatusCode() == 200)
      }
      ...
      return false;
    }

    @Override
    protected void onPostExecute(Boolean result) {
        processResult(result);
    }
}