【问题标题】:populate json array in android spinner在 android spinner 中填充 json 数组
【发布时间】:2016-05-06 07:13:34
【问题描述】:

我在 android spinner 中解析 json 时遇到问题。我已经尝试过下面列出的代码,但我在微调器中得到了完整的 json 数组,如屏幕截图

我的 Json 数组

{"Department":[{"1":"Computer"},{"2":"IT"},{"3":"Civil"}]} // like this type json string

我的代码

public class GetDropdownItems extends AsyncTask<Void, Void, String[]> {
        public GetDropdownItems() {
            super();
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            Log.i("MY_NETWORK", "first");
        }

        @Override
        protected String[] doInBackground(Void... params) {
            StringBuilder sbstaffdep = new StringBuilder();
            String staffdepURL = StaticDataEntity.URL_GETDEP;
            String charset = "UTF-8";  // Or in Java 7 and later, use the constant: java.nio.charset.StandardCharsets.UTF_8.name()
            URLConnection connectionstaffDep = null;
            try {
                connectionstaffDep = new URL(staffdepURL).openConnection();
            } catch (IOException e) {
                e.printStackTrace();
            }

            connectionstaffDep.setDoOutput(true); // Triggers POST.
            connectionstaffDep.setRequestProperty("Accept-Charset", charset);
            connectionstaffDep.setConnectTimeout(6000);

            InputStream responsestaffDep = null;
            try {
                responsestaffDep = connectionstaffDep.getInputStream();
            } catch (IOException e) {
                e.printStackTrace
                        ();
                return new String[]{"unreachable"};

            }

            BufferedReader brstaffDep = new BufferedReader(new InputStreamReader(responsestaffDep));
            String readstaffDep;
            try {

                while ((readstaffDep = brstaffDep.readLine()) != null) {
                    //System.out.println(read);
                    sbstaffdep.append(readstaffDep);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {

                brstaffDep.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            String[] finaldata = new String[1];
            finaldata[0] = sbstaffdep.toString();
            return finaldata;
        }

        @Override
        protected void onPostExecute(String[] s) {
            super.onPostExecute(s);

            if (s[0].equals("unreachable")) {
                new SweetAlertDialog(SignUpStaff.this, SweetAlertDialog.ERROR_TYPE)
                        .setTitleText("Oops...")
                        .setContentText("Unable to connect to server ! \n Please try again later.")
                        .setCancelText("Ok")
                        .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                sweetAlertDialog.cancel();
                            }
                        })
                        .show();
                return;
            }
            Log.i("MY_NETWORK", s.toString());
            String[] dataofdropdowndep = s[0].split(",");
            ArrayAdapter<String> adapterdep = new ArrayAdapter<String>(SignUpStaff.this, android.R.layout.simple_list_item_1, dataofdropdowndep);
            adapterdep.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            dropstaffdep.setAdapter(adapterdep);
        }
    }

【问题讨论】:

  • {"Department":[{"1":"Computer"}{"2":"IT"}{"3":"Civil"}]} 不是有效的 json 字符串
  • 试试这个教程:androidbegin.com/tutorial/… 或查看这个参考:stackoverflow.com/questions/12906681/…
  • 我发现 json 数据是有效的,因为我从 php process json encode 获取数据。
  • 根据@ρяσѕρєяK 的评论,JSON 数组无效。我认为你在那里缺少一些逗号。尝试检查您的 json here
  • 如果您有服务器响应,这是错误的做法,那么您必须解析它并将其设置为 arraylist,然后使用该数组列表设置适配器,然后将其设置为解决问题的微调器

标签: android arrays json android-spinner


【解决方案1】:
public class GetDropdownItems extends AsyncTask<Void, Void, String> {
        public GetDropdownItems() {
            super();
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            Log.i("MY_NETWORK", "first");
        }

        @Override
        protected String doInBackground(Void... params) {
            StringBuilder sbstaffdep = new StringBuilder();
            String staffdepURL = StaticDataEntity.URL_GETDEP;
            String charset = "UTF-8";  // Or in Java 7 and later, use the constant: java.nio.charset.StandardCharsets.UTF_8.name()
            URLConnection connectionstaffDep = null;
            try {
                connectionstaffDep = new URL(staffdepURL).openConnection();
            } catch (IOException e) {
                e.printStackTrace();
            }

            connectionstaffDep.setDoOutput(true); // Triggers POST.
            connectionstaffDep.setRequestProperty("Accept-Charset", charset);
            connectionstaffDep.setConnectTimeout(6000);

            InputStream responsestaffDep = null;
            try {
                responsestaffDep = connectionstaffDep.getInputStream();
            } catch (IOException e) {
                e.printStackTrace
                        ();
                return "unreachable";

            }
try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    responsestaffDep, "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.d("-------------", json);
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }


