第json.getInt行的空指针异常("成功")

时间:2016-04-19 17:53:46

标签: php android json

我是android编程的新手,目前开发的应用程序需要android和mysql数据库之间的连接。我已经完成了php和android中的连接部分但是在获得成功标记时它有nullpointer错误。我不知道是什么错,但我确实认为这是因为联系失败......请帮助

get_bus_data.php:

<?php

$response = array();

require_once __DIR__ . '/db_connect.php';

$db = new DB_CONNECT();

if (isset($_POST["busid"])) {

$busid = $_POST['busid'];

$result = mysql_query("SELECT * FROM busstop1 WHERE busid = $busid");

if (!empty($result)) {
    // check for empty result
    if (mysql_num_rows($result) > 0) {

        $result = mysql_fetch_array($result);

        $bus = array();
        $bus["Bus"] = $result["busid"];
        $bus["Time"] = $result["TimeSchedule"];

        // success
        $response["success"] = 1;

        // user node
        $response["Schedule"] = array();

        array_push($response["Schedule"], $bus);

        // echoing JSON response
        echo json_encode($response);
    } else {

        $response["success"] = 0;
        $response["message"] = "No schedule found";

        // echo no users JSON
        echo json_encode($response);
    }
} else {

    $response["success"] = 0;
    $response["message"] = "No schedule found";

    // echo no users JSON
    echo json_encode($response);
}else {

// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";

// echoing JSON response
echo json_encode($response);}
?>

db_connect.php

<?php

class DB_CONNECT {

// constructor
function __construct() {
    // connecting to database
    $this->connect();
}

// destructor
function __destruct() {
    // closing db connection
    $this->close();
}

function connect() {
    // import database connection variables
    require_once __DIR__ . '/db_config.php';

    // Connecting to mysql database
    $con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or  die(mysql_error());

    // Selecing database
    $db = mysql_select_db(DB_DATABASE) or die(mysql_error()) or    die(mysql_error());

    // returing connection cursor
    return $con;
}

function close() {
    // closing db connection
    mysql_close();
}

}

?>

httpUrlConnectionParser.java

public class HttpUrlConnectionParser {
public static JSONObject jObj = null;
public static InputStream is=null;
public static String json = "";
public static HttpURLConnection urlConnection;

public HttpUrlConnectionParser(){
}

public static JSONObject makehttpUrlConnection(String url_path,HashMap<String,String> data) {
    try {
        URL url = new URL(url_path);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setReadTimeout(10000);
        urlConnection.setConnectTimeout(15000);
        urlConnection.setRequestMethod("POST");
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);

        OutputStream os = urlConnection.getOutputStream();

        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        writer.write(getQueryData(data));
        writer.flush();
        writer.close();

        urlConnection.connect();
        is = urlConnection.getInputStream();

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"),8);
            StringBuilder sb = new StringBuilder();
            String line = null;


            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }

            json = sb.toString();
            is.close();

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


    try{
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return jObj;
}

public static String getQueryData(HashMap<String,String>data) throws UnsupportedEncodingException{
    StringBuilder result =  new StringBuilder();
    boolean first = true;

    for(Map.Entry<String,String> entry:data.entrySet()){
        if(first)
            first = false;
        else
            result.append("&");
        result.append(URLEncoder.encode(entry.getKey(),"UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(entry.getValue(),"UTF-8"));

    }

    return result.toString();
}

}

testactivity.java

public class testactivity extends Activity {

private TextView test2;
Button test;
private HashMap<String,String> data;
private String url = "http://192.168.1.13/android_connect/get_bus_data.php";
private ProgressDialog pDialog;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_testactivity);
    test2 = (TextView)findViewById(R.id.test2);
    test = (Button)findViewById(R.id.btn_get);
    test.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new GetBookDataTask().execute();

        }
    });

}

private class GetBookDataTask extends AsyncTask<String, String, String>
{

    protected void onPreExecute()
    {

        super.onPreExecute();
        pDialog = new ProgressDialog(testactivity.this);
        pDialog.setMessage("Loading products. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();

    }


    protected String doInBackground(String... params) {
        data = new HashMap<>();
        data.put("busid", "101");

        try {

            JSONObject json = HttpUrlConnectionParser.makehttpUrlConnection(url, data);
            int succ = json.getInt("success");

            if (succ == 0) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();
                    }
                });
            } else {
                JSONArray jsonArray=json.getJSONArray("Schedule");
                JSONObject child=jsonArray.getJSONObject(0);
                final String ans=child.optString("Time");

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        test2.setText(ans.toString());
                    }
                });
            }

        } catch (JSONException e) {
        }

        return null;
    }

    protected void onPostExecute(String result){
        super.onPostExecute(result);
        pDialog.dismiss();
        }
    }
}

php的输出应该是这样的:

{"success":1,"Schedule":[{"Bus":"101","Time":"10:30"}]}

0 个答案:

没有答案