duanpeng1532 2014-11-22 19:15
浏览 73
已采纳

从url读取json(Android)

Sorry for my English. I can not in any way to display data that are taken from the json link. Like a lot of examples on the internet, but I can not seem to understand what is the error. I think that is not correct php files, although it can be. I ask you, programmers help to understand why the application does not work. Below I have brought all the files: Working json link from which I am trying to read data http://ksupulse.tk/get_all.php

db_config.php

    <?php 
    define('DB_USER', "login"); 
    define('DB_PASSWORD', "pass"); 
    define('DB_DATABASE', "database"); 
    define('DB_SERVER', "server"); 
?>

db_connect.php

<?php

/**
 * A class file to connect to database
 */
class DB_CONNECT {

    // constructor
    function __construct() {
        // connecting to database
        $this->connect();
    }

    // destructor
    function __destruct() {
        // closing db connection
        $this->close();
    }

    /**
     * Function to connect with database
     */
    function connect() {
        // import database connection variables
        require_once __DIR__ . '/db_config.php';

        // Connecting to mysql database
        $con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());

        // Selecing database
        $db = mysql_select_db(DB_DATABASE) or die(mysql_error()) or die(mysql_error());

        // returing connection cursor
        return $con;
    }

    /**
     * Function to close db connection
     */
    function close() {
        // closing db connection
        mysql_close();
    }

}

?>

get_all.php

<?php
header('Content-Type: application/json; charset=utf-8');


$response = array();

require 'db_connect.php';

$db = new DB_CONNECT();

$result = mysql_query("SELECT * FROM demo") or die(mysql_error());

if (mysql_num_rows($result) > 0) {
    $response["demo"] = array();

    while ($row = mysql_fetch_array($result)) {
        $product = array();
        $product["id"] = $row["id"];
        $product["name"] = $row["name"];
        $product["detaly"] = $row["detaly"];

        array_push($response["demo"], $product);
    }
    $response["success"] = 1;



    echo json_encode($response);


} else {
    $response["success"] = 0;
    $response["message"] = "No products found";

    echo json_encode($response);
}
?>

Android files:

MainActivity

 public class MainActivity extends Activity {

        //URL to get JSON Array
        private static String url = "http://ksupulse.tk/get_all.php";

        //JSON Node Names 
        private static final String TAG_USER = "detaly";
        private static final String TAG_ID = "id";
        private static final String TAG_NAME = "name";
        private static final String TAG_EMAIL = "email";

        JSONArray user = null;



        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            setContentView(R.layout.activity_main);

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

            // Getting JSON from URL
            JSONObject json = jParser.getJSONFromUrl(url);

            try {
                // Getting JSON Array
                user = json.getJSONArray(TAG_USER);
                JSONObject c = user.getJSONObject(0);

                // Storing  JSON item in a Variable
                String id = c.getString(TAG_ID);
                String name = c.getString(TAG_NAME);
                String email = c.getString(TAG_EMAIL);

                //Importing TextView
                final TextView uid = (TextView)findViewById(R.id.uid);
                final TextView name1 = (TextView)findViewById(R.id.name);
                final TextView email1 = (TextView)findViewById(R.id.email);

                //Set JSON Data in TextView
                uid.setText(id);
                name1.setText(name);
                email1.setText(email);


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



        }

JSONParser

public class JSONParser {

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

    // constructor
    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            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, "utf-8"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "
");
            }
            is.close();
            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;

    }
}

This is something that I am concerned in error:

11-22 18:37:57.448: E/JSON Parser(1850): Error parsing data org.json.JSONException: Value  of type java.lang.String cannot be converted to JSONObject

All errors:

