0

私は Android アプリに取り組んでおり、PHP フォーラムからトピックのリストを取得する必要がありますが、コードを実行すると、このエラーが発生し、理解できませんでした。

03-18 09:11:43.221: E/JSON(286): <br />
03-18 09:11:43.221: E/JSON(286): <b>Parse error</b>:in  <b>C:\xampp\htdocs\android_login_api\include\list_of_topics.php</b> on line <b>26</b><br />
03-18 09:11:43.322: E/JSON Parser(286): Error parsing data org.json.JSONException: Value <br of     type java.lang.String cannot be converted to JSONObject

ここに私のphpがあります

<?php

/*
 * Following code will list all the products
 */

// array for JSON response
$response = array();

// include db connect class
require_once __DIR__ . 'DB_Connect.php';

// connecting to db
$db = new DB_CONNECT();

// get all products from products table
if(isset($_GET['parent']))
{
    $id = intval($_GET['parent']);}
$result = mysql_query("select t.id, t.title, u.username as author,  from topics as t  left join user as u where t.parent="'.$id.'" and t.id2=1 group by t.id order by t.timestamp2 desc');
") or die(mysql_error());

// check for empty result
if (mysql_num_rows($result) > 0) {
    // looping through all results
    // products node
    $response["topics"] = array();

    while ($row = mysql_fetch_array($result)) {
    // temp user array
    $topic = array();
    $topic["tid"] = $row["t.id"];
    $topic["name"] = $row["t.title"];
    $topic["author"] = $row["u.username"];


    // push single product into final response array

    array_push($response["topics"], $topic);
    echo json_encode($response);
    }
    // success
    $response["success"] = 1;

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

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

これは JSON パーサー クラスです。1 つはユーザー reg&login 用、もう 1 つはトピック リスト用の 2 つの JSONOBJECT があります。

package com.example.androidhive.library;


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

import android.util.Log;

public class JSONParser {

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

    // constructor
    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {

        // Making HTTP request
        try {
            // 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();

        } 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();
            Log.e("JSON", json);
        } catch (Exception e) {
            //Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // 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;

    }

     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();
            Log.e("JSON", sb.toString());
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // 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;

        }


}

これは Android 側の .java ファイルです

package com.example.androidhive;

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

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

import android.app.ListActivity;
import android.app.ProgressDialog;
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;
import android.widget.TextView;

import com.example.androidhive.library.JSONParser;




public class Topics_list extends ListActivity {

// Progress Dialog
private ProgressDialog pDialog;

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

ArrayList<HashMap<String, String>> TopicsList;

// url to get all products list
private static String url_all_topics = "http://10.0.2.2/android_login_api/include/list_of_topics.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_TOPICS = "topics";
private static final String TAG_TOPICSID = "t.id";
private static final String TAG_TOPICTITLE = "t.title";
private static final String TAG_TOPICAUTHOR = "u.username";

// products JSONArray
JSONArray topics = null;

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

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

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

// Get listview
ListView lv = getListView();

// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {

    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    // getting values from selected ListItem
    String tid = ((TextView) view.findViewById(R.id.tid)).getText()
        .toString();
    }
   });

   }

    /*// Starting new intent
    Intent in = new Intent(getApplicationContext(),
        EditProductActivity.class);
    // sending pid to next activity
    in.putExtra(TAG_PID, pid);

    // starting new activity and expecting some response back
    startActivityForResult(in, 100);
    }
});

}

// Response from Edit Product Activity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
    // if result code 100 is received
    // means user edited/deleted product
    // reload this screen again
    Intent intent = getIntent();
    finish();
    startActivity(intent);
}

}*/

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

/**
 * Before starting background thread Show Progress Dialog
 * */
