I'm new. Both here at the forum and regarding programming in general. I'm currently experimenting with an android app. I've set up a localhost mysql database using WAMPserver and I want to query data from a table in it using a php script.
I picked a few things from a tutorial (http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/), but Android could not find the class JSONParser. According to this blog this is because it uses a deprecated method (DefaultHttpClient). The author of the blog above provides an alternative JSONParser class which uses HttpURLConnection instead, so I decided to create a class in my project named JSONParser & copy pasted the updated class there.
I use my class FetchCoordsIntentService that extends IntentService to fetch an address from the mysql table "customers" (using a php script) and then geocode it (and show it on a map on the ui thread). The geocoding bit works fine (I've tested it separately earlier), but now that I want to read the address from the database (instead of providing it directly) I get a NullPointerexception. I've provided the onHandleIntent() method (that I override in FetchCoordsIntentService) further below. This is where both the database query and the geocoding happends. I've commented where the NullPointerException appears.
My question: Why do this NullPointerException occur?
I will try to provide more information if that is required. Thank you for your time!
Here is the updated JSONParser class:
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
public class JSONParser {
String charset = "UTF-8";
HttpURLConnection conn;
DataOutputStream wr;
StringBuilder result;
URL urlObj;
JSONObject jObj = null;
StringBuilder sbParams;
String paramsString;
public JSONObject makeHttpRequest(String url, String method,
HashMap<String, String> params) {
sbParams = new StringBuilder();
int i = 0;
for (String key : params.keySet()) {
try {
if (i != 0){
sbParams.append("&");
}
sbParams.append(key).append("=")
.append(URLEncoder.encode(params.get(key), charset));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
i++;
}
if (method.equals("POST")) {
// request method is POST
try {
urlObj = new URL(url);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept-Charset", charset);
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.connect();
paramsString = sbParams.toString();
wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(paramsString);
wr.flush();
wr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
else if(method.equals("GET")){
// request method is GET
if (sbParams.length() != 0) {
url += "?" + sbParams.toString();
}
try {
urlObj = new URL(url);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(false);
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept-Charset", charset);
conn.setConnectTimeout(15000);
conn.connect();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
//Receive the response from the server
InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
Log.d("JSON Parser", "result: " + result.toString());
} catch (IOException e) {
e.printStackTrace();
}
conn.disconnect();
// try parse the string to a JSON object
try {
jObj = new JSONObject(result.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON Object
return jObj;
}
}
Here is my override of the onHandleIntent method in my FetchCoordsIntentService class:
@Override
protected void onHandleIntent(Intent intent) {
Log.i(TAG,"onHandleIntent started ");
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
mJSONParser=new JSONParser();
String company_name;
String address_street;
String address_city;
String address_country;
String objectAddress="";
String errorMessage = "";
List<Address> list=null;
int success=0;
mReceiver=intent.getParcelableExtra(Constants.RECEIVER);
if(geocoder.isPresent()){
try {
//----FETCH COMPANY DETAILS----
HashMap<String,String> params=new HashMap<>();
params.put(TAG_COMPANY_NAME,"Jannes Korv");
//NullPointerException here!
JSONObject json = mJSONParser.makeHttpRequest("http://localhost/test/read.php", "POST", params);
Log.d("Company loaded ", json.toString());
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.i(TAG,"Success! ");
JSONArray companyArray = json.getJSONArray(TAG_CUSTOMER_TABLE_NAME);
JSONObject companyObj = companyArray.getJSONObject(0);
company_name=companyObj.getString(TAG_COMPANY_NAME);
address_street=companyObj.getString(TAG_ADDRESS_STREET);
address_city=companyObj.getString(TAG_ADRESS_CITY);
address_country=companyObj.getString(TAG_ADRESS_COUNTRY);
objectAddress=address_street+", "+address_city+", "+address_country;
//----GEOCODE COMPANY ADDRESS TO COORDINATES----
list = geocoder.getFromLocationName(objectAddress, 1);
}
else{
Log.i(TAG,"Company not found!");
}
}
catch (JSONException e){
e.printStackTrace();
}
catch (IOException ioException) {
// Catch network or other I/O problems.
errorMessage = getString(R.string.service_not_available);
Log.e(TAG, errorMessage, ioException);
}
catch (IllegalArgumentException illegalArgumentException) {
// Catch invalid address values.
errorMessage = getString(R.string.invalid_address_used);
Log.e(TAG, errorMessage + ". " +
"Address = " + objectAddress, illegalArgumentException);
}
// Handle case where no address was found
if (list == null || list.size() == 0) {
if (errorMessage.isEmpty()) {
errorMessage = getString(R.string.no_address_found);
Log.e(TAG, errorMessage);
}
deliverResultToReceiver(Constants.FAILURE_RESULT, errorMessage,"");
} else {
Address address = list.get(0);
double lat = address.getLatitude();
double lng = address.getLongitude();
deliverResultToReceiver(Constants.SUCCESS_RESULT,String.valueOf(lat),String.valueOf(lng));
}
}
}
Here is my php script "read.php" that is supposed to fetch address data from the mysql table:
<?PHP
$user_name = "root";
$password = "";
$database = "test";
$server = "localhost";
// array for JSON response
$response = array();
$db_handle=mysqli_connect($server, $user_name, $password, $database);
if (mysqli_connect_errno($db_handle))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else{
// check for post data
if (isset($_POST['company_name'])) {
$company_name = $_POST['company_name'];
$SQL = "SELECT company_name,address_street,address_city,address_country FROM customers WHERE company_name=$company_name";
$result = mysqli_query($db_handle, $SQL);
if(!empty($result)){
if(mysqli_num_rows($result)>0){
$result = mysqli_fetch_array($result);
$customers = array();
$customers["company_name"] = $result["company_name"];
$customers["address_street"] = $result["address_street"];
$customers["address_city"] = $result["address_city"];
$customers["address_country"] = $result["address_country"];
$response["success"] = 1;
$response["customers"] = array();
array_push($response["customers"], $customers);
echo json_encode($response);
}
else{
$response["success"] = 0;
$response["message"] = "0 rows!";
echo json_encode($response);
}
}
else{
$response["success"] = 0;
$response["message"] = "No customers found!";
echo json_encode($response);
}
else{
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
echo json_encode($response);
}
}
mysqli_close($db_handle);
?>