onPostExecute未执行

时间:2015-07-17 09:24:31

标签: android android-asynctask

我的应用中有一个AsyncTask类连接到外部数据库。任务完成(成功)后,我想开始一项新活动。

MainActivity

public class MainActivity extends Activity implements OnClickListener, PostKey.AsyncResponse {
    PostKey asyncTask = new PostKey();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        asyncTask.delegate = this;
    }

    public void processFinish(String output){
        //this you will received result fired from async class of onPostExecute(result) method.
       String string;
       string = "test";
       Log.d(string, " processFinish");
    }

    public void onClick(View v) {
        keyValue = key.getText().toString(); // Is declared at the top didn't include it in this snippet
        String pattern = "^[a-zA-Z0-9]*$";

        if(keyValue.length() < 5){
            new PostKey().execute(keyValue);
        }
    }
}

PostKey

public class PostKey extends AsyncTask<String, Integer, Double> {
    public AsyncResponse delegate = null;

    @Override
    protected Double doInBackground(String... params) {
        postData(params[0]);
        return null;
    }

    //@Override can't add override, it doesn't override method from its superclass
    protected void onPostExecute(String result){
        delegate.processFinish(result);
    }

    public void postData(String valueIWantToSend) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost     = new HttpPost("http:/www.domain.com/post.php");

        try {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("x", "test"));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            HttpResponse response = httpclient.execute(httppost);
            String responseStr = EntityUtils.toString(response.getEntity());

            Log.d(responseStr, ""); // This gets logged

            if(responseStr == "true"){
                delegate.processFinish(responseStr); // This doesn't execute the processFinish in mainActivity either
            }
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }
    }

    public interface AsyncResponse {
        void processFinish(String output);
    }
}

1 个答案:

答案 0 :(得分:1)

//@Override can't add override, it doesn't override method from its superclass
protected void onPostExecute(String result)

将错误视为提示:您的方法签名错误。它应该是

@Override
protected void onPostExecute(Double result)

或者由于您并未真正返回任何Double,只需更改extends AsyncTask<String, Integer, Double>中的结果类型声明。