@Override
protected void onPreExecute() {
    super.onPreExecute();
    pDialog = new ProgressDialog(Topics_list.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) {
    // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    // getting JSON string from URL
    JSONObject json = jParser.makeHttpRequest (url_all_topics, "GET", params);

    // Check your log cat for JSON reponse
    Log.d("All topics: ", json.toString());

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

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

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

        // Storing each json item in variable
        String id = c.getString(TAG_TOPICSID);
        String topict = c.getString(TAG_TOPICTITLE);
        String username = c.getString(TAG_TOPICAUTHOR);

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

        // adding each child node to HashMap key => value
        map.put(TAG_TOPICSID, id);
        map.put(TAG_TOPICTITLE, topict);
        map.put(TAG_TOPICAUTHOR, username);

        // adding HashList to ArrayList
        TopicsList.add(map);
        }
    } else {
        // no products found
        // Launch Add New product Activity
       /* Intent i = new Intent(getApplicationContext(),
            NewProductActivity.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(
           Topics_list.this, TopicsList,
            R.layout.list_item, new String[] { TAG_TOPICSID,TAG_TOPICTITLE,
                TAG_TOPICAUTHOR},
            new int[] { R.id.tid, R.id.title });
        // updating listview
        setListAdapter(adapter);
    }
    });

}

}
 }

最新の .php コード バージョン

<?php

/*
 * Following code will list all the products
 */

// array for JSON response
$response = array();

// include db connect class
require_once __DIR__ . 'DB_Connect.php';

// connecting to db
$db = new DB_CONNECT();

// get all products from products table

if(array_key_exists('parent', $_GET)){
      $id = intval($_GET['parent']);
 } else {
 exit();}
 //echo json_encode ("wrong");
      // something to stop this processing
     // $response["success"]=0;
     //$response["message"] = "No";
 //echo json_encode((object)$response);}

$result = mysql_query("select  t.id, t.title, u.username,  from topics as t  left join user as u where t.parent= '$id' and t.id2=1 group by t.id order by t.timestamp2 desc")
or die(mysql_error());


// check for empty result

//if (mysql_num_rows($result) > 0) {
    // looping through all results
    // products node
   // $response["topics"] = array();
    //echo json_encode((object)$response);

   // while ($row = mysql_fetch_array($result)) {
    // temp user array
    //    $topic = array();
    //    $topic["tid"] = $row["t.id"];
     //   $topic["name"] = $row["t.title"];
      //  $topic["author"] = $row["u.username"];


    // push single product into final response array

      /  array_push($response["topics"], $topic);

//}
if (mysqli_num_rows($result) > 0) {
    // looping through all results
    // products node
    $response['topics'] = array();
    while (true) {
       $row = mysqli_fetch_array($result);
       if(!$row)break;
       // temp user array
       $topic = array();
       $topic["tid"] = $row["t.id"];
       $topic["name"] = $row["t.title"];
       $topic["author"] = $row["u.username"];
       // push single product into final response array
       array_push($response["topics"], (object)$topic);
    }

    // success
    $response["success"] = 1;

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

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

誰かが私を助けてくれることを願っています。あなたの助けに感謝。私はあまり上手ではないので我慢してください。

4

1 に答える 1

2

まあ、あなたは変形したjson応答をまったく構築していると思います。

また、Mysql は非推奨です。mysqli インターフェイスを使用してください。

各データベース レコードを個別にエコーしないでください。

また、キー => 値に関連付けられた配列を通常の json 配列に渡そうとしていますが、これを行うと、次のキャストが使用されます。

json_encode((object)$keyValueArray);

Jsonにはキーと値のペアの配列がありませんが、そのためのオブジェクトがあるためです。

修正され、再フォーマットされたコードは次のとおりです。

私の発言は// * * *で始まります

<?php

/*
 * Following code will list all the products
 */

// *** this will be the database connection 
$db = null; 

// *** We will first check for the $_GET, since if it fails, no need to 
// *** use resources, open databases etc...

// *** I have to warn you about $_GET, anything which is not numeric will
// *** give an $id of 0 so I added a numeric check..
if( (isset($_GET['parent'])) && (is_numeric($_GET['parent'])) ){
     $id = intval($_GET['parent']);
} else {
// *** Examine the function responseFailure I appended to source
// *** Inform about bad id and exit.
     responseFailure("Bad id");
}

// *** Your DB_Connect.php uses mysql commands which are deprecated
// *** So I cancelled it and put an alternative 

// include db connect class
// require_once __DIR__ . 'DB_Connect.php';
// connecting to db
// $db = new DB_CONNECT();

// *** To use mysqli interface please use the code below.  
// *** Replace the values of $dbHost, $dbUser, $dbPass & $dbName
// *** With your own connection information

$dbHost = 'Your Database Server Name';    
$dbUser = 'Your Username On That Server';
$dbPass = 'Your Password On That Server';
$dbName = 'Your Database Name On That Server';

// *** Now lets try to connect
$db = mysqli_connect($dbHost, $dbUser, $dbPass, $dbName);
//  *** inform if connect fails and exit.
if(!$db)responseFailure("Unable to connect database server");

// get all products from products table 

// *** your query is complex, so build it into a string for clarity.
// *** one bug in your code was "..."'.$id.'"...' which will give a parse error

$query = "select t.id, t.title, u.username as author, " 
        ."from topics as t left join user as u where t.parent='"
        .$id
        ."' and t.id2=1 group by t.id order by t.timestamp2 desc";

$result = mysqli_query($db, $query);
//  *** inform if query fails and exit.
if(!$result)responseFailure("Database Query failed");

// check for empty result
// *** Now if no rows, leave, no need too much code depth
if(mysqli_num_rows($result) == 0) responseFailure("No topics found");

// array for JSON response
// *** We guaranteed the success now :)
$response = array('topics' => array(), 'success'=> 1);
// *** here for programming clarity I modified
// *** while ($row = mysqli_fetch_assoc($result)) {
// *** which is generally considered as a bad practice.
while (true) {
    $row = mysqli_fetch_assoc($result);
    if(!$row)break;
    // temp user array
    $topic = array();
    $topic["tid"] = $row["t.id"];
    $topic["name"] = $row["t.title"];
    $topic["author"] = $row["u.username"];
    // push single product into final response array
    // *** Yes we will echo it later
    // *** And since it is a key => value associated array
    // *** We will cast it into object while adding
    array_push($response["topics"], (object)$topic);
} // *** end while
// *** Since it is a key => value associated array
// *** We will cast it into object while encoding
echo json_encode((object)$response); // *** you can echo it now.
if($db)mysqli_close($db);            // *** close database connection
exit(0);                             // *** Job done say goodbye

// *** we may fail in multiple points
// *** so writing this as a seperate function is optimal
// *** This function exits the php script, it does not return back

function responseFailure($msg) {
    $r = array("success" => 0, "message" => $msg); // *** build response
    echo json_encode((object)$r);  // *** build json and send it
    if($db)mysqli_close($db);      // *** close database connection if open
    exit();                        // *** stop processing
}
?>

これらがお役に立てば幸いです。

于 2013-03-18T09:27:31.913 に答える