- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
现在我正在尝试使用 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/
我找不到答案。尝试了很多网站,包括这个。我想知道问题出在哪里。 错误是:org.json.JSONException:java.lang.String类型的值连接无法转换为JSONObject 这是我
我从 Java 应用程序提交了一个查询,该查询在 Elasticsearch 服务器上运行时以字符串形式返回结果。我希望结果为 JSONObject 列表对象。我可以将字符串转换为 JSONObjec
我正在尝试解析 JSON 字符串,但在尝试获取嵌套对象时出现错误: JSONObject jsonObject = new JSONObject(jsonString); System.out.pri
我有这样的 API 输出: {"user" : {"status" : {"stat1" : "54", "stats2" : "87"}}} 我从这个 API 创建了一个简单的 JSONObject
我正在寻找一种方法来比较两个 JSONObjects 除了使用 JSONObject.toString().equals(JSONObject.toString()) 并遇到了这种类似的方法,但它的比
我在读取和写入 Json 文件时遇到问题。我想将一些内容附加到 json 文件中,但它无法正常工作:它只是放入一个新的 json 对象,而没有使用 ',' 将其与前一个对象分开。我在每个网站上到处搜索
我有 JSON 文件:“D://test.json”,它遵循 MongoDB 格式: { "key":"value" } { "embedded": { "key2": "value2" } } {
我想要一个像这样的 json 文件: { "resu0": {"item":"value"} "resu1": {"item":"value"} "resu2": {"item":"value"} }
我有一个像这样的 JSON { "result": { "issue_date": "xx-yy-zzzz", "father/husband": "TEST",
我想发送json,里面有另一个json对象,像这样 { "key1": "value1", "key2": "valu2", "content": {
private JSONObject insertJSONintoJSON(JSONObject newJSON, JSONObject parent) { Object[] a = pare
常规更新:我之前询问是否可以按原样获取 JSONObject 的值,以便稍后将其与覆盖的版本进行比较。我的第一次尝试是: JSONObject oldObj = new JSONObject(); p
我正在尝试创建一个具有特定键和空值的 JSONObject。但该值应该是 JSONObject 而不是 JSONArray。 我已经使用 localJson.append(key, JSONObjec
我得到的所有资源都是从 JSONArray 获取 JSONObject。但在这种情况下,我想获得“temp”的温度。我不认为它是数组的一部分。我怎样才能得到它? { "coord":{
我正在尝试解析 JSONObject 以获取 JSON 数组的数据。 但问题是 JSONParser 是 org.json.simple.JSONParser 中的一个类,而 JSONObject 位
我发现 variable instanceof JSONObject 有奇怪的行为。我有以下代码: Object value; try { value = customer.get(key);
JsonObject 和 JSONObject 有什么区别? 当我们使用 put、add 和 addproperty 方法时,我有点混淆 JsonObject 和 JSONObject。 提前致谢。
我想从 Another JSONObject 中的一个 JSONObject 中检索数据谁能告诉我如何取回它们 我的JSONObject是这样的 {"udetail":{"ID":238597,"Re
你是否注意到,如果你使用 put() 将一个 JSONObject 放入另一个 JSONObject,容器 JSONObject 将不会存储对第一个 JSONObject 的引用,而是一个新的 JSO
我的应用程序构建得很好,但是当我运行它时,当以下行尝试执行时,我不断收到异常: JSONObject json = new JSONObject(); 我收到以下异常: 异常 javax.servle
我是一名优秀的程序员,十分优秀!