【发布时间】: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 字符串 -
我发现 json 数据是有效的,因为我从 php process json encode 获取数据。
-
根据@ρяσѕρєяK 的评论,JSON 数组无效。我认为你在那里缺少一些逗号。尝试检查您的 json here
-
如果您有服务器响应,这是错误的做法,那么您必须解析它并将其设置为 arraylist,然后使用该数组列表设置适配器,然后将其设置为解决问题的微调器
标签: android arrays json android-spinner