我的问题是我的JSON在toast中返回的内容。吐司是让我知道查询是成功的。问题是toast被触发,这意味着查询成功,但它不包含Success []以外的任何内容。成功的查询应该以成功[JSON RESULTS HERE]的形式返回。
-
更新:我收到org.json.JSONException:当我运行logCat时,org.json.JSONObject.get(JSONObject.java:354)的联盟没有值。
可能会发生什么?有没有人有任何解决方案?
JSON
{"version":"1.0","leagues":{"league":[{"homeURL":"http://www.myfantasyleague.com/2013/home/18752","name":"Northern Wisconsin Premier FFL","id":"18752"},{"homeURL":"http://www.myfantasyleague.com/2013/home/36678","name":"Central Wisconsin Fantasy Football League","id":"36678"},{"homeURL":"http://www.myfantasyleague.com/2013/home/37766","name":"On Wisconsin","id":"37766"},{"homeURL":"http://www.myfantasyleague.com/2013/home/49677","name":"Wisconsin's Premier Dynasty Football League","id":"49677"}]},"encoding":"ISO-8859-1"}
主要活动
public final static String BaseUrl="DUMMYURL";
ArrayList<DEPT_HOLD> deptList=new ArrayList<DEPT_HOLD>();
private class GetDeptAyncTask extends AsyncTask<Hashtable<String,String>,Void,String>{
// Parse in background
@Override
protected String doInBackground(Hashtable<String,String>... params) {
@SuppressWarnings("rawtypes")
Hashtable ht=params[0];
@SuppressWarnings("unchecked")
String json=HelperHttp.getJSONResponseFromURL(BaseUrl+"ENDOFDUMMYURL", ht);
if(json!=null) parseJsonString(deptList,json);
else {
return "Invalid Company Id";
}
return "SUCCESS";
}
// Parse JSON
protected void parseJsonString(ArrayList<DEPT_HOLD> deptList,String json) {
try {
JSONObject top = new JSONObject(json);
JSONObject leagues = (JSONObject) top.get("leagues");
JSONArray array = (JSONArray) leagues.get("league");
for(int i = 0; i < array.length(); i++) {
JSONObject j = array.getJSONObject(i);
DEPT_HOLD d = new DEPT_HOLD();
d.two = j.optString("name","");
d.one = j.optString("id","");
deptList.add(d);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
// Execute post
@Override
protected void onPostExecute(String result) {
if("SUCCESS".equals(result)) {
Toast.makeText(LeaguesTemporary.this, "Success "+deptList.size, Toast.LENGTH_LONG).show();
DeptArrayAdapter adapter=new DeptArrayAdapter(LeaguesTemporary.this,R.id.text1,deptList);
ListView listv=(ListView)findViewById(R.id.lv);
listv.setAdapter(adapter);
}
else{}
}
}
吐司
Toast.makeText(MainActivity.this, "Success "+deptList.size(), Toast.LENGTH_LONG).show();
DEPT_HOLD.java
public class DEPT_HOLD {
public String two;
public String one;
}
DeptArrayAdapter
public class DeptArrayAdapter extends ArrayAdapter<DEPT_HOLD>{
private Context context;
ArrayList<DEPT_HOLD> dataObject;
public DeptArrayAdapter(Context context, int textViewResourceId,
ArrayList<DEPT_HOLD> dataObject) {
super(context, textViewResourceId, dataObject);
this.context=context;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView=convertView;
if(rowView==null){
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.row_layout, parent, false);
}
TextView textView = (TextView) rowView.findViewById(R.id.text1);
TextView textView1 = (TextView) rowView.findViewById(R.id.text2);
textView.setText(""+getItem(position).one);
textView1.setText(""+getItem(position).two);
return rowView;
}
}
HelperHttp
public class HelperHttp {
public static HttpClient httpclient;
private static List<NameValuePair> buildNameValuePair(Hashtable<String, String> httpPost){
if(httpPost==null) return null;
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
Enumeration<String> keys=httpPost.keys();
while(keys.hasMoreElements()){
String key = (String)keys.nextElement();
String value = (String)httpPost.get(key);
BasicNameValuePair nv=new BasicNameValuePair(key,value);
nvps.add(nv);
}
return nvps;
}
private static String buildGetUrl(List<NameValuePair> params, String url){
String paramString = URLEncodedUtils.format(params, "utf-8");
if(!url.endsWith("?"))
url += "?";
url+=paramString;
return url;
}
public static DefaultHttpClient getThreadSafeClient() {
if (httpclient != null)
return (DefaultHttpClient) httpclient;
HttpParams params = new BasicHttpParams();
ConnManagerParams.setMaxTotalConnections(params, 100);
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
// Create and initialize scheme registry
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(
new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
httpclient = new DefaultHttpClient(cm, params);
return (DefaultHttpClient) httpclient;
}
public static String getJSONResponseFromURL(String url, Hashtable<String, String> httpGetParams){
String json_string="";
List<NameValuePair> nvps=buildNameValuePair(httpGetParams);
url=buildGetUrl(nvps,url);
System.out.println("URL==>"+url);
InputStream is = null;
try{
HttpGet httpget = new HttpGet(url);
HttpResponse response = getThreadSafeClient().execute(httpget);
HttpEntity entity = response.getEntity();
is = entity.getContent();
BufferedReader reader=new BufferedReader(new InputStreamReader(is),8192);
String line=null;
while((line=reader.readLine())!=null){
json_string=json_string+line;
}
response.getEntity().consumeContent();
System.out.println("Json Response==>"+json_string);
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
return null;
}
return json_string;
}
}
答案 0 :(得分:0)
您的字符串比较不正确。而不是
result=="SUCCESS"
使用
"SUCCESS".equals(result)
(或者甚至更好,返回一个布尔值)
答案 1 :(得分:0)
除了比较问题(由@ njzk2确定)之外,我认为您忘记打印列表的大小。
变化:
Toast.makeText(MainActivity.this, "Success "+deptList, Toast.LENGTH_LONG).show();
对此:
Toast.makeText(MainActivity.this, "Success "+deptList.size(), Toast.LENGTH_LONG).show();
答案 2 :(得分:0)
也许您使用==来测试字符串相等性,并且“SUCCESS”共享相同的常量字符串,因此您总是得到假的True结果。尝试result.equals(“SUCCESS”)并再次运行。
答案 3 :(得分:0)
尝试如下: -
try {
JSONObject jObject = new JSONObject(jsonString);
JSONObject jLeagues = jObject.getJSONObject("leagues");
JSONArray jLeague = jLeagues.getJSONArray("league");
deptList = new ArrayList<DEPT_HOLD>();
for (int i = 0; i < jLeague.length(); i++) {
JSONObject jl = jLeague.getJSONObject(i);
deptList.add(new DEPT_HOLD(jl.getString("name")));
deptList.add(new DEPT_HOLD(jl.getString("id")));
deptList.add(new DEPT_HOLD(jl.getString("homeURL")));
}
StringBuilder totalDept = new StringBuilder();
for (int i = 0; i < deptList.size(); i++) {
DEPT_HOLD dept = deptList.get(i);
String value = dept.getName();
totalDept.append(value + ", \n");
}
Toast.makeText(ExampleJSONActivity.this, "success " + totalDept,
Toast.LENGTH_LONG).show();
} catch (Exception e) {
// TODO: handle exception
}
DEPT_HOLD: -
public class DEPT_HOLD {
private String name;
public DEPT_HOLD(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}