user1701467
user1701467

Reputation: 285

App doesn't retrieve JSON data from PHP webservice. Webservice works fine

My app doesn't seem to pull the JSON data from PHP webservice properly.

Visiting the webservice's function to get all data records from database produces JSON properly, but my app can't grab that data and seems to end up with NullPointerException.

LogCat issues me this:

Update:

Noticed this error in yellow that happens before the below errors:

W/System.err(835): org.apache.http.conn.HttpHostConnectException: Connection to http:// localhost refused

If I can't connect to the webservice on my localhost then I'm not getting the JSON to my app. But why would it refuse connection to localhost?

W/System.err(1159): at com.example.myfirstapp.MainActivity$LoadAllCars.doInBackground(MainActivity.java:113) W/System.err(1159): at com.example.myfirstapp.MainActivity$LoadAllCars.doInBackground(MainActivity.java:1) E/AndroidRuntime(1159): at com.example.myfirstapp.MainActivity$LoadAllCars.doInBackground(MainActivity.java:116) E/AndroidRuntime(1159): at com.example.myfirstapp.MainActivity$LoadAllCars.doInBackground(MainActivity.java:1) E/WindowManager(1159): at com.example.myfirstapp.MainActivity$LoadAllCars.onPreExecute(MainActivity.java:103)

Line 113: JSONObject json = jParser.makeHttpRequest(url_all_cars, "GET", params); Line 116: Log.d("All Cars: ", json.toString());

MainActivity

package com.example.myfirstproject;

//imports

public class MainActivity extends ListActivity implements OnItemClickListener {

    // Progress Dialog
    private ProgressDialog pDialog;

    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();

    ArrayList<HashMap<String, String>> carsList;

    // url to get all products list
    private static String url_all_cars = "http://localhost/webservice/get_all_cars.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_CARS = "cars";
    private static final String TAG_NAME = "name";

    // products JSONArray
    JSONArray cars = null;

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

        // Hashmap for ListView
        carsList = new ArrayList<HashMap<String, String>>();

        // Loading products in Background Thread
        new LoadAllcars().execute();

        // Get listview
        ListView lv = getListView();
    }

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

    /**
     * Background Async Task to Load all product by making HTTP Request
     * */
    class LoadAllcars extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Loading cars. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * getting All products from url
         * */
        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url_all_cars, "GET", params);

            // Check your log cat for JSON reponse
            Log.d("All cars: ", json.toString());

            try {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // products found
                    // Getting Array of Products
                    cars = json.getJSONArray(TAG_CARS);

                    // looping through All Products
                    for (int i = 0; i < cars.length(); i++) {
                        JSONObject c = cars.getJSONObject(i);

                        // Storing each json item in variable
                        String title = c.getString(TAG_NAME);

                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        map.put(TAG_NAME, name);

                        // adding HashList to ArrayList
                        carsList.add(map);
                    }
                } else {
                    // no products found
                    pDialog = new ProgressDialog(MainActivity.this);
                    pDialog.setMessage("No cars found");
                    pDialog.setIndeterminate(false);
                    pDialog.setCancelable(false);
                    pDialog.show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                    ListAdapter adapter = new SimpleAdapter(
                            MainActivity.this, carsList,
                            android.R.id.list, new String[] {TAG_NAME},
                            new int[] { R.id.title });
                    // updating listview
                    setListAdapter(adapter);
                }
            });

        }
    }
}

EDIT

JSONParser:

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    // function get json from url
    // by making HTTP POST or GET method
    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {

        // Making HTTP request
        try {

            // check for request method
            if(method == "POST"){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }else if(method == "GET"){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }           

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

Upvotes: 0

Views: 733

Answers (3)

user1791586
user1791586

Reputation:

Well if you are getting a null pointer exception on this line

JSONObject json = jParser.makeHttpRequest(url_all_cars, "GET", params);

then 1 or more of them things must be null. The jParser is instantiated, the url string is also, the params is as a list however there is nothing in the list. Have a look inside the jParser and see what is happening with that list of params. Do you need them? Does it need them?

EDIT

So the jParser is converting your list(which is empty) to a string with string builder. Which is returning an empty sting.

so your url when it is sent to your server looks like this

http://localhost/webservice/get_all_cars.php?

So the normal url but with a question mark on it. Is that correct?

It would make sense to log the statuscode and status reason from your httpresponse so you can see what the server is responsing you would do that like so...

Log.d("Class Name", "Status code: " + httpResponse.getStatusLine().getStatusCode() + " Status Phrase: " + httpResponse.getStatusLine().getReasonPhrase());

EDIT

The url is set to "localhost" so I presume it is looking within the device rather than at your server. Put in the ip of your server instead

Upvotes: 1

user1701467
user1701467

Reputation: 285

Problem was here:

private static String url_all_cars = "http://localhost/webservice/get_all_cars.php";

Can't use localhost because the emulated phone itself is localhost/127.0.0.1

You need to change localhost to 10.0.2.2:

private static String url_all_cars = "http://10.0.2.2/webservice/get_all_cars.php";

Upvotes: 0

James McCracken
James McCracken

Reputation: 15766

I think your problem may be that you never put anything in params. It's just an empty List.

Upvotes: 1

Related Questions