从JSON将数据填充到微调器时出错

时间:2014-08-27 07:03:29

标签: android json android-asynctask android-spinner

我想从php服务器获取数据并使用spinner填充它。我正在关注this tutorial

我无法理解错误本身。任何人都可以解释我的代码有什么问题吗?

我是JSON和androi JSON编程的新手。

这是来自服务器(输出)的JSON数据

[{"id":"1","name":"F"},{"id":"2","name":"D"},{"id":"3","name":"E"}]

这是我的asynctask文件

 private class DownloadJSON extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {
            // Locate the WorldPopulation Class
            //   world = new ArrayList<WorldPopulation>();
            // Create an array to populate the spinner
            worldlist = new ArrayList<String>();
            // JSON file URL address
            jsonobject = JSONfunctions.getJSONfromURL("http://192.168.0.102/test/Get_spinner_color.php");

            try {
                // Locate the NodeList name
               // jsonarray = jsonobject.getJSONArray("");
                for (int i = 0; i < jsonarray.length(); i++) {
                    jsonobject = jsonarray.getJSONObject(i);

                    // WorldPopulation worldpop = new WorldPopulation();

                    ////  worldpop.setRank(jsonobject.optString("rank"));
                    //  worldpop.setCountry(jsonobject.optString("country"));
                    //  worldpop.setPopulation(jsonobject.optString("population"));
                    //   worldpop.setFlag(jsonobject.optString("flag"));
                    //   world.add(worldpop);

                    // Populate spinner with country names
                    worldlist.add(jsonobject.getString("name"));

                }
            } catch (Exception e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void args) {
            // Locate the spinner in activity_main.xml


            // Spinner adapter
            color1.setAdapter(new ArrayAdapter<String>(QuickSearch.this,
                    android.R.layout.simple_spinner_dropdown_item, worldlist));


        }

这是我的JSON函数文件

  

公共类JSONfunctions {

public static JSONObject getJSONfromURL(String url) {
    InputStream is = null;
    String result = "";
    JSONObject jArray = null;

    // Download JSON data from URL
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();

    } catch (Exception e) {
        Log.e("log_tag", "Error in http connection " + e.toString());
    }

    // Convert response to string
    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();
        result = sb.toString();
    } catch (Exception e) {
        Log.e("log_tag", "Error converting result " + e.toString());
    }

    try {

        jArray = new JSONObject(result);
    } catch (JSONException e) {
        Log.e("log_tag", "Error parsing data " + e.toString());
    }

    return jArray;
} }

这是我从logcat

的错误
08-27 12:24:13.930  19976-20028/com.diamond.traders E/log_tag﹕ Error parsing data org.json.JSONException: Value [{"id":"1","name":"F"},{"id":"2","name":"D"},{"id":"3","name":"E"}] of type org.json.JSONArray cannot be converted to JSONObject
08-27 12:24:13.930  19976-20028/com.diamond.traders W/dalvikvm﹕ threadid=13: thread exiting with uncaught exception (group=0x41554ba8)
08-27 12:24:13.940  19976-20028/com.diamond.traders E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #3
    Process: com.diamond.traders, PID: 19976
    java.lang.RuntimeException: An error occured while executing doInBackground()
            at android.os.AsyncTask$3.done(AsyncTask.java:300)
            at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
            at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
            at java.util.concurrent.FutureTask.run(FutureTask.java:242)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:841)
     Caused by: java.lang.NullPointerException: println needs a message
            at android.util.Log.println_native(Native Method)
            at android.util.Log.e(Log.java:232)
            at com.diamond.traders.QuickSearch$DownloadJSON.doInBackground(QuickSearch.java:245)
            at com.diamond.traders.QuickSearch$DownloadJSON.doInBackground(QuickSearch.java:215)
            at android.os.AsyncTask$2.call(AsyncTask.java:288)
            at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:841)

3 个答案:

答案 0 :(得分:0)

错误

  

org.json.JSONArray无法转换为JSONObject

RES

[                         // JSONArray
    {                     // JSONObject 
        "id": "1", 
        "name": "F"
    },
    {
        "id": "2",
        "name": "D"
    },
    {
        "id": "3",
        "name": "E"
    }
]

更改为..

JSONArray jArray = new JSONArray(result);
for(int i = 0; i < jArray.length(); i++)
{
    JSONObject json = jArray.getJSONObject(i);
    String name = json.getString("name");
}

因为您的回复以JSONArray而不是JSONObject

开头

答案 1 :(得分:0)

此错误

 Log.e("Error", e.getMessage());

打印因为try块中的代码错误。您的回复中的第一个标记是JSONArray,因此您需要通过

进行更改
JSONArray jArray = new JSONArray(result);

为此你必须在JSONfunctions类中更改你的方法并返回JSONArray而不是JSONObject。

答案 2 :(得分:0)

将此代码替换为您自己的JSON代码。

public class JSONfunctions {

public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;

// Download JSON data from URL
try {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();
    is = entity.getContent();

} catch (Exception e) {
    Log.e("log_tag", "Error in http connection " + e.toString());
}

// Convert response to string
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();
    result = sb.toString();
} catch (Exception e) {
    Log.e("log_tag", "Error converting result " + e.toString());
}

try {

    jArray = new JSONArray(result);

       for(int i = 0; i < jArray.length(); i++)
     {
        JSONObject json = jArray.getJSONObject(i);

         String name= json.getString("name");

       // make String array to store names
       // Because Spinner need Array as a data

       String[] string[]={}; // Declare and Initialize String array
       string[i]=name; //use this array to show data in spinner

     }

} catch (JSONException e) {
    Log.e("log_tag", "Error parsing data " + e.toString());
}

return jArray;

}}