0

I'm trying to connect an android device to a database using XAMPP

MySQL and Apache is working properly

This is UpdateDatabase.java

public class UpdateDatabase extends ListActivity {

private ProgressDialog pDialog;

//192.168.1.254 - IP of the server(laptop)
private static String url = "http://192.168.1.254:80/shopsmart/test.php";

//JSON Node Names
private static final String prod_list = "product";
private static final String prod_id = "ProductID";
private static final String prod_aisle = "Aisle";
private static final String prod_category = "Category";
private static final String prod_subcategory = "SubCategory";
private static final String prod_name = "ProductName";
private static final String prod_price = "Price";

// Product JSON Array
JSONArray products = null;

// Hashmap for ListView
ArrayList<HashMap<String, String>>productList;

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

    productList = new ArrayList<HashMap<String, String>>();

    ListView lv = getListView();

    // Calling async task to get json
    new GetDatabase().execute();
}

/**
 * Async task class to get json by making HTTP call
 * */
private class GetDatabase extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(UpdateDatabase.this);
        pDialog.setMessage("Loading...");
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        // Creating service handler class instance
        ServiceHandler sh = new ServiceHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

        Log.e("Response: ", "> " + jsonStr);

        //if (jsonStr != null){
            try{
                JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array node
                products = jsonObj.getJSONArray(prod_list);

                // Looping through all products
                for(int x =0; x<products.length();x++){
                    JSONObject p = products.getJSONObject(x);

                    String id = p.getString(prod_id);
                    String name = p.getString(prod_name);
                    String category = p.getString(prod_category);
                    String subcategory = p.getString(prod_subcategory);
                    String aisle = p.getString(prod_aisle);
                    String price = p.getString(prod_price);

                    // tmp hashmap for single product
                    HashMap<String,String> product = new HashMap<String,String>();

                    // adding each child node to HashMap key => value
                    product.put(prod_id, id);
                    product.put(prod_aisle, aisle);
                    product.put(prod_category, category);
                    product.put(prod_subcategory, subcategory);
                    product.put(prod_name, name);
                    product.put(prod_price, price);

                    // adding product to product list
                    productList.add(product);
                    Log.e("productList", "" + productList);
                }
            }
            catch(JSONException e){
                e.printStackTrace();
            }
        //}
        //else{
        //  Log.e("ServiceHandler","Couldn't get any data from the url");
        //}

        return null;
    }


    @Override
    protected void onPostExecute(Void result){
        super.onPostExecute(result);
        //Dismiss the progress dialog
        if(pDialog.isShowing())
            pDialog.dismiss();

        // updating parsed JSON data into Listview
        ListAdapter adapter = new SimpleAdapter(
            UpdateDatabase.this, productList,
            R.layout.update_database,new String[]{prod_name,prod_aisle,prod_category,prod_subcategory},
            new int[]{R.id.name,R.id.aisle,R.id.category,R.id.subcategory}
        );

        setListAdapter(adapter);
    }

}

}

In this portion of the code:

String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

jsonStr is equal to Null and a NullPointerException will occur;

What should I do?

Thanks in advance

This is the ServiceHandler.java

public class ServiceHandler {

static String response = null;
public final static int GET = 1;
public final static int POST = 2;

public ServiceHandler() {

}

/**
 * Making service call
 * @url - url to make request
 * @method - http request method
 * */
public String makeServiceCall(String url, int method) {
    return this.makeServiceCall(url, method, null);
}

/**
 * Making service call
 * @url - url to make request
 * @method - http request method
 * @params - http request params
 * */
public String makeServiceCall(String url, int method,
        List<NameValuePair> params) {
    try {
        // http client
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpEntity httpEntity = null;
        HttpResponse httpResponse = null;

        // Checking http request method type
        if (method == POST) {
            HttpPost httpPost = new HttpPost(url);
            // adding post params
            if (params != null) {
                httpPost.setEntity(new UrlEncodedFormEntity(params));
            }

            httpResponse = httpClient.execute(httpPost);

        } else if (method == GET) {
            // appending params to url
            if (params != null) {
                String paramString = URLEncodedUtils
                        .format(params, "utf-8");
                url += "?" + paramString;
            }
            HttpGet httpGet = new HttpGet(url);

            httpResponse = httpClient.execute(httpGet);

        }
        httpEntity = httpResponse.getEntity();
        response = EntityUtils.toString(httpEntity);

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

    return response;

}
}

This is also the Error Message in LogCat:

01-17 03:20:38.461: E/AndroidRuntime(21809): FATAL EXCEPTION: AsyncTask #1
01-17 03:20:38.461: E/AndroidRuntime(21809): java.lang.RuntimeException: An error occured while executing doInBackground()
01-17 03:20:38.461: E/AndroidRuntime(21809):    at android.os.AsyncTask$3.done(AsyncTask.java:299)
01-17 03:20:38.461: E/AndroidRuntime(21809):    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
01-17 03:20:38.461: E/AndroidRuntime(21809):    at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
01-17 03:20:38.461: E/AndroidRuntime(21809):    at java.util.concurrent.FutureTask.run(FutureTask.java:239)
01-17 03:20:38.461: E/AndroidRuntime(21809):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
01-17 03:20:38.461: E/AndroidRuntime(21809):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
01-17 03:20:38.461: E/AndroidRuntime(21809):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
01-17 03:20:38.461: E/AndroidRuntime(21809):    at java.lang.Thread.run(Thread.java:838)
01-17 03:20:38.461: E/AndroidRuntime(21809): Caused by: java.lang.NullPointerException
01-17 03:20:38.461: E/AndroidRuntime(21809):    at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
01-17 03:20:38.461: E/AndroidRuntime(21809):    at org.json.JSONTokener.nextValue(JSONTokener.java:94)
01-17 03:20:38.461: E/AndroidRuntime(21809):    at org.json.JSONObject.<init>(JSONObject.java:154)
01-17 03:20:38.461: E/AndroidRuntime(21809):    at org.json.JSONObject.<init>(JSONObject.java:171)
01-17 03:20:38.461: E/AndroidRuntime(21809):    at com.example.shopsmart.UpdateDatabase$GetDatabase.doInBackground(UpdateDatabase.java:88)
01-17 03:20:38.461: E/AndroidRuntime(21809):    at com.example.shopsmart.UpdateDatabase$GetDatabase.doInBackground(UpdateDatabase.java:1)
01-17 03:20:38.461: E/AndroidRuntime(21809):    at android.os.AsyncTask$2.call(AsyncTask.java:287)
01-17 03:20:38.461: E/AndroidRuntime(21809):    at java.util.concurrent.FutureTask.run(FutureTask.java:234)
01-17 03:20:38.461: E/AndroidRuntime(21809):    ... 4 more
7
  • Any errors? I would make sure 192.168.1.254:80/shopsmart/test.php is compatible with makeServiceCall. Try using a different, known good publically available url for makeServiceCall to rule out your url being the problem. Commented Jan 16, 2014 at 19:02
  • 192.168.254:80/shopsmart/test.php is working properly. I have edited my post to show the ServiceHandler.java where makeServiceCall is called upon Commented Jan 16, 2014 at 19:17
  • Are there any errors? Try debugging makeServiceCall and see if one of those exceptions are being thrown. If not, debug why response is being set to null. Commented Jan 16, 2014 at 19:23
  • perhaps search on this error. I see this, which would explain the problem, stackoverflow.com/questions/14180643/… Commented Jan 16, 2014 at 19:29
  • The IOException was thrown while doing this line of code httpResponse = httpClient.execute(httpGet); But I'm know how to solve this Commented Jan 16, 2014 at 20:18

1 Answer 1

0

I double checked my code and it turn out that there is no error in any of the code seen above. My problem was with the firewall. Here are the steps for future reference: (using Windows 8)

  1. Press Windows Key and search for "Allow app through Windows Firewall " in settings
  2. Click "Change settings" << this will allow you to configure the firewall for the specific app

3.Look for "Apache HTTP Server" and check both Private and Public and Click OK(My Apache HTTP Server was allowed only in Public that's why I cannot access the
[http://192.168.1.254/shopsmart.test.php] that caused the IOException in the ServiceHandler.java and NullPointerException in UpdateDatabase.java)

That's that!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.