简体   繁体   English

教程第6部分中的错误:JSON解析和Android ListView设计

[英]Error in tutorial Part 6: JSON Parsing and Android ListView Design

Android Eclipse Logcat give me an error : Android Eclipse Logcat给我一个错误:

02-07 06:31:28.531: E/JSON Parser(644): Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject

More.. 更多..

02-07 07:18:15.991: D/JSON GETTING DATA:(644): [<br /><b>Notice</b>:  Undefined variable: query_params in <b>D:\xampp\xampp\htdocs\webservice\comments.php</b> on line <b>17</b><br />{"success":0,"message":"No Post Available!"}]

I go here and found 我去这里发现

<?php

//Our "config.inc.php" file connects to database every time we include or require
//it within a php script.  Since we want this script to add a new user to our db,
//we will be talking with our database, and therefore,
//let's require the connection to happen:

`require("config.inc.php");`

//initial query
$query = "Select * FROM comments";

//execute query

    try {
        $stmt   = $db->prepare($query);
        $result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
    $response["success"] = 0;
    $response["message"] = "Database Error!";
    die(json_encode($response));
}

// Finally, we can retrieve all of the found rows into an array using fetchAll 

$rows = $stmt->fetchAll();


if (isset($row)){
    $response["success"] = 1;

$response["message"] = "Post Available!";
$response["posts"] = array();

foreach ($rows as $row) {
    $post = array();
    $post["post_id"]  = $row["post_id"];
    $post["username"] = $row["username"];
    $post["title"]    = $row["title"];
    $post["message"]  = $row["message"];

    //update our repsonse JSON data
    array_push($response["posts"], $post);
}

    // echoing JSON response
    echo json_encode($response);


} else {
    $response["success"] = 0;
    $response["message"] = "No Post Available!";
    die(json_encode($response));
}

?>


  <?php
<ol>
//load and connect to MySQL database stuff
require("config.inc.php");

if (!empty($_POST)) {
    //initial query
    $query = "INSERT INTO comments ( username, title, message ) VALUES ( :user, :title, :message )";

    //Update query


$query_params = array(
    ':user' => $_POST['username'],
    ':title' => $_POST['title'],
    ':message' => $_POST['message']
);

//execute query
try {
    $stmt   = $db->prepare($query);
    $result = $stmt->execute($query_params);
}
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:
    $response["success"] = 0;
    $response["message"] = "Database Error. Couldn't add post!";
    die(json_encode($response));
}

$response["success"] = 1;
$response["message"] = "Post Successfully Added!";
echo json_encode($response);


} 
?>

config.inc.php config.inc.php文件

<?php 

 // These variables define the connection information for your MySQL database 
    // This is also for the Xampp example,  if you are hosting on your own server,
    //make the necessary changes (mybringback_travis, etc.)
$username = "travis"; 
$password = "bacon1"; 
$host = "localhost"; 
$dbname = "webservice"; 

// UTF-8 is a character encoding scheme that allows you to conveniently store 
// a wide varienty of special characters, like ¢ or €, in your database. 
// By passing the following $options array to the database connection code we 
// are telling the MySQL server that we want to communicate with it using UTF-8 
// See Wikipedia for more information on UTF-8: 
// http://en.wikipedia.org/wiki/UTF-8 
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'); 

// A try/catch statement is a common method of error handling in object oriented code. 
// First, PHP executes the code within the try block.  If at any time it encounters an 
// error while executing that code, it stops immediately and jumps down to the 
// catch block.  For more detailed information on exceptions and try/catch blocks: 
// http://us2.php.net/manual/en/language.exceptions.php 
try 
{ 
    // This statement opens a connection to your database using the PDO library 
    // PDO is designed to provide a flexible interface between PHP and many 
    // different types of database servers.  For more information on PDO: 
    // http://us2.php.net/manual/en/class.pdo.php 
    $db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options); 
} 
catch(PDOException $ex) 
{ 
    // If an error occurs while opening a connection to your database, it will 
    // be trapped here.  The script will output an error and stop executing. 
    // Note: On a production website, you should not output $ex->getMessage(). 
    // It may provide an attacker with helpful information about your code 
    // (like your database username and password). 
    die("Failed to connect to the database: " . $ex->getMessage()); 
} 

// This statement configures PDO to throw an exception when it encounters 
// an error.  This allows us to use try/catch blocks to trap database errors. 
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 

// This statement configures PDO to return database rows from your database using an associative 
// array.  This means the array will have string indexes, where the string value 
// represents the name of the column in your database. 
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); 

