Why am I getting, “incompatible types: Object cannot be converted to String” with this?

拈花ヽ惹草 提交于 2019-12-10 13:59:00

问题


I'm trying to use the simplest possible code for calling a Web API REST method from an Android app, and the code that I found here looked very promising:

public String callWebService(String requestUrl)
{
    String deviceId = "Android Device";

    HttpClient httpclient = new DefaultHttpClient();
    HttpGet request = new HttpGet(requestUrl);
    request.addHeader("deviceId", deviceId);

    ResponseHandler handler    = new BasicResponseHandler();
    String result = "";

    try
    {
        result = httpclient.execute(request, handler); // <= a line too far
    }
    catch (ClientProtocolException e)
    {
        e.printStackTrace();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }

    httpclient.getConnectionManager().shutdown();

    return result;
}

However, it won't compile, telling me: "incompatible types: Object cannot be converted to String" on this line:

result = httpclient.execute(request, handler);

It does give a couple of options in an attempt to circumvent the logjam:

...but I don't know which, if any, of these options is the preferred way to solve this dilemma. Is one way "the way"?

UPDATE

This code, as I said, looks promising to me, however I think it's basically unusable as is, because it gives me the dreaded "NetworkOnMainThreadException" From logcat:

04-01 13:18:41.861    1267-1267/hhs.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
. . .
    java.lang.IllegalStateException: Could not execute method of the activity
. . .
     Caused by: java.lang.reflect.InvocationTargetException
. . .
     Caused by: android.os.NetworkOnMainThreadException

回答1:


Because you are using a raw type in

ResponseHandler handler = ...

With raw types, the type variables in the method declarations are erased. So everything appears as Object (or whatever the leftmost bound of the type parameter is).

Instead, use a parameterized type

ResponseHandler<String> handler = ...

This also works because BasicResponseHandler extends ResponseHandler<String>.

Now

httpclient.execute(request, handler);

will have a return type associated with the type argument used when declaring handler, which is String and the result can therefore be assigned to a String variable (or anywhere a String is expected).




回答2:


Try this:

result = httpclient.execute(request, handler).toString();

If i'm not wrong, you should be able to use the "toString" method to convert the return of execute method to String type.



来源:https://stackoverflow.com/questions/22791834/why-am-i-getting-incompatible-types-object-cannot-be-converted-to-string-wit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!