试图让表行计数值,但遇到错误转换的结果显示java.lang.NullPointerException:锁== NULL数值、错误、结果、让表行计

2023-09-03 21:45:31 作者:ㄣ尛念想

我是新的这个东西,所以我需要我目前的问题帮助,我试图让表行计数值,但错误分析数据org.json.JSONException:java.lang.String类型的值结果不能转换为JSONObject的出现

这是我的rowcount.php:

< PHP $库MySQLi =新库MySQLi(本地主机,根,,smkkimmanuel2); / *检查连接* / 如果(mysqli_connect_errno()){     的printf(连接失败:%S \ N,mysqli_connect_error());     出口(); } 如果($结果= $ mysqli->查询(SELECT * FROM pendaftaran)){     / *的行数确定结果集* /     $ row_cnt = $ result-> NUM_ROWS; 的printf(结果集有%d行\ñ,$ row_cnt); $响应[行数] = $ row_cnt; 死亡(json_en code($响应)); } ?>

和我row_count_test类:

包id.wanda.smkkkristenimmanuelii; 进口org.json.JSONException; 进口org.json.JSONObject; 进口android.app.Activity; 进口android.os.AsyncTask; 进口android.os.Bundle; 进口android.view.View; 进口android.widget.TextView; 公共类Row_count_test延伸活动{ 私人TextView的testRowCount; //标志网络连接状态     布尔isInternet present = FALSE;           //连接器类     ConnectionDetector CD; // JSON解析器类 JSONParser jsonParser =新JSONParser(); 私有静态最后弦乐LOGIN_URL =htt​​p://192.168.1.110/smkkimmanuel2/rowcount.php; // JSON元素的PHP脚本的repsonse IDS: 私有静态最后弦乐TAG_ROWCOUNT =行数; 公共静态字符串行; @覆盖 保护无效的onCreate(包savedInstanceState){ // TODO自动生成方法存根 super.onCreate(savedInstanceState); 的setContentView(R.layout.activity_row_count_test); testRowCount =(TextView中)findViewById(R.id.test); 新的行数()执行()。 } 公共无效rowCount时(视图v){ } 一流的行数扩展的AsyncTask<字符串,字符串,字符串> { @覆盖 保护字符串doInBackground(字符串参数... args){ 字符串中的getRow; //获取产品的详细信息通过HTTP请求 JSONObject的JSON = jsonParser.makeHtt prequestRowCount(LOGIN_URL); 尝试 { =的getRow json.getString(TAG_ROWCOUNT); 行=中的getRow; }赶上(JSONException E){ e.printStackTrace(); }赶上(NullPointerException异常E){ e.printStackTrace(); } 返回行; } @覆盖 保护无效onPostExecute(串行){ // TODO自动生成方法存根 testRowCount.setText(行); } } } excel表格中的数据有效性的使用方法,让输入数据不在出错

这是我的JSONObject先生@PareshMayani:

公开的JSONObject makeHtt prequestRowCount(URL字符串,字符串的方法){           //使HTTP请求         尝试 {                 DefaultHttpClient的HttpClient =新DefaultHttpClient();                 HttpPost httpPost =新HttpPost(URL);                   HTT presponse HTT presponse = httpClient.execute(httpPost);                 HttpEntity httpEntity = HTT presponse.getEntity();                 是= httpEntity.getContent();                          }赶上(UnsupportedEncodingException E){             e.printStackTrace();         }赶上(ClientProtocolException E){             e.printStackTrace();         }赶上(IOException异常E){             e.printStackTrace();         }           尝试 {             的BufferedReader读卡器=新的BufferedReader(新的InputStreamReader(                     是,ISO-8859-1),8);             StringBuilder的SB =新的StringBuilder();             串线= NULL;             而((行= reader.readLine())!= NULL){                 sb.append(行+\ N);             }             is.close();             JSON = sb.toString();         }赶上(例外五){             Log.e(缓冲区错误,转换的结果错误+ e.toString());         }         Log.d(JSON解析器,JSON);         //尝试解析字符串到一个JSON对象         尝试 {             jObj =新的JSONObject(JSON);         }赶上(JSONException E){             Log.e(JSON解析器,错误分析数据+ e.toString());         }           //返回JSON字符串         返回jObj;       }

编辑: 这似乎是发生在php文件的问题,它返回空值。 所以我需要用PHP文件帮助,

下面是新logcat的错误:

十一月5日至26号:28:46.530:E /缓存器的错误(15945):错误转换结果显示java.lang.NullPointerException:锁== NULL 十一月五号至26日:28:46.530:E / JSON解析器(15945):错误分析数据org.json.JSONException:输入的字符0结束

下面是新rowcount.php文件:

< PHP $库MySQLi =新库MySQLi(本地主机,根,,smkkimmanuel2); / *检查连接* / 如果(mysqli_connect_errno()){     的printf(连接失败:%S \ N,mysqli_connect_error());     出口(); } 如果($结果= $ mysqli->查询(SELECT * FROM pendaftaran)){     / *的行数确定结果集* /     $ row_cnt = $ result-> NUM_ROWS; $响应[行数] = $ row_cnt; 回声json_en code($响应);退出; } ?>

解决方案

我终于解决了我的问题,首先我创建的config.php用于连接到数据库

< PHP $用户名=根; $密码=; $主机=localhost的; $ DBNAME =smkkimmanuel2;     $选项=阵列(PDO :: MYSQL_ATTR_INIT_COMMAND =>'SET NAMES UTF8);     尝试     {         $ DB =新PDO(mysql的:主机= {$主机}; DBNAME = {$ DBNAME};字符集= UTF8,$用户名,密码$,$选择);     }     赶上(PDOException $前)     {         模具(无法连接到数据库:$ EX->的getMessage());     }           $ DB->的setAttribute(PDO :: ATTR_ERRMODE,PDO :: ERRMODE_EXCEPTION);     $ DB->的setAttribute(PDO :: ATTR_DEFAULT_FETCH_MODE,PDO :: FETCH_ASSOC);           如果(function_exists('get_magic_quotes_gpc')及&安培; get_magic_quotes_gpc())     {         功能undo_magic_quotes_gpc(安培; $阵列)         {             的foreach($阵列和放大器; $值)             {                 如果(is_array($值))                 {                     undo_magic_quotes_gpc($值);                 }                 其他                 {                     $值=函数stripslashes($值);                 }             }         }               undo_magic_quotes_gpc($ _ POST);         undo_magic_quotes_gpc($ _ GET);         undo_magic_quotes_gpc($ _ COOKIE);     }           标题(内容类型:text / html的;字符集= UTF-8);           在session_start(); ?>

和调整我rowcount.php是这样的:

< PHP //装载并连接到MySQL数据库的东西 要求(config.php文件);     //获取基于掀起了用户名的用户信息。     $查询=SELECT * FROM pendaftaran_calon_siswa;               尝试 {         $语句= $ DB-> prepare($查询);         $ stmt->执行();     }     赶上(PDOException $前){         //为了测试,你可以使用一个模具和消息。         //模具(无法运行的问题:$ EX->的getMessage());                  //或者只是用这个使用这个产品JSON数据:         $响应[成功] = 0;         $响应[信息] =数据库ERROR1请重试!;         死亡(json_en code($响应));              }          //获取所有行从查询 $行= $ stmt->使用fetchall(); $行=计数($行);      $响应[行数] = $行; 回声json_en code($响应);      ?>

和它的作品,不知道如何,但它的工作原理,感谢大家谁在帮我,终于解决了这个问题。

i'm new in this thing, so i need help with my current problem, i'm trying to get table row count value but "Error parsing data org.json.JSONException: Value Result of type java.lang.String cannot be converted to JSONObject" appear

here's my 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));
}


?>

and my 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);
		}
	}

	
}

here's my JSONObject Mr. @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;
 
    }

EDITED : it seems the problem occurs in the php file, it returning null value. so i need help with the php file,

here's the new logcat error :

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 

here's the new rowcount.php file :

<?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;
}


?>

解决方案

i've finally solve my problem, first i create a config.php for connection to the database

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

?>

and tweak my rowcount.php to be like this :

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

?> 

and it works, don't know how but it works, thanks everyone who's helping me, finally solve this problem.