Android 从JSON向微调器填充数据时出错

Android 从JSON向微调器填充数据时出错,android,json,android-asynctask,android-spinner,Android,Json,Android Asynctask,Android Spinner,我想从php服务器获取数据,并使用spinner填充它。我跟在后面 我无法理解错误本身。谁能解释一下我的代码有什么问题吗 我对JSON和AndroiJSON编程都是新手 这是我从服务器获得的JSON数据(输出) 这是我的异步任务文件 private class DownloadJSON extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void

我想从php服务器获取数据,并使用spinner填充它。我跟在后面

我无法理解错误本身。谁能解释一下我的代码有什么问题吗

我对JSON和AndroiJSON编程都是新手

这是我从服务器获得的JSON数据(输出)

这是我的异步任务文件

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


        }
这是我在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)
错误

无法将org.json.JSONArray转换为JSONObject

Res

改为

JSONArray jArray = new JSONArray(result);
for(int i = 0; i < jArray.length(); i++)
{
    JSONObject json = jArray.getJSONObject(i);
    String name = json.getString("name");
}
JSONArray jArray=新的JSONArray(结果);
for(int i=0;i
因为您的响应以
JSONArray
开头,而不是以
JSONObject
这个错误开头

 Log.e("Error", e.getMessage());
打印,因为try块中的代码错误。响应中的第一个标记是JSONArray,因此需要通过

JSONArray jArray = new JSONArray(result);

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

将此代码替换为您自己的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;
公共类JSONfunctions{
公共静态JSONObject getJSONfromURL(字符串url){
InputStream=null;
字符串结果=”;
JSONObject jArray=null;
//从URL下载JSON数据
试一试{
HttpClient HttpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(url);
HttpResponse response=httpclient.execute(httppost);
HttpEntity=response.getEntity();
is=entity.getContent();
}捕获(例外e){
e(“Log_标记”,“http连接错误”+e.toString());
}
//将响应转换为字符串
试一试{
BufferedReader reader=新的BufferedReader(新的InputStreamReader(
is,“iso-8859-1”),8);
StringBuilder sb=新的StringBuilder();
字符串行=null;
而((line=reader.readLine())!=null){
sb.追加(第+行“\n”);
}
is.close();
结果=sb.toString();
}捕获(例外e){
Log.e(“Log_标记”,“错误转换结果”+e.toString());
}
试一试{
jArray=新的JSONArray(结果);
for(int i=0;i

}}

我应该通过什么作为“结果”??我只想从json结果中获得名称担心我是json新手,我是否应该将php服务器的URL作为结果传递给JSONArray jArray=new JSONArray(result);?我应该通过什么作为“结果”??我只想要json结果中的名称,所以删除这一行Log.e(“Error”,e.getMessage());我再次阅读了你的答案三次,然后我修改了我的JSON函数代码,它将输出jsonarry,而不是abject,它成功了。谢谢你的帮助
 Log.e("Error", e.getMessage());
JSONArray jArray = new JSONArray(result);
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;