MSaudi
MSaudi

Reputation: 4652

HTTP Post request working on real device and not working on Android emulator

I'm making a post request to web server that has some php scripts to return some data.

When I run the code in my real phone, the code works well. When testing on the emulator, it does not work. It throws "NULL POINTER EXCEPTION". exception.getMessage() tells NULL

I also tried to access this server by requesting the url directly in emulator from the browser application and it worked. Sure i got the error that no post data sent as I'm not sending any post parameters but it was reachable. I got a certificate error at the beginning but it worked after I clicked ok.

I had the same problem when trying to connect to the local server (10.0.2.2) on my development machine. I thought the problem was in the configuration so I uploaded it to web server but still get the same problem:

public String postData(ArrayList<String> params) {

    String responseText=null;

    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(SERVERURL);
    Log.i(TAG, "Posting HttpPost .. . ");
    //goes well till this line

    try {
    // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);

        nameValuePairs.add(new BasicNameValuePair("long", params.get(0)));
        nameValuePairs.add(new BasicNameValuePair("lat", params.get(1)));


        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);

        Log.i(TAG, "Posting  httpclient.execute .. . ");

        responseText = convertStreamToString(response.getEntity().getContent());
        //responseText = EntityUtils.toString(response.getEntity());
        if (responseText !=null) {

            Log.i(TAG,"PRESPONSE TEXT:"+ responseText);
        }                       
        else
            Log.i(TAG," Entity RESPONSE is NULL");

    } catch (ClientProtocolException e) {

        Log.i(TAG, " POST ClientProtocolException " +e.getMessage());
    } catch (IOException e) {
        Log.i(TAG, " POST IOException " +e.getMessage());
    } catch (Exception el) {
        Log.i(TAG, " POST Exception " +el.getMessage());
    }

    return responseText;
} 

Upvotes: 1

Views: 3419

Answers (1)

MSaudi
MSaudi

Reputation: 4652

The problem was solved by making another emulator targeting another platform version. I was working on Android 4 with Google APIs. I made another emulator 2.3 API 10 with Google API.

Thanks for people suggestions here for trying another emulator or restarting it.

Upvotes: 2

Related Questions