duanhe6718 2016-06-25 08:54
浏览 58
已采纳

too long

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);   

    ?>
  • 写回答

1条回答 默认 最新

  • dpiw16824 2016-06-27 16:26
    关注

    Sorry, solved it later but forgot to update here. The main issue was that I tested the app on my mobile and thus could not connect to localhost on my computer. This feels really stupid and obvious in hindsight!

    Anyway, I solved it by downloading ngrok at https://ngrok.com/. This cute program allowed me to open up a temporary tunnel to my localhost via a generated link. The fact that it also allowed me to monitor the JSON response helped a lot later on as well.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 Macbookpro 连接热点正常上网,连接不了Wi-Fi。
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题