缓冲区错误:&& JSON分析器错误:

时间:2016-05-12 13:53:08

标签: php android json parsing buffer

所以当我运行它时,我的Android应用程序出现2个错误。 first- / Buffer Error:转换结果时出错java.lang.NullPointerException:lock == null second- / JSON Parser:解析数据时出错org.json.JSONException:字符0处的输入结束...似乎我已经阅读了与同一问题有关的无数问题,但没有一个对我的情况有所帮助。我将用户名从共享首选项传递给我的php,所以我可以从DB查询当前用户。我从网上运行了PHP,一切似乎都在上升。希望有人可以帮助发现我的错误......继承人的代码 All_Content.java

package com.example.mrbuknahsty.annovoteexdb;

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.widget.ListAdapter;
import android.widget.SimpleAdapter;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

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

/**
 * Created by mr.buknahsty on 5/10/2016.
 */
public class All_Content extends ListActivity
{
// Progress Dialog
private ProgressDialog pDialog;

// Creating JSON Parser object
JSONParser jParser = new JSONParser();

ArrayList<HashMap<String, String>> contentList;

sessionManager session;

// url to get all products list
private static String url_all_content =   
"http://www.lkirkpatrick.btcwsd.com/anno/all.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_CONTENT = "content";
private static final String TAG_T_ID = "t_id";
private static final String TAG_NAME = "name";

// products JSONArray
JSONArray contents = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.all_content);

    // Hashmap for ListView
    contentList = new ArrayList<HashMap<String, String>>();

    // Loading products in Background Thread
    new LoadAllProducts().execute();

}

        /**
         * Background Async Task to Load all product by making HTTP Request
         * */
        class LoadAllProducts extends AsyncTask<String, String, String> {

            /**
             * Before starting background thread Show Progress Dialog
             * */
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                pDialog = new ProgressDialog(All_Content.this);
                pDialog.setMessage("Loading products. Please wait...");
                pDialog.setIndeterminate(false);
                pDialog.setCancelable(false);
                pDialog.show();
            }

            /**
             * getting All products from url
             * */
            protected String doInBackground(String... args) {
                session = new sessionManager(getApplicationContext());

                session.checkLogin();

                HashMap<String, String> user = session.getUserDetails();

                // name
                String uName = user.get(sessionManager.KEY_NAME);

                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>
 (1);
                // getting JSON string from URL
                JSONObject json = jParser.makeHttpRequest(url_all_content,   
 uName+"GET", params);

                if(json!=null) {
                    // do something
                    Log.d("results: ", json.toString());


                    // Check your log cat for JSON reponse


                    try {
                        // Checking for SUCCESS TAG
                        int success = json.getInt(TAG_SUCCESS);

                        if (success == 1) {
                            // products found
                            // Getting Array of Products
                            contents = json.getJSONArray(TAG_CONTENT);

                            // looping through All Products
                            for (int i = 0; i < contents.length(); i++)
                            {
                                JSONObject c = contents.getJSONObject(i);

                                // Storing each json item in variable
                                String id = c.getString(TAG_T_ID);
                                String name = c.getString(TAG_NAME);

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

                                // adding each child node to HashMap key =>   
 value
                                map.put(TAG_T_ID, id);
                                map.put(TAG_NAME, name);

                                // adding HashList to ArrayList
                                contentList.add(map);
                            }
                        } else {
                            // no products found
                            // Launch Add New product Activity
                            Intent i = new Intent(getApplicationContext(),
                                    All_Content.class);
                            // Closing all previous activities
                            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            startActivity(i);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                return null;
            }

            /**
             * After completing background task Dismiss the progress dialog
             * **/
            protected void onPostExecute(String file_url) {
                // dismiss the dialog after getting all products
                pDialog.dismiss();
                // updating UI from Background Thread
                runOnUiThread(new Runnable() {
                    public void run() {
                        /**
                         * Updating parsed JSON data into ListView
                         * */
                        ListAdapter adapter = new SimpleAdapter(
                                All_Content.this, contentList,
                                R.layout.list_item, new String[] { TAG_T_ID,
                                TAG_NAME},
                                new int[] { R.id.t_id, R.id.name });
                        // updating listview
                        setListAdapter(adapter);
                    }
                });

            }

        }
    }

JSONParser类

package com.example.mrbuknahsty.annovoteexdb;

import android.util.Log;

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.json.JSONException;
import org.json.JSONObject;

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

/**
 * Created by mr.buknahsty on 5/10/2016.
 */
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

// 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 == "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 == "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 + "\n");
            }
            is.close();
            json = sb.toString();

        }catch(Exception e)
        {
            Log.i("Buffer Error", "Error converting result " + 
e.toString());
        }

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

        // return JSON String
        return jObj;

}
}

