gpt4 book ai didi

php - 为什么 jsonObject 为空?

转载 作者:行者123 更新时间:2023-11-29 23:54:30 28 4
gpt4 key购买 nike

现在我正在尝试使用 Android 应用程序访问本地 XAMPP 服务器上的远程数据库。该应用程序有效,实际上它从正确的 Activity 开始。但是当我尝试访问数据库时它崩溃了。在日志中说,第 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;

}

这是列表类的代码:

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

?>

最佳答案

首先,在 https://jsoneditoronline.org/ 上打印并验证 JSON 响应格式

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

关于php - 为什么 jsonObject 为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50526934/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com