OnPostExecute()函数未在AsyncTask中执行

时间:2014-04-18 21:33:41

标签: android android-asynctask

您好我正在开发一个在远程服务器上执行数据库查询的应用程序。到目前为止,我已经成功地与服务器端的PHP脚本进行了交互,我的代码正在发送字符串值而没有任何问题,但我不知道如何检查我是否收回了值i&i #39; m通过我的PHP脚本发回,因为我的OnPostExecute函数没有响应。 请帮助。

以下是遇到问题的代码:

public void submit_data(View V){
    try{
        new DoSocketProgramming().execute("10.0.2.2");
    }
    catch(Exception e){
        Toast.makeText(getApplicationContext(), "problem here", Toast.LENGTH_SHORT).show();
    }
    Toast.makeText(getApplicationContext(), "created till here", Toast.LENGTH_SHORT).show();
}

public class DoSocketProgramming extends AsyncTask<String, Void, String>
{
    String sendsentence=" this message is sent\n";
    String recvsentence=null;

    protected void onPreExecute()
    {
        Toast.makeText(getApplicationContext(), "this is preExecute", Toast.LENGTH_LONG).show();
    }
    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub

        try{            

            Socket con=new Socket(addr,1678);
            DataInputStream dis=new DataInputStream(con.getInputStream());
            DataOutputStream dos=new DataOutputStream(con.getOutputStream());

            dos.writeUTF(sendsentence);
            recvsentence=dis.readUTF();

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

        return recvsentence;
    }

    protected void onPostExecute(String result) {
        try{
        Toast.makeText(getApplicationContext(), "this is post execute"+ recvsentence, Toast.LENGTH_LONG).show();
        }catch(Exception e){
                e.printStackTrace();
        }
}       

}

1 个答案:

答案 0 :(得分:0)

实际上可能是。问题是您使用getApplicationContext()作为Context,这几乎总是错误的,除非您确切知道自己在做什么,否则不应该使用它。<\ n / p>

创建AsyncTask时,构造函数会收到调用它的Context Activity,您应该将此Context存储在AsyncTask类中,在onPostExecute()方法中使用它。

这是一个例子:

public class MyAsyncTask extends AsyncTask {
   Context context;

   private MyAsyncTask(Context context) { this.context = context; }

   @Override
   protected void onPostExecute(...) {
     super.onPostExecute(result);

     Toast.makeText(context, "this is post execute"+ recvsentence, Toast.LENGTH_LONG).show();
  }
}
相关问题