我有问题。我没有将JSONArray设置为Spinner。我的JSON外观["category1","category2","category3"]
如何将这个JSONArray转换为微调器?我不知道我的代码是否正常
public class Main extends Activity {
String urlCat = "http://tvapp.pcrevue.sk/categories.json";
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
JSONArray jsonArray = getJSONArrayFromUrl(urlCat);
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayUseLogoEnabled(false);
ArrayAdapter<String> spinnerMenu = new ArrayAdapter<String>(actionBar.getThemedContext(), android.R.layout.simple_list_item_1, jsonArray);
actionBar.setListNavigationCallbacks(spinnerMenu,
new ActionBar.OnNavigationListener() {
@Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
FragmentTransaction tx = getFragmentManager().beginTransaction();
switch (itemPosition) {
case 0:
tx.replace(android.R.id.content, new Tab1Fragment());
break;
case 1:
tx.replace(android.R.id.content, new Tab2Fragment());
break;
default:
break;
}
tx.commit();
return false;
}
});
}
public JSONArray getJSONArrayFromUrl(String url) {
InputStream is = null;
JSONArray jObj = null;
String json = "";
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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, "iso-8859-1"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
//json += line;
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 JSONArray(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
我需要你的帮助。 THX
答案 0 :(得分:1)
我在ArrayAdapter中找不到任何接受JSONArray对象的构造函数,如果您有任何疑问,请参考Array Adapter。
您需要传递List而不是JSONArray。 并且, 您正在执行UI线程的网络操作,因此您将获得 NetworkOnMainThread 例外。它适用于较低版本,但较高版本会抛出异常。尝试使用 AsyncTask 获取值或单独的线程
所以得到这样的列表
ArrayList<String> list = new ArrayList<String>();
for(int i=0; i<jsonArray.length(); i++) {
list.add(jsonArray.getString(i));
}
ArrayAdapter<String> spinnerMenu = new ArrayAdapter<String>(actionBar.getThemedContext(), android.R.layout.simple_list_item_1, list);
答案 1 :(得分:1)
第一个解决方案
实际上我没有在ArrayAdapter中找到任何需要JSONArray的构造函数。
如果您的JSONArray
拥有所有字符串元素,那么
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
List<String> listist = new ArrayList<String>();
String res = callGet("http://tvapp.pcrevue.sk/categories.json");
JSONArray jsonArray = new JSONArray(res);
for (int i = 0; i < jsonArray.length(); i++) {
try {
listist.add("" + jsonArray.get(i));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Log.e("", "listist.size() : " + listist.size());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String callGet(String urlString) {
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setSoTimeout(params, 10000);
HttpConnectionParams.setConnectionTimeout(params, 10000);
HttpClient httpclient = new DefaultHttpClient(params);
HttpGet httppost = new HttpGet(urlString);
try {
HttpResponse response = httpclient.execute(httppost);
return EntityUtils.toString(response.getEntity());
} catch (Exception e) {
return "";
}
}
}
我得到了我的logcat输出
03-17 21:49:36.821: E/(376): listist.size() : 10
第二个解决方案
您是否尝试使用GSON lib进行json解析?它将Java对象转换为JSON
表示形式。
List<String> listist = new ArrayList<String>();
iidList = new Gson().fromJson(jsonArray, List.class);
ArrayAdapter<String> spinnerMenu = new ArrayAdapter<String>(
actionBar.getThemedContext(),
android.R.layout.simple_list_item_1, listist);
答案 2 :(得分:0)
Spinners接受数组没有问题。因此,只需从json中提取java数组并将该数组传递给微调器。在线有很多关于如何将json转换为java数组的例子,例如How to parse a JSON and turn its values into an Array?。并使用java数组创建微调器:Android: Create spinner programmatically from array