0

I have Restful Web Service implemented by Jersey. I connect from Android via HTTP client to fetch the data. It works fine in API level 10 and older versions but not on API level 11 or greater. I appreciate for any help. I have a nullPointerException in these versions.

public String getBaseURI(String str) {
        String result = "";
        try {
            HttpParams httpParameters = new BasicHttpParams();
            int timeoutConnection = 3000;
            HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
            int timeoutSocket = 5000;
            HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
            DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
            HttpGet getRequest = new HttpGet(ServerAddress + str);
            getRequest.addHeader("accept", "application/json");
            HttpResponse response = httpClient.execute(getRequest);
            result = getResult(response).toString();
            httpClient.getConnectionManager().shutdown();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } 
        return result;
    }

private StringBuilder getResult(HttpResponse response) throws IllegalStateException, IOException {
        if (response.getStatusLine().getStatusCode() != 201) 
            throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        StringBuilder result = new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())), 1024);
        String output;
        while ((output = br.readLine()) != null) 
            result.append(output);
        return result;      
    }

Tag : AndroidRuntime

The logcat exception:

Exception: FATAL EXCEPTION: main
java.lang.NullPointerException
at com.android.internal.os.LoggingPrintStream.Prrintln(LogiingPrintStream.java.298)
at Client.getBaseURI (Client.java:66)

when I call a rest service such as: String str = client.getBaseURI("task/project/get/" + user);
I get the Error.

private void listViewSet() {

        ListView lv = (ListView) this.findViewById(R.id.listView);
        lv.setAdapter(new MultiAdapter(this));

        lv.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {

                switch (pos) {
            case ADD:
            String str = client.getBaseURI("task/project/get/" + user);// Json format
                        ......
                }
            }
        });
    }
Ali
  • 9,800
  • 19
  • 72
  • 152
  • If you add the NullpointerException information to your question it's easier to help out. The exception should tell which line that caused it. – johlo Jun 05 '12 at 20:29
  • 1
    Please ***make it clear*** where the `NullPointerException` occurs in your code. We have no idea which line is "line 66" and you haven't mentioned a `Client.java` class anywhere in your post. – Alex Lockwood Jun 05 '12 at 20:49

1 Answers1

0

Are you performing the HTTP request on a separate thread (using an AsyncTask, for example)?

Some of the newer APIs (especially ICS, in my experience) forcefully require you to perform network connections on a separate thread so as to not block the UI thread. Network connections can be potentially long and expensive, so you never want to perform them on the UI thread. Doing so might prevent the UI from being drawn to the screen, cause your application to force close, make your application appear laggy to the user, etc.

Alex Lockwood
  • 83,063
  • 39
  • 206
  • 250
  • No not AsyncTask, I call it when user click on a list view as I added to end of the code. – Ali Jun 05 '12 at 21:01
  • 2
    You **need** to implement your network connection on a separate thread if you want your app to work reliably on all devices. This isn't something to complain about, as you really should do this anyway. Not doing so will get you negative reviews on the market... :P. For more information on how to avoid blocking the UI thread, read this [article](http://developer.android.com/resources/articles/painless-threading.html). – Alex Lockwood Jun 05 '12 at 21:04
  • Thank, you are completely right, If I call the method in the Thread, it works fine. – Ali Jun 05 '12 at 21:26
  • The lesson here is to **never block the UI thread**. Blocking the UI thread is bad!! :) – Alex Lockwood Jun 05 '12 at 21:27
  • I'd also like to point out that wrapping your code in an `AsyncTask` might be easier than using a Thread... `AsyncTask` was designed as a way to abstract the use of `Thread`s out all together. Just a suggestion; you could do it either way. – Alex Lockwood Jun 05 '12 at 21:29