试图获取 table 行计数值但得到错误转换结果 java.lang.NullPointerException: lock == null
trying to get table row count value but got Error converting result java.lang.NullPointerException: lock == null
我是这方面的新手,所以我需要帮助解决我当前的问题,我正在尝试获取 table 行计数值,但 "Error parsing data org.json.JSONException: Value Result of type java.lang.String cannot be converted to JSONObject" 出现
这是我的 rowcount.php :
<?php
$mysqli = new mysqli("localhost", "root", "", "smkkimmanuel2");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if ($result = $mysqli->query("SELECT * FROM pendaftaran")) {
/* determine number of rows result set */
$row_cnt = $result->num_rows;
printf("Result set has %d rows.\n", $row_cnt);
$response["rowcount"] = $row_cnt;
die(json_encode($response));
}
?>
和我的 row_count_test class :
package id.wanda.smkkkristenimmanuelii;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class Row_count_test extends Activity {
private TextView testRowCount;
// flag for Internet connection status
Boolean isInternetPresent = false;
// Connection detector class
ConnectionDetector cd;
// JSON parser class
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "http://192.168.1.110/smkkimmanuel2/rowcount.php";
// JSON element ids from repsonse of php script:
private static final String TAG_ROWCOUNT = "rowcount";
public static String row;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_row_count_test);
testRowCount = (TextView) findViewById(R.id.test);
new RowCount().execute();
}
public void rowCount(View v) {
}
class RowCount extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... args) {
String getRow;
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequestRowCount(LOGIN_URL);
try {
getRow = json.getString(TAG_ROWCOUNT);
row = getRow;
} catch (JSONException e) {
e.printStackTrace();
}catch (NullPointerException e) {
e.printStackTrace();
}
return row;
}
@Override
protected void onPostExecute(String row) {
// TODO Auto-generated method stub
testRowCount.setText(row);
}
}
}
这是我的 JSONObject @PareshMayani 先生:
public JSONObject makeHttpRequestRowCount(String url, String method) {
// Making HTTP request
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException 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");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
Log.d("JSON Parser", json);
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
已编辑:
问题似乎出现在 php 文件中,它返回空值。
所以我需要有关 php 文件的帮助,
这是新的 logcat 错误:
05-26 11:28:46.530: E/Buffer Error(15945): Error converting result java.lang.NullPointerException: lock == null
05-26 11:28:46.530: E/JSON Parser(15945): Error parsing data org.json.JSONException: End of input at character 0 of
这是新的 rowcount.php 文件:
<?php
$mysqli = new mysqli("localhost", "root", "", "smkkimmanuel2");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if ($result = $mysqli->query("SELECT * FROM pendaftaran")) {
/* determine number of rows result set */
$row_cnt = $result->num_rows;
$response["rowcount"] = $row_cnt;
echo json_encode($response);exit;
}
?>
删除 printf 行并替换如下
$row_cnt = $result->num_rows;
// remove this line
//printf("Result set has %d rows.\n", $row_cnt);
$response["rowcount"] = $row_cnt;
//replace this line
//die(json_encode($response));
echo json_encode($response);exit;
您面临 2 个问题:
1) 05-25 14:43:42.974: E/JSON Parser(23557): Error parsing data
org.json.JSONException: Value Result of type java.lang.String cannot
be converted to JSONObject
当您尝试从字符串创建 JSON 对象并且该字符串实际上不是 JSON 对象字符串时,会触发此异常。
如果您得到 {"rowcount":5}
那么这是正确的 JSON 对象。
2) java.lang.RuntimeException: An error occured while executing
doInBackground()
Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the > original thread that created a view hierarchy can touch its views.
问题描述本身是不言自明的。仅供参考,由于 doInBackground()
:
中写的下面一行,这个问题被提出
testRowCount.setText(row);
您不能在执行后台操作时更新任何视图(即 TextView 或任何其他视图)。换句话说,您可以仅从主线程更新 UI。
有两种方法:
- 在
doInBackground()
方法中实现runOnUiThread()
,并在里面编写视图更新代码。
- 从
onPostExecute()
方法更新 UI。
我终于解决了我的问题,首先我创建了一个 config.php 用于连接到数据库
<?php
$username = "root";
$password = "";
$host = "localhost";
$dbname = "smkkimmanuel2";
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try
{
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}
catch(PDOException $ex)
{
die("Failed to connect to the database: " . $ex->getMessage());
}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
{
function undo_magic_quotes_gpc(&$array)
{
foreach($array as &$value)
{
if(is_array($value))
{
undo_magic_quotes_gpc($value);
}
else
{
$value = stripslashes($value);
}
}
}
undo_magic_quotes_gpc($_POST);
undo_magic_quotes_gpc($_GET);
undo_magic_quotes_gpc($_COOKIE);
}
header('Content-Type: text/html; charset=utf-8');
session_start();
?>
并将我的 rowcount.php 调整为如下所示:
<?php
//load and connect to MySQL database stuff
require("config.php");
//gets user's info based off of a username.
$query = "SELECT * FROM pendaftaran_calon_siswa";
try {
$stmt = $db->prepare($query);
$stmt->execute();
}
catch (PDOException $ex) {
// For testing, you could use a die and message.
//die("Failed to run query: " . $ex->getMessage());
//or just use this use this one to product JSON data:
$response["success"] = 0;
$response["message"] = "Database Error1. Please Try Again!";
die(json_encode($response));
}
//fetching all the rows from the query
$row = $stmt->fetchAll();
$rows = count($row);
$response["rowcount"] = $rows;
echo json_encode($response);
?>
成功了,不知道怎么回事,谢谢大家的帮助,终于解决了这个问题。
我是这方面的新手,所以我需要帮助解决我当前的问题,我正在尝试获取 table 行计数值,但 "Error parsing data org.json.JSONException: Value Result of type java.lang.String cannot be converted to JSONObject" 出现
这是我的 rowcount.php :
<?php
$mysqli = new mysqli("localhost", "root", "", "smkkimmanuel2");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if ($result = $mysqli->query("SELECT * FROM pendaftaran")) {
/* determine number of rows result set */
$row_cnt = $result->num_rows;
printf("Result set has %d rows.\n", $row_cnt);
$response["rowcount"] = $row_cnt;
die(json_encode($response));
}
?>
和我的 row_count_test class :
package id.wanda.smkkkristenimmanuelii;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class Row_count_test extends Activity {
private TextView testRowCount;
// flag for Internet connection status
Boolean isInternetPresent = false;
// Connection detector class
ConnectionDetector cd;
// JSON parser class
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "http://192.168.1.110/smkkimmanuel2/rowcount.php";
// JSON element ids from repsonse of php script:
private static final String TAG_ROWCOUNT = "rowcount";
public static String row;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_row_count_test);
testRowCount = (TextView) findViewById(R.id.test);
new RowCount().execute();
}
public void rowCount(View v) {
}
class RowCount extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... args) {
String getRow;
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequestRowCount(LOGIN_URL);
try {
getRow = json.getString(TAG_ROWCOUNT);
row = getRow;
} catch (JSONException e) {
e.printStackTrace();
}catch (NullPointerException e) {
e.printStackTrace();
}
return row;
}
@Override
protected void onPostExecute(String row) {
// TODO Auto-generated method stub
testRowCount.setText(row);
}
}
}
这是我的 JSONObject @PareshMayani 先生:
public JSONObject makeHttpRequestRowCount(String url, String method) {
// Making HTTP request
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException 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");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
Log.d("JSON Parser", json);
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
已编辑: 问题似乎出现在 php 文件中,它返回空值。 所以我需要有关 php 文件的帮助,
这是新的 logcat 错误:
05-26 11:28:46.530: E/Buffer Error(15945): Error converting result java.lang.NullPointerException: lock == null
05-26 11:28:46.530: E/JSON Parser(15945): Error parsing data org.json.JSONException: End of input at character 0 of
这是新的 rowcount.php 文件:
<?php
$mysqli = new mysqli("localhost", "root", "", "smkkimmanuel2");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if ($result = $mysqli->query("SELECT * FROM pendaftaran")) {
/* determine number of rows result set */
$row_cnt = $result->num_rows;
$response["rowcount"] = $row_cnt;
echo json_encode($response);exit;
}
?>
删除 printf 行并替换如下
$row_cnt = $result->num_rows;
// remove this line
//printf("Result set has %d rows.\n", $row_cnt);
$response["rowcount"] = $row_cnt;
//replace this line
//die(json_encode($response));
echo json_encode($response);exit;
您面临 2 个问题:
1) 05-25 14:43:42.974: E/JSON Parser(23557): Error parsing data org.json.JSONException: Value Result of type java.lang.String cannot be converted to JSONObject
当您尝试从字符串创建 JSON 对象并且该字符串实际上不是 JSON 对象字符串时,会触发此异常。
如果您得到 {"rowcount":5}
那么这是正确的 JSON 对象。
2) java.lang.RuntimeException: An error occured while executing doInBackground() Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the > original thread that created a view hierarchy can touch its views.
问题描述本身是不言自明的。仅供参考,由于 doInBackground()
:
testRowCount.setText(row);
您不能在执行后台操作时更新任何视图(即 TextView 或任何其他视图)。换句话说,您可以仅从主线程更新 UI。
有两种方法:
- 在
doInBackground()
方法中实现runOnUiThread()
,并在里面编写视图更新代码。 - 从
onPostExecute()
方法更新 UI。
我终于解决了我的问题,首先我创建了一个 config.php 用于连接到数据库
<?php
$username = "root";
$password = "";
$host = "localhost";
$dbname = "smkkimmanuel2";
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try
{
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}
catch(PDOException $ex)
{
die("Failed to connect to the database: " . $ex->getMessage());
}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
{
function undo_magic_quotes_gpc(&$array)
{
foreach($array as &$value)
{
if(is_array($value))
{
undo_magic_quotes_gpc($value);
}
else
{
$value = stripslashes($value);
}
}
}
undo_magic_quotes_gpc($_POST);
undo_magic_quotes_gpc($_GET);
undo_magic_quotes_gpc($_COOKIE);
}
header('Content-Type: text/html; charset=utf-8');
session_start();
?>
并将我的 rowcount.php 调整为如下所示:
<?php
//load and connect to MySQL database stuff
require("config.php");
//gets user's info based off of a username.
$query = "SELECT * FROM pendaftaran_calon_siswa";
try {
$stmt = $db->prepare($query);
$stmt->execute();
}
catch (PDOException $ex) {
// For testing, you could use a die and message.
//die("Failed to run query: " . $ex->getMessage());
//or just use this use this one to product JSON data:
$response["success"] = 0;
$response["message"] = "Database Error1. Please Try Again!";
die(json_encode($response));
}
//fetching all the rows from the query
$row = $stmt->fetchAll();
$rows = count($row);
$response["rowcount"] = $rows;
echo json_encode($response);
?>
成功了,不知道怎么回事,谢谢大家的帮助,终于解决了这个问题。