尝试获取表行计数值但得到错误转换结果java.lang.NullPointerException:lock == null

时间:2015-05-25 07:52:58

标签: javascript php android json jsonobject

我是这个东西的新手,所以我需要帮助我当前的问题,我正在尝试获取表行计数值,但“解析数据时出错org.json.JSONException:类型java.lang.String的值结果无法转换为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类:

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文件中,它返回null值。 所以我需要帮助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;
}


?>

3 个答案:

答案 0 :(得分:1)

删除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;

答案 1 :(得分:1)

您面临两个问题:

  

1)05-25 14:43:42.974:E / JSON Parser(23557):解析数据时出错   org.json.JSONException:值类型为java.lang.String的结果不能   转换为JSONObject

当您尝试从字符串创建JSON对象并且该字符串实际上不是JSON对象字符串时会触发此异常。

如果您获得了{"rowcount":5}那么正确的JSON对象。

  

2)java.lang.RuntimeException:执行时发生错误   doInBackground()   引起:android.view.ViewRootImpl $ CalledFromWrongThreadException:只有&gt;创建视图层次结构的原始线程可以触及其视图。

问题描述本身是不言自明的。仍然仅供参考,由于doInBackground()

中写的以下行,此问题正在提升
testRowCount.setText(row);

在执行后台操作时,您无法更新任何视图(即TextView或任何其他视图)。换句话说,您可以仅在主线程中更新UI。

为此,有两种方法:

  1. runOnUiThread()方法中实施doInBackground()并在其中编写视图更新代码。
  2. onPostExecute()方法更新用户界面。

答案 2 :(得分:0)

我终于解决了我的问题,首先我创建了一个用于连接数据库的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);
    

?> 

并且它有效,不知道它是如何工作的,感谢所有帮助我的人,最终解决了这个问题。