all.php

<?php
require_once 'get_all.php';

$uName = "";


if(isset($_POST['uName']))
{
$uName = $_POST['uName'];
}


// Instance of a Topic class
$get_AllObject = new get_All();

// Registration of new topic
if(!empty($uName))
{

$json_registration = $get_AllObject->getAll($uName);

echo json_encode($json_registration);
}

?>

和我的get_all.php

<?php
include_once 'error.php';

class get_All{

private $db;
private $db_table = "topics";

public function __construct()
{
    $this->db = new DbConnect();
}


public function getAll($uName)
{   
    $response = array();

    ///////////////////////////////////////////
    //USERS TABLE
    //query to get current logged in user_id
    $un = "SELECT * FROM users WHERE username = '$uName'";

    //running query
    $unResults = mysqli_query($this->db->getDb(), $un);

    //get user_id results from query **CREDIT GOES TO BEN LAPAZ FOR THIS..
    while ($row = mysqli_fetch_array($unResults))
    {
        $id = ($row['user_id']);
    }

    //now i have current user_id
    /////////////////////////////////////////////////////////
    //CREATED_TOPICS TABLE
    //query to get all data from created_topics thats under user_id that 
matches current user_id
    $t_id = "SELECT * FROM created_topics WHERE user_id = '$id'";

    //running query
    $t_id_Results = mysqli_query($this->db->getDb(), $t_id);

    //get topic_id results from query 
    while ($rowT = mysqli_fetch_array($t_id_Results))
    {
        $id_T = ($rowT['topic_id']);
    }

    //now i have all topic_ids' for current user
  /////////////////////////////////////////////////////////////////////////
    //TOPICS TABLE
    //query to get all data from topics thats has to do with topic_ids from   
previous query
    $userContent = "SELECT * FROM topics WHERE topic_id = '$id_T'";

    $userContentResults = mysqli_query($this->db->getDb(),$userContent);

    //running query
   if ($userContentResults && mysqli_num_rows($userContentResults) > 0) 
   {
        // looping through all results
        // products node
        $response["content"] = array();

        //get content results from query 
        while ($rowContent = mysqli_fetch_array($userContent))
        {
             $content = array();
             $content["topic_id"] = $row["topic_id"];
             $content["topic_name"] = $row["topic_name"];
             $content["content"] = $row["content"];
             $content["code"] = $row["code"];
             $content["created_at"] = $row["created_at"];
             $content["updated_at"] = $row["updated_at"];

            // push single content into final response array
            array_push($response["content"], $content);
          }
            // success
            $response["success"] = 1;

            // echoing JSON response
            echo json_encode($response);
        } 
        else {
            // no products found
            $response["success"] = 0;
            $response["message"] = "No products found";

            // echo no users JSON
            echo json_encode($response);
        }
}
}
?>

并记录///这是我得到的全部

05-12 08:34:41.728 12650-12740/com.example.mrbuknahsty.annovoteexdb   
I/Buffer Error: Error converting result java.lang.NullPointerException: lock  
==  null

05-12 08:34:41.728 12650-12740/com.example.mrbuknahsty.annovoteexdb   
I/JSON Parser: Error parsing data org.json.JSONException: End of input at   
character 0 of 
05-12 08:34:41.828 12650-12650/com.example.mrbuknahsty.annovoteexdb  
I/Timeline: 
Timeline: Activity_idle id: android.os.BinderProxy@41b644f8 time:47813028

0 个答案:

没有答案