// This block of code is used to undo magic quotes.  Magic quotes are a terrible 
// feature that was removed from PHP as of PHP 5.4.  However, older installations 
// of PHP may still have magic quotes enabled and this code is necessary to 
// prevent them from causing problems.  For more information on magic quotes: 
// http://php.net/manual/en/security.magicquotes.php 
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); 
} 

// This tells the web browser that your content is encoded using UTF-8 
// and that it should submit content back to you using UTF-8 
header('Content-Type: text/html; charset=utf-8'); 

// This initializes a session.  Sessions are used to store information about 
// a visitor from one web page visit to the next.  Unlike a cookie, the information is 
// stored on the server-side and cannot be modified by the visitor.  However, 
// note that in most cases sessions do still use cookies and require the visitor 
// to have cookies enabled.  For more information about sessions: 
// http://us.php.net/manual/en/book.session.php 
session_start(); 

// Note that it is a good practice to NOT end your PHP files with a closing PHP tag. 
// This prevents trailing newlines on the file from being included in your output, 
// which can cause problems with redirecting users.

?>

Notice: Undefined variable: query_params in D:\\xampp\\xampp\\htdocs\\webservice\\comments.php on line 17 {"success":0,"message":"No Post Available!"} can't be converted to json. 注意:未定义变量:第17行{“ success”:0,“ message”:“无可用帖子!”}中D:\\ xampp \\ xampp \\ htdocs \\ webservice \\ comments.php中的query_params无法转换为json。 How to fix this problem? 如何解决这个问题? Full source code is There ! 完整的源代码在那里

ReadComment.java ReadComment.java

package com.example.mysqltest;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class ReadComments extends ListActivity {

// Progress Dialog
private ProgressDialog pDialog;

// php read comments script

// localhost :
// testing on your device
// put your local ip instead, on windows, run CMD > ipconfig
// or in mac's terminal type ifconfig and look for the ip under en0 or en1
// private static final String READ_COMMENTS_URL =
// "http://xxx.xxx.x.x:1234/webservice/comments.php";

// testing on Emulator:
private static final String READ_COMMENTS_URL = "http://10.0.2.2:1234/webservice/comments.php";

// testing from a real server:
// private static final String READ_COMMENTS_URL =
// "http://www.mybringback.com/webservice/comments.php";

// JSON IDS:
private static final String TAG_SUCCESS = "success";
private static final String TAG_TITLE = "title";
private static final String TAG_POSTS = "posts";
private static final String TAG_POST_ID = "post_id";
private static final String TAG_USERNAME = "username";
private static final String TAG_MESSAGE = "message";
// it's important to note that the message is both in the parent branch of
// our JSON tree that displays a "Post Available" or a "No Post Available"
// message,
// and there is also a message for each individual post, listed under the
// "posts"
// category, that displays what the user typed as their message.

// An array of all of our comments
private JSONArray mComments = null;
// manages all of our comments in a list.
private ArrayList<HashMap<String, String>> mCommentList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // note that use read_comments.xml instead of our single_post.xml
    setContentView(R.layout.read_comments);
}

@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    // loading the comments via AsyncTask
    new LoadComments().execute();
}

public void addComment(View v) {
    Intent i = new Intent(ReadComments.this, AddComment.class);
    startActivity(i);
}

/**
 * Retrieves recent post data from the server.
 */