11-22 18:37:54.748: E/Trace(1850): error opening trace file: No such file or directory (2) 11-22 18:37:57.448: E/JSON Parser(1850): Error parsing data org.json.JSONException: Value of type java.lang.String cannot be converted to JSONObject 11-22 18:37:57.448: D/AndroidRuntime(1850): Shutting down VM 11-22 18:37:57.460: W/dalvikvm(1850): threadid=1: thread exiting with uncaught exception (group=0xa6265288) 11-22 18:37:57.468: E/AndroidRuntime(1850): FATAL EXCEPTION: main 11-22 18:37:57.468: E/AndroidRuntime(1850): java.lang.RuntimeException: Unable to start activity ComponentInfo{learn2crack.jsonparsing/learn2crack.jsonparsing.MainActivity}: java.lang.NullPointerException 11-22 18:37:57.468: E/AndroidRuntime(1850): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059) 11-22 18:37:57.468: E/AndroidRuntime(1850): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084) 11-22 18:37:57.468: E/AndroidRuntime(1850): at android.app.ActivityThread.access$600(ActivityThread.java:130) 11-22 18:37:57.468: E/AndroidRuntime(1850): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195) 11-22 18:37:57.468: E/AndroidRuntime(1850): at android.os.Handler.dispatchMessage(Handler.java:99) 11-22 18:37:57.468: E/AndroidRuntime(1850): at android.os.Looper.loop(Looper.java:137) 11-22 18:37:57.468: E/AndroidRuntime(1850): at android.app.ActivityThread.main(ActivityThread.java:4745) 11-22 18:37:57.468: E/AndroidRuntime(1850): at java.lang.reflect.Method.invokeNative(Native Method) 11-22 18:37:57.468: E/AndroidRuntime(1850): at java.lang.reflect.Method.invoke(Method.java:511) 11-22 18:37:57.468: E/AndroidRuntime(1850): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 11-22 18:37:57.468: E/AndroidRuntime(1850): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 11-22 18:37:57.468: E/AndroidRuntime(1850): at dalvik.system.NativeStart.main(Native Method) 11-22 18:37:57.468: E/AndroidRuntime(1850): Caused by: java.lang.NullPointerException 11-22 18:37:57.468: E/AndroidRuntime(1850): at learn2crack.jsonparsing.MainActivity.onCreate(MainActivity.java:43) 11-22 18:37:57.468: E/AndroidRuntime(1850): at android.app.Activity.performCreate(Activity.java:5008) 11-22 18:37:57.468: E/AndroidRuntime(1850): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079) 11-22 18:37:57.468: E/AndroidRuntime(1850): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023) 11-22 18:37:57.468: E/AndroidRuntime(1850): ... 11 more 11-22 18:57:04.626: E/JSON Parser(1888): Error parsing data org.json.JSONException: Value of type java.lang.String cannot be converted to JSONObject 11-22 18:57:04.626: D/AndroidRuntime(1888): Shutting down VM 11-22 18:57:04.626: W/dalvikvm(1888): threadid=1: thread exiting with uncaught exception (group=0xa6265288) 11-22 18:57:04.626: E/AndroidRuntime(1888): FATAL EXCEPTION: main 11-22 18:57:04.626: E/AndroidRuntime(1888): java.lang.RuntimeException: Unable to start activity ComponentInfo{learn2crack.jsonparsing/learn2crack.jsonparsing.MainActivity}: java.lang.NullPointerException 11-22 18:57:04.626: E/AndroidRuntime(1888): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059) 11-22 18:57:04.626: E/AndroidRuntime(1888): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084) 11-22 18:57:04.626: E/AndroidRuntime(1888): at android.app.ActivityThread.access$600(ActivityThread.java:130) 11-22 18:57:04.626: E/AndroidRuntime(1888): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195) 11-22 18:57:04.626: E/AndroidRuntime(1888): at android.os.Handler.dispatchMessage(Handler.java:99) 11-22 18:57:04.626: E/AndroidRuntime(1888): at android.os.Looper.loop(Looper.java:137) 11-22 18:57:04.626: E/AndroidRuntime(1888): at android.app.ActivityThread.main(ActivityThread.java:4745) 11-22 18:57:04.626: E/AndroidRuntime(1888): at java.lang.reflect.Method.invokeNative(Native Method) 11-22 18:57:04.626: E/AndroidRuntime(1888): at java.lang.reflect.Method.invoke(Method.java:511) 11-22 18:57:04.626: E/AndroidRuntime(1888): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 11-22 18:57:04.626: E/AndroidRuntime(1888): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 11-22 18:57:04.626: E/AndroidRuntime(1888): at dalvik.system.NativeStart.main(Native Method) 11-22 18:57:04.626: E/AndroidRuntime(1888): Caused by: java.lang.NullPointerException 11-22 18:57:04.626: E/AndroidRuntime(1888): at learn2crack.jsonparsing.MainActivity.onCreate(MainActivity.java:43) 11-22 18:57:04.626: E/AndroidRuntime(1888): at android.app.Activity.performCreate(Activity.java:5008) 11-22 18:57:04.626: E/AndroidRuntime(1888): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079) 11-22 18:57:04.626: E/AndroidRuntime(1888): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023) 11-22 18:57:04.626: E/AndroidRuntime(1888): ... 11 more

  • 写回答

1条回答 默认 最新

  • dongmoxin7111 2014-11-22 20:28
    关注
    1. http://ksupulse.tk/get_all.php doesn't work and the stack trace shows 'No such file' so make sure you're passing the correct link.
    2. Use a website such as http://www.jsoneditoronline.org/ to see exactly what's coming back. The error is in your MainActivity class when you're parsing the JSON. "Error parsing data org.json.JSONException: Value  of type java.lang.String cannot be converted to JSONObject". Your line JSONObject c = user.getJSONObject(0); needs a string passed in instead of "0."

    Side comment: It's not good practice to make networking calls on the main thread in Android. Use AsyncTask.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