为什么jsonObject为null?

时间:2018-05-25 10:19:32

标签: php android sql xampp

目前我正在尝试使用Android App访问本地XAMPP服务器上的远程数据库。 该应用程序工作,实际上它从正确的活动开始。但是当我尝试访问数据库时,它会崩溃。在日志中说,在第67行(即在这里:

 JSONObject jsonObject = httpJsonParser.makeHttpRequest(
            BASE_URL + "fetch_all_movies.php", "GET", null);
    try {
        int success = jsonObject.getInt(KEY_SUCCESS);) 

jsonObject = null。 所以我的问题是,这是什么原因?

以下是Parser的系数:

enter code here

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.net.Uri;
import android.util.Log;

public class HttpJsonParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
HttpURLConnection urlConnection = null;

// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
                                  Map<String, String> params) {

    try {
        Uri.Builder builder = new Uri.Builder();
        URL urlObj;
        String encodedParams = "";
        if (params != null) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                builder.appendQueryParameter(entry.getKey(),     entry.getValue());
            }
        }
        if (builder.build().getEncodedQuery() != null) {
            encodedParams =  builder.build().getEncodedQuery();

        }
        if ("GET".equals(method)) {
            url = url + "?" + encodedParams;
            urlObj = new URL(url);
            urlConnection = (HttpURLConnection) urlObj.openConnection();
            urlConnection.setRequestMethod(method);


        } else {
            urlObj = new URL(url);
            urlConnection = (HttpURLConnection) urlObj.openConnection();
            urlConnection.setRequestMethod(method);
            urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            urlConnection.setRequestProperty("Content-Length", String.valueOf(encodedParams.getBytes().length));
            urlConnection.getOutputStream().write(encodedParams.getBytes());
        }


        urlConnection.connect();
        is = urlConnection.getInputStream();
        BufferedReader reader = new BufferedReader(new     InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
        jObj = new JSONObject(json);


    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    } catch (Exception e) {
        Log.e("Exception", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}

}

以下是列表类的代码:

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.example.lukas.remotemysqlconnection.helper.CheckNetworkStatus;
import com.example.lukas.remotemysqlconnection.helper.HttpJsonParser;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

public class MovieListingActivity extends AppCompatActivity {
private static final String KEY_SUCCESS = "success";
private static final String KEY_DATA = "data";
private static final String KEY_MOVIE_ID = "movie_id";
private static final String KEY_MOVIE_NAME = "movie_name";
private static final String BASE_URL = "http://192.168.0.169/movies/";
private ArrayList<HashMap<String, String>> movieList;
private ListView movieListView;
private ProgressDialog pDialog;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_movie_listing);
    movieListView = (ListView) findViewById(R.id.movieList);
    new FetchMoviesAsyncTask().execute();

}

/**
 * Fetches the list of movies from the server
 */
private class FetchMoviesAsyncTask extends AsyncTask<String, String, String> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        //Display progress bar
        pDialog = new ProgressDialog(MovieListingActivity.this);
        pDialog.setMessage("Loading movies. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    @Override
    protected String doInBackground(String... params) {
        HttpJsonParser httpJsonParser = new HttpJsonParser();
        JSONObject jsonObject = httpJsonParser.makeHttpRequest(
                BASE_URL + "fetch_all_movies.php", "GET", null);
        try {
            int success = jsonObject.getInt(KEY_SUCCESS);
            JSONArray movies;
            if (success == 1) {
                movieList = new ArrayList<>();
                movies = jsonObject.getJSONArray(KEY_DATA);
                //Iterate through the response and populate movies list
                for (int i = 0; i < movies.length(); i++) {
                    JSONObject movie = movies.getJSONObject(i);
                    Integer movieId = movie.getInt(KEY_MOVIE_ID);
                    String movieName = movie.getString(KEY_MOVIE_NAME);
                    HashMap<String, String> map = new HashMap<String, String>();
                    map.put(KEY_MOVIE_ID, movieId.toString());
                    map.put(KEY_MOVIE_NAME, movieName);
                    movieList.add(map);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();

}

所有php文件都位于xamm / htdocs / movies /...下的指定文件夹中。

这是php的db_connect:

  <?php
  define('DB_USER', "root"); // db user
  define('DB_PASSWORD', ""); // db password (mention your db password here)
  define('DB_DATABASE', "androiddeft"); // database name
  define('DB_SERVER', "localhost"); // db server

  $con = mysqli_connect(DB_SERVER,DB_USER,DB_PASSWORD,DB_DATABASE);

  // Check connection
  if(mysqli_connect_errno()){
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
  ?>

最后但并非最不重要的,这是php文件:

 <?php
 include 'db/db_connect.php';
 //Query to select movie id and movie name
 $query = "SELECT movie_id, movie_name FROM movies";
 $result = array();
 $movieArray = array();
 $response = array();
 //Prepare the query
 if($stmt = $con->prepare($query)){
$stmt->execute();
//Bind the fetched data to $movieId and $movieName
$stmt->bind_result($movieId,$movieName);
//Fetch 1 row at a time                 
while($stmt->fetch()){
    //Populate the movie array
    $movieArray["movie_id"] = $movieId;
    $movieArray["movie_name"] = $movieName;
    $result[]=$movieArray;

}
$stmt->close();
$response["success"] = 1;
$response["data"] = $result;


 }else{
//Some error while fetching data
$response["success"] = 0;
$response["message"] = mysqli_error($con);


 }
 //Display JSON response
 echo json_encode($response);

 ?>

2 个答案:

答案 0 :(得分:1)

首先,在https://jsoneditoronline.org/

上打印并验证JSON响应格式

然后检查您获取的JSON对象是否存在使用 jsonobject.has(“key”)方法。

答案 1 :(得分:0)

您没有发送JSON。如果你看,你会发现内容类型是application/html

通过设置Content_Type标题:

来解决此问题
header('Content-Type: application/json');
echo json_encode($response);

这可能不是你的实际错误,但你应该这样做以消除它作为一种可能性,因为这是提供JSON的正确方法。