从url读取json(Android)

时间:2014-11-22 19:15:12

标签: java php android json eclipse

抱歉我的英文。我不能以任何方式显示从json链接获取的数据。像在互联网上的很多例子,但我似乎无法理解什么是错误。我认为这是不正确的PHP文件,虽然它可以。我问你,程序员帮助理解为什么应用程序不起作用。下面我带了所有文件: 正在尝试读取数据http://ksupulse.tk/get_all.php

的json链接

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文件:

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 + "\n");
            }
            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;

    }
}

这是我担心的错误:

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:54.748:E / Trace(1850):错误打开跟踪文件:没有这样的   文件或目录(2)11-22 18:37:57.448:E / JSON Parser(1850):错误   解析数据org.json.JSONException:java.lang.String类型的值   无法转换为JSONObject 11-22 18:37:57.448:   D / AndroidRuntime(1850):关闭VM 11-22 18:37:57.460:   W / dalvikvm(1850):threadid = 1:线程退出未捕获的异常   (组= 0xa6265288)11-22 18:37:57.468:E / AndroidRuntime(1850):致命   EXCEPTION:main 11-22 18:37:57.468:E / AndroidRuntime(1850):   java.lang.RuntimeException:无法启动活动   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):引起: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更多11-22   18:57:04.626:E / JSON Parser(1888):解析数据时出错   org.json.JSONException:java.lang.String类型的值不能   转换为JSONObject 11-22 18:57:04.626:D / AndroidRuntime(1888):   关闭VM 11-22 18:57:04.626:W / dalvikvm(1888):threadid = 1:   线程退出与未捕获的异常(组= 0xa6265288)11-22   18:57:04.626:E / AndroidRuntime(1888):致命异常:主要11-22   18:57:04.626:E / AndroidRuntime(1888):java.lang.RuntimeException:   无法开始活动   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):引起: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 个答案:

答案 0 :(得分:0)

  1. http://ksupulse.tk/get_all.php不起作用,堆栈跟踪显示“No such file”,因此请确保传递正确的链接。
  2. 使用http://www.jsoneditoronline.org/等网站查看确切的内容。在解析JSON时,错误发生在MainActivity类中。 “解析数据时出错org.json.JSONException:java.lang.String类型的值无法转换为JSONObject”。你的行JSONObject c = user.getJSONObject(0);需要传入的字符串而不是“0”。
  3. 旁注: 在Android的主线程上进行网络调用并不是一种好习惯。使用AsyncTask。