Php 为什么jsonObject为空?

Php 为什么jsonObject为空?,php,android,sql,xampp,Php,Android,Sql,Xampp,现在我正在尝试使用Android应用程序访问本地XAMPP服务器上的远程数据库。 这个应用程序可以工作,事实上它是从正确的活动开始的。但当我试图访问数据库时,它崩溃了。日志中说,在第67行(即: JSONObject jsonObject = httpJsonParser.makeHttpRequest( BASE_URL + "fetch_all_movies.php", "GET", null); try { int success = js

现在我正在尝试使用Android应用程序访问本地XAMPP服务器上的远程数据库。 这个应用程序可以工作,事实上它是从正确的活动开始的。但当我试图访问数据库时,它崩溃了。日志中说,在第67行(即:

 JSONObject jsonObject = httpJsonParser.makeHttpRequest(
            BASE_URL + "fetch_all_movies.php", "GET", null);
    try {
        int success = jsonObject.getInt(KEY_SUCCESS);) 
jsonObject=null。 所以我的问题是,这是什么原因

以下是解析器的coe:

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;

}
在此处输入代码
导入java.io.BufferedReader;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.InputStreamReader;
导入java.io.UnsupportedEncodingException;
导入java.net.HttpURLConnection;
导入java.net.ProtocolException;
导入java.net.URL;
导入java.util.Map;
导入org.json.JSONException;
导入org.json.JSONObject;
导入android.net.Uri;
导入android.util.Log;
公共类HttpJsonParser{
静态InputStream为空;
静态JSONObject jObj=null;
静态字符串json=“”;
HttpURLConnection-urlConnection=null;
//函数从url获取json
//通过使用HTTP POST或GET方法
公共JSONObject makeHttpRequest(字符串url、字符串方法、,
映射参数){
试一试{
Uri.Builder=新的Uri.Builder();
URL-urlObj;
字符串encodedParams=“”;
如果(参数!=null){
对于(Map.Entry:params.entrySet()){
builder.appendQueryParameter(entry.getKey(),entry.getValue());
}
}
if(builder.build().getEncodedQuery()!=null){
encodedParams=builder.build().getEncodedQuery();
}
if(“GET”.equals(方法)){
url=url+“?”+编码参数;
urlObj=新URL(URL);
urlConnection=(HttpURLConnection)urlObj.openConnection();
urlConnection.setRequestMethod(方法);
}否则{
urlObj=新URL(URL);
urlConnection=(HttpURLConnection)urlObj.openConnection();
urlConnection.setRequestMethod(方法);
setRequestProperty(“内容类型”,“应用程序/x-www-form-urlencoded”);
urlConnection.setRequestProperty(“内容长度”,String.valueOf(encodedParams.getBytes().Length));
urlConnection.getOutputStream().write(encodedParams.getBytes());
}
urlConnection.connect();
is=urlConnection.getInputStream();
BufferedReader reader=新的BufferedReader(新的InputStreamReader(is));
StringBuilder sb=新的StringBuilder();
弦线;
而((line=reader.readLine())!=null){
sb.追加(第+行“\n”);
}
is.close();
json=sb.toString();
jObj=新的JSONObject(json);
}捕获(不支持的编码异常e){
e、 printStackTrace();
}捕获(协议例外e){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}捕获(JSONException e){
Log.e(“JSON解析器”,“错误解析数据”+e.toString());
}捕获(例外e){
Log.e(“异常”,“错误解析数据”+e.toString());
}
//返回JSON字符串
返回jObj;
}
}

下面是Listing类的代码:

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();
导入android.app.ProgressDialog;
导入android.content.Intent;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.support.v7.app.AppActivity;
导入android.view.view;
导入android.widget.AdapterView;
导入android.widget.ListAdapter;
导入android.widget.ListView;
导入android.widget.simpledapter;
导入android.widget.TextView;
导入android.widget.Toast;
导入com.example.lukas.remotemysqlconnection.helper.CheckNetworkStatus;
导入com.example.lukas.remotemysqlconnection.helper.HttpJsonParser;
导入org.json.JSONArray;
导入org.json.JSONException;
导入org.json.JSONObject;
导入java.util.ArrayList;
导入java.util.HashMap;
公共类MovieListingActivity扩展了AppCompatingActivity{
私有静态最终字符串密钥\u SUCCESS=“SUCCESS”;
私有静态最终字符串键\u DATA=“DATA”;
私有静态最终字符串密钥\u MOVIE\u ID=“MOVIE\u ID”;
私有静态最终字符串键\u MOVIE\u NAME=“MOVIE\u NAME”;
私有静态最终字符串BASE_URL=”http://192.168.0.169/movies/";
私人电影导演;
私有ListView-movieListView;
私人对话;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u movie\u列表);
movieListView=(ListView)findViewById(R.id.movieList);
新建FetchMoviesAsyncTask().execute();
}
/**
*从服务器获取电影列表
*/
私有类FetchMoviesAsyncTask扩展了AsyncTask{
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
//显示进度条
pDialog=新建进度对话框(MovieListingActivity.this);
pDialog.setMessage(“正在加载电影,请稍候…”);
pDialog.setUndeterminate(假);
pDialog.setCancelable(假);
pDialog.show();
}
@凌驾
受保护的字符串doInBackground(字符串…参数){
HttpJsonParser HttpJsonParser=新的HttpJsonParser();
JSONObject JSONObject=httpJsonParser.makeHttpRequest(
BASE_URL+“fetch_all_movies.php”,“GET”,null);
试一试{
int success=jsonObject.getInt(KEY_success);
JSONArray电影;
如果(成功==1){
movieList=newarraylist();
movies=jsonObject.getJSONArray(键数据);
//遍历响应并填充电影列表
对于(int i=0;i  <?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
 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);

 ?>
header('Content-Type: application/json');
echo json_encode($response);