public void updateJSONdata() {

    // Instantiate the arraylist to contain all the JSON data.
    // we are going to use a bunch of key-value pairs, referring
    // to the json element name, and the content, for example,
    // message it the tag, and "I'm awesome" as the content..

    mCommentList = new ArrayList<HashMap<String, String>>();

    // Bro, it's time to power up the J parser
    JSONParser jParser = new JSONParser();
    // Feed the beast our comments url, and it spits us
    // back a JSON object. Boo-yeah Jerome.

    JSONObject json = jParser.getJSONFromUrl(READ_COMMENTS_URL);
    Log.d("JSON: ", json.toString());

    // when parsing JSON stuff, we should probably
    // try to catch any exceptions:
    try {
        int success = json.getInt(TAG_SUCCESS);

        if (success == 1) {
            // I know I said we would check if "Posts were Avail."
            // (success==1)
            // before we tried to read the individual posts, but I lied...
            // mComments will tell us how many "posts" or comments are
            // available
            mComments = json.getJSONArray(TAG_POSTS);

            // looping through all posts according to the json object
            // returned
            for (int i = 0; i < mComments.length(); i++) {
                JSONObject c = mComments.getJSONObject(i);

                // gets the content of each tag
                String title = c.getString(TAG_TITLE);
                String content = c.getString(TAG_MESSAGE);
                String username = c.getString(TAG_USERNAME);

                // creating new HashMap
                HashMap<String, String> map = new HashMap<String, String>();

                map.put(TAG_TITLE, title);
                map.put(TAG_MESSAGE, content);
                map.put(TAG_USERNAME, username);

                // adding HashList to ArrayList
                mCommentList.add(map);

                // annndddd, our JSON data is up to date same with our array
                // list
            }
        } else {

        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

}

/**
 * Inserts the parsed data into the listview.
 */
private void updateList() {
    // For a ListActivity we need to set the List Adapter, and in order to
    // do
    // that, we need to create a ListAdapter. This SimpleAdapter,
    // will utilize our updated Hashmapped ArrayList,
    // use our single_post xml template for each item in our list,
    // and place the appropriate info from the list to the
    // correct GUI id. Order is important here.
    ListAdapter adapter = new SimpleAdapter(this, mCommentList,
            R.layout.single_post, new String[] { TAG_TITLE, TAG_MESSAGE,
                    TAG_USERNAME }, new int[] { R.id.title, R.id.message,
                    R.id.username });

    // I shouldn't have to comment on this one:
    setListAdapter(adapter);

    // Optional: when the user clicks a list item we
    // could do something. However, we will choose
    // to do nothing...
    ListView lv = getListView();
    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {

            // This method is triggered if an item is click within our
            // list. For our example we won't be using this, but
            // it is useful to know in real life applications.

        }
    });
}

public class LoadComments extends AsyncTask<Void, Void, Boolean> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(ReadComments.this);
        pDialog.setMessage("Loading Comments...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected Boolean doInBackground(Void... arg0) {
        updateJSONdata();
        return null;

    }

    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);
        pDialog.dismiss();
        updateList();
    }
}
}

JSONparser.java JSONparser.java

package com.example.mysqltest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = null;

// constructor
public JSONParser() {

}

public JSONObject getJSONFromUrl(final String url) {

    // Making HTTP request
    try {
        // Construct the client and the HTTP request.
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        // Execute the POST request and store the response locally.
        HttpResponse httpResponse = httpClient.execute(httpPost);
        // Extract data from the response.
        HttpEntity httpEntity = httpResponse.getEntity();
        // Open an inputStream with the data content.
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        // Create a BufferedReader to parse through the inputStream.
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "utf-8"), 8);
        // Declare a string builder to help with the parsing.
        StringBuilder sb = new StringBuilder();
        // Declare a string to store the JSON object data in string form.
        String line = null;

        // Build the string until null.
        // while ((line = reader.readLine()) != null) {
        // sb.append(line + "\n");
        // }
        while ((line = reader.readLine()) != null) {
            sb.append(line);
            json = sb.toString().substring(0, sb.toString().length() - 1);
        }
        // Close the input stream.
        is.close();
        // Convert the string builder data to an actual string.
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // Try to parse the string to a JSON object
    try {
        Log.d("JSON: ", "["+json+"]");
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // Return the JSON Object.
    return jObj;

}

// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
        List<NameValuePair> params) {

    // Making HTTP request
    try {

        // check for request method
        if (method.equalsIgnoreCase("POST")) {
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();

            is = httpEntity.getContent();

        } else if (method.equalsIgnoreCase("GET")) {
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            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);
            json = s

b.toString().substring(0, sb.toString().length() - 1);
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }


        try {jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }


    return jObj;

}
}

There's another addComment.php file, 还有另一个addComment.php文件,

<?php



and connect to MySQL database stuff
require("config.inc.php");

if (!empty($_POST)) {

    $query = "INSERT INTO comments ( username, title, message ) VALUES ( :user, :title, `:message` 

)";

//Update query, Maybe This vaiable is undefined?
$query_params = array(
    ':user' => $_POST['username'],
    ':title' => $_POST['title'],
    ':message' => $_POST['message']
);

try {
    $stmt   = $db->prepare($query);
    $result = $stmt->execute($query_params);
}
catch (PDOException $ex) {

    die("Failed to run query: " . $ex->getMessage());

    //or just use this use this one:
    $response["success"] = 0;
    $response["message"] = "Database Error. Couldn't add post!";
    die(json_encode($response));
}

$response["success"] = 1;
$response["message"] = "Post Successfully Added!";
echo json_encode($response);


} 
?>