            return json;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);

            if (s.equals("unreachable")) {
                new SweetAlertDialog(SignUpStaff.this, SweetAlertDialog.ERROR_TYPE)
                        .setTitleText("Oops...")
                        .setContentText("Unable to connect to server ! \n Please try again later.")
                        .setCancelText("Ok")
                        .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                sweetAlertDialog.cancel();
                            }
                        })
                        .show();
                return;
            }
            Log.i("MY_NETWORK", s.toString());
            Json js=new Json(s);
JSONArray array=js.getJSONArray("Department");
for(JSONArray b:array){
// traverse array here
}
            ArrayAdapter<String> adapterdep = new ArrayAdapter<String>(SignUpStaff.this, android.R.layout.simple_list_item_1, dataofdropdowndep);
            adapterdep.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            dropstaffdep.setAdapter(adapterdep);
        }
    }

【讨论】:

    【解决方案2】:

    HI 从服务器更改您的 Json 响应,或者您可以手动更改。

    这是你的格式:

    {"Department"
     [
      {
       "1": "Computer"
      },
      {
       "2": "IT"
      },
      {
       "3": "Civil"
      }
     ]
    }
    

    请在线查看任何 json 查看器格式。

    【讨论】:

      【解决方案3】:

      这种类型的json数据: 检查这个 json 数组:

      {
          "schools": [{
              "Name": "Hill View Elementary",
              "SchoolID": "HVE"
          }, {
              "Name": "Mill View",
              "SchoolID": "MVE"
          }, {
              "Name": "Big School",
              "SchoolID": "BSC"
          }]
      }
      

      你的错误是你没有在两个对象之间放置逗号

      【讨论】:

        【解决方案4】:

        你获取 Json 文件的方式不对,已经有 Json 类可以单独获取每个数组、对象或键。

        org.json 是我们将与JSONArrayJSONObject 类一起使用的库。

        在我们开始之前,你应该对 Json 文件方案有一个基本的了解:

        "name":{}这是用{}符号表示的数组语法,这个数组可以存放数组、对象或键。

        [] 代表和对象,它也可以保存数组和键,但它没有名称。

        "key":"value" 现在是键类型,它可以保存您想要的数据或值,并有一个键来按名称检索它。

        现在这里有一段代码来获取您的文件并单独获取 Json 文件的每个部分,然后您可以根据需要填充它。

        import java.io.BufferedReader;
        import java.io.IOException;
        import java.io.InputStream;
        import java.io.InputStreamReader;
        
        import org.json.JSONArray;
        import org.json.JSONException;
        import org.json.JSONObject;
        
        import android.content.res.Resources;
        
        public class Fetch {
        
            final private static String DEPARTMENT = "Department";
            String [] departments ;
        
        
            public void fetch(Resources r , int resourceID) {
                String JsonString = readStringFromRaw(r, resourceID);
                //the whole josn file is a json object even if it starts with { and ends with } so...
                try {
        
                    JSONObject mainObject = new JSONObject(JsonString);
                    // the JSONObject throws a JSONException if there is something wrong with the syntax
                    JSONArray department = mainObject.getJSONArray(DEPARTMENT);
        
                    int length = department.length();
        
                    departments = new String[length];
        
                    JSONObject object;
                    for(int i = 0 ; i < length ; i++){
                    object = department.getJSONObject(i);
                    departments[0] = object.getString(""+i+1);
                    //this because you tagged the keys with 1 , 2 , 3 and so on.. so it has the value of the object that it is in + 1 . 
                    //the reason I put "" empty quotations is because I want it a string so this is a way to cast the numbers to strings .
        
                    }
        
        
                } catch (JSONException e) {
                    e.printStackTrace();
                }
        
            }
        
            public static String readStringFromRaw(Resources r, int resourceID) {
                InputStream is = r.openRawResource(resourceID);
                BufferedReader br = new BufferedReader(new InputStreamReader(is));
                StringBuilder sb = new StringBuilder(1000);
                String line;
                try {
                    while ((line = br.readLine()) != null)
                        sb.append(line);
                    br.close();
                    is.close();
                    return sb.toString();
                } catch (IOException e) {
                    return e.getMessage();
                }
            }
        }
        

        通过这个类,您可以获得一个字符串数组,其中包含您想要的 json 文件的部门。

        数组和对象之间的层次结构非常重要,因此请记住,当您编写 json 文件时,可以更轻松地提取信息。

        【讨论】:

        • 顺便说一下,我已经测试了你提供的 Json 文件,它工作得非常好,只要你使用 json 编辑器就不会出错。
        猜你喜欢
        • 2016-10-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多