I'm using this video to try and connect an android app to a locally hosted MySQL database. The php script doesn't seem to be the issue as it works fine locally (through internet explorer) and I keep on receiving a null pointer exception causing the app to crash.
The main activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.responseTextView = (TextView) this.findViewById(R.id.responseTextView);
new GetAllCustomerTask().execute(new ApiConnector());
}
public void setTextToTextView(JSONArray jsonArray)
{
String s = "";
for(int i=0; i<jsonArray.length();i++){
JSONObject json = null;
try {
json = jsonArray.getJSONObject(i);
s = s +
"Name : "+json.getString("name")+"
"+
"Owner : "+json.getInt("owner")+"
"+
"Species : "+json.getInt("species")+"
"+
"Sex : "+json.getInt("sex")+"
"+
"Birth : "+json.getInt("birth")+"
"+
"Death : "+json.getInt("death")+"
";
} catch (JSONException e) {
e.printStackTrace();
}
}
this.responseTextView.setText(s);
}
private class GetAllCustomerTask extends AsyncTask<ApiConnector,Long,JSONArray>
{
@Override
protected JSONArray doInBackground(ApiConnector... params) {
return params[0].GetAllCustomers();
}
@Override
protected void onPostExecute(JSONArray jsonArray) {
setTextToTextView(jsonArray);
}
}
ApiConnector class
String url = "http://localhost/getallcustomers.php";
HttpEntity httpEntity = null;
try
{
DefaultHttpClient httpClient = new DefaultHttpClient(); // Default HttpClient
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
httpEntity = httpResponse.getEntity();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
JSONArray jsonArray = null;
if (httpEntity != null) {
try {
String entityResponse = EntityUtils.toString(httpEntity);
Log.e("Entity Response : ", entityResponse);
jsonArray = new JSONArray(entityResponse);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return jsonArray;
}
I think the problem may be with the url, but as I said before it seems to be working fine through internet explorer.
Any help would be much appreciated.