使用异步Http客户端获得响应

时间:2013-02-06 15:07:28

标签: java android android-asynctask

早上好。 我想在TextView中发送get请求和显示响应。

public class MyHttpClient {

private static final String BASE_URL = "http://pgu.com";

private static AsyncHttpClient client = new AsyncHttpClient();

 public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.get(getAbsoluteUrl(url), params, responseHandler);
 }   
 private static String getAbsoluteUrl(String relativeUrl) {
      return BASE_URL + relativeUrl;
  }}

我正在打电话给这堂课

public class MyHttpClientUsage {

Handler h;

public MyHttpClientUsage(Handler h){
    this.h = h;
}

public void getInfoAbout() throws HttpException{

    RequestParams params = new RequestParams();
    params.put("a", "Static");
    params.put("content", "47");

    MyHttpClient.get("", params, new AsyncHttpResponseHandler(){
         @Override
            public void onSuccess(String response) {
                  System.out.println(response);
                              //Simplify sending int to TextView
                  MyHttpClientUsage.this.h.sendEmptyMessage(678); 
                         }
    });
}}

在活动中,我有一个Handler来获取消息并设置TextView

public class MainActivity extends Activity {

Handler h;
TextView largeText;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    largeText = (TextView) findViewById(R.id.textView1);

    h = new Handler(){

        public void handleMessage(android.os.Message msg){
            largeText.setText(msg.what);
        }

    };

    MyHttpClientUsage connect = new MyHttpClientUsage(h);
    try {
        connect.getInfoAbout();
    } catch (HttpException e) {
        e.printStackTrace();
    }

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}}

在LogCat中我有这个警告

02-06 14:30:51.783: W/dalvikvm(546): threadid=1: thread exiting with uncaught exception (group=0x409961f8)

和错误

02-06 14:30:51.833: E/AndroidRuntime(546): android.content.res.Resources$NotFoundException:   String resource ID #0x2a6

1 个答案:

答案 0 :(得分:1)

正如您在此处所看到的那样Message. what是一个int.you将setText方法传递给TextView,其中CharSequence为参数。将您的代码更改为:

largeText.setText(String.valueOf(msg.what));

largeText.setText(msg.what.toString());