login.php 的login.php

<?php


require("config.inc.php");

if (!empty($_POST)) {

$query = " 
        SELECT 
            id, 
            username, 
            password
        FROM users 
        WHERE 
            username = :username 
    ";

$query_params = array(
    ':username' => $_POST['username']
);

try {
    $stmt   = $db->prepare($query);
    $result = $stmt->execute($query_params);
}
catch (PDOException $ex) {

    $response["success"] = 0;
    $response["message"] = "Database Error1. Please Try Again!";
    die(json_encode($response));

}


$validated_info = false;

$row = $stmt->fetch();
if ($row) {

    if ($_POST['password'] === $row['password']) {
        $login_ok = true;
    }
}

if ($login_ok) {
    $response["success"] = 1;
    $response["message"] = "Login successful!";
    die(json_encode($response));
} else {
    $response["success"] = 0;
    $response["message"] = "Invalid Credentials!";
    die(json_encode($response));
}
} 

?>

Register.php Register.php

<?php


require("config.inc.php");


if

 (!empty($_POST)) {

    if (empty($_POST['username']) || empty($_POST['password'])) {

    $response["success"] = 0;
    $response["message"] = "Please Enter Both a Username and Password.";

    die(json_encode($response));
}


$query        = " SELECT 1 FROM users WHERE username = :user";

$query_params = array(
    ':user' => $_POST['username']
);


try {

    $stmt   = $db->prepare($query);
    $result = $stmt->execute($query_params);
}
catch (PDOException $ex) {

    $response["success"] = 0;
    $response["message"] = "Database Error1. Please Try Again!";
    die(json_encode($response));
}

$row = $stmt->fetch();
if ($row) {


    //You could comment out the above die and use this one:
    $response["success"] = 0;
    $response["message"] = "I'm sorry, this username is already in use";
    die(json_encode($response));
}

$query = "INSERT INTO users ( username, password ) VALUES ( :user, :pass ) ";


$query_params = array(
    ':user' => $_POST['username'],
    ':pass' => $_POST['password']
);

try {
    $stmt   = $db->prepare($query);
    $result = $stmt->execute($query_params);
}
catch (PDOException $ex) {


    //or just use this use this one:
    $response["success"] = 0;
    $response["message"] = "Database Error2. Please Try Again!";
    die(json_encode($response));
}

$response["success"] = 1;
$response["message"] = "Username Successfully Added!";
echo json_encode($response);



}

?>

index.php 的index.php

<?php

require("config.inc.php");

if (!empty($_POST)) {

if (empty($_POST['username']) || empty($_POST['password'])) {


    // Create some data that will be the JSON response 
    $response["success"] = 0;
    $response["message"] = "Please Enter Both a Username and Password.";

    die(json_encode($response));
}

$query        = " SELECT 1 FROM users WHERE username = :user";
//now lets update what :user should be
$query_params = array(
    ':user' => $_POST['username']
);

//Now let's make run the query:
try {
    // These two statements run the query against your database table. 
    $stmt   = $db->prepare($query);
    $result = $stmt->execute($query_params);
}
catch (PDOException $ex) {

    die("Failed to run query: " . $ex->getMessage());

    //You eventually want to comment out the above die and use this one:
    $response["success"] = 0;
    $response["message"] = "Database Error. Please Try Again!";
    die(json_encode($response));
}

$row = $stmt->fetch();
if ($row) {
    die("This username is already in use");
    //You could comment out the above die and use this one:
    $response["success"] = 0;
    $response["message"] = "I'm sorry, this username is already in use";
    die(json_encode($response));
}

$query = "INSERT INTO users ( username, password ) VALUES ( :user, :pass ) ";

//Again, we need to update our tokens with the actual data:
$query_params = array(
    ':username' => $_POST['username'],
    ':password' => $_POST['password']
);

//time to run our query, and create the user
try {
    $stmt   = $db->prepare($query);
    $result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
    // Again, don't display $ex->getMessage() when you go live. 
    die("Failed to run query: " . $ex->getMessage());
    //You could comment out the above die and use this one:
    $response["success"] = 0;
    $response["message"] = "Database Error. Please Try Again!";
    die(json_encode($response));
}

$response["success"] = 1;
$response["message"] = "Username Successfully Added!";
echo json_encode($response);    
} 

?>

I have sovled this problem, you just need to add string 我已经解决了这个问题,您只需要添加字符串

$query_params=null;

after

require("config.inc.php");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM