无法使用XAMPP将Android设备连接到数据库

时间:2014-01-16 18:56:12

标签: java php android xampp

我正在尝试使用XAMPP将Android设备连接到数据库

MySQL和Apache正常运行

这是 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);
    }

}

}

在这部分代码中:

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

jsonStr等于Null并且会发生NullPointerException;

我该怎么办?

提前致谢

这是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;

}
}

这也是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

1 个答案:

答案 0 :(得分:0)

我仔细检查了我的代码,结果发现上面的任何代码都没有错误。我的问题出在防火墙上。 以下是未来参考的步骤: (使用Windows 8)

  1. 按Windows键并在设置
  2. 中搜索“允许应用程序通过Windows防火墙”
  3. 点击“更改设置”&lt;&lt;这将允许您为特定应用程序配置防火墙
  4. 3.查找“Apache HTTP Server”并检查Private和Public并单击OK(我的Apache HTTP Server仅在Public中被允许,这就是我无法访问的原因) 导致ServiceHandler.java中的IOException和UpdateDatabase.java中的NullPointerException的[http://192.168.1.254/shopsmart.test.php]

    就是这样!