无法完全从Json获取数据

时间:2014-05-27 21:59:46

标签: android json parsing listview

我从 http://abinet.org/?json=1 获取JSON数据并在ListView中显示标题。代码工作正常,但问题是,它在我的ListView中跳过了几个标题,并且正在重复一个标题。

您可以通过在线JSON编辑器中将其复制粘贴到上面给出的网址中查看json数据http://www.jsoneditoronline.org/
我想在"帖子"要在ListView中显示的数组,但它显示如下:

enter image description here

如果您看到上面链接中的JSON数据,则会丢失3个标题(它们应该介于第一个和第二个标题之间)和第5个标题正在重复。不知道为什么会这样。我需要做些什么小调整?请帮我。

这是我的代码:

public class MainActivity extends Activity {



// URL to get contacts JSON
private static String url = "http://abinet.org/?json=1";

// JSON Node names
private static final String TAG_POSTS = "posts";
static final String TAG_TITLE = "title";



private ProgressDialog pDialog;
JSONArray contacts = null;
TextView img_url;


ArrayList<HashMap<String, Object>> contactList;
ListView lv;
LazyAdapter adapter;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    lv = (ListView) findViewById(R.id.newslist);

    contactList = new ArrayList<HashMap<String, Object>>();

    new GetContacts().execute();
}



private class GetContacts extends AsyncTask<Void, Void, Void> {

     protected void onPreExecute() {
         super.onPreExecute();
         // Showing progress dialog
         pDialog = new ProgressDialog(MainActivity.this);
         pDialog.setMessage("Please wait...");
         pDialog.setCancelable(false);
         pDialog.show();

     }


    protected Void doInBackground(Void... arg0) {



        // Making a request to url and getting response

        JSONParser jParser = new JSONParser();
        // Getting JSON from URL
        JSONObject jsonObj = jParser.getJSONFromUrl(url);


       // if (jsonStr != null) {
            try {


                // Getting JSON Array node
                contacts = jsonObj.getJSONArray(TAG_POSTS);




                // looping through All Contacts
                for (int i = 0; i < contacts.length(); i++) {
                  // JSONObject c = contacts.getJSONObject(i);


                   JSONObject posts = contacts.getJSONObject(i);
                   String title = posts.getString(TAG_TITLE).replace("&#8217;", "'");
                   JSONArray attachment = posts.getJSONArray("attachments");
                     for (int j = 0; j< attachment.length(); j++){
                   JSONObject obj = attachment.getJSONObject(j);
                   JSONObject image = obj.getJSONObject("images");

                   JSONObject image_small = image.getJSONObject("thumbnail");

                   String  imgurl = image_small.getString("url");  


                    HashMap<String, Object> contact = new HashMap<String, Object>();
                    contact.put("image_url", imgurl);

                    contact.put(TAG_TITLE, title);
                    contactList.add(contact);
                     }    

               }
            } catch (JSONException e) {
                e.printStackTrace();
            }


        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();



        adapter=new LazyAdapter(MainActivity.this, contactList);
        lv.setAdapter(adapter);

    }



   }

 } 

这是我的JsonParser类(虽然不是必需的):

public JSONParser() {
}
 public JSONObject getJSONFromUrl(String url) {
  // Making HTTP request
  try {
    // defaultHttpClient
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);
    HttpResponse httpResponse = httpClient.execute(httpPost);
    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"), 8);
   StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
      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 JSONObject(json);
  } catch (JSONException e) {
    Log.e("JSON Parser", "Error parsing data " + e.toString());
 }
 // return JSON String
 return jObj;
}
} 

这是适配器类:

public class LazyAdapter extends BaseAdapter {

private Activity activity;
private ArrayList<HashMap<String, Object>> data;
private static LayoutInflater inflater=null;


public LazyAdapter(Activity a,ArrayList<HashMap<String, Object>> d) {
    activity = a;
    data=d;
    inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

}

public int getCount() {
    return data.size();
}

public Object getItem(int position) {
    return position;
}

public long getItemId(int position) {
    return position;
}

public View getView(int position, View convertView, ViewGroup parent) {
    View vi=convertView;
    if(convertView==null)
        vi = inflater.inflate(R.layout.third_row, null);

    TextView title = (TextView)vi.findViewById(R.id.headline3); // title
    SmartImageView iv =  (SmartImageView) vi.findViewById(R.id.imageicon);


   HashMap<String, Object> song = new HashMap<String, Object>();
    song = data.get(position);

    // Setting all values in listview
    title.setText((CharSequence) song.get(MainActivity.TAG_TITLE));

    iv.setImageUrl((String) song.get("image_url"));
  thumb_image);
    return vi;
}
}

请帮帮我。我现在已经坚持了一个多星期了。我认为我的MainActivity课程中只有一些内容需要改变。

1 个答案:

答案 0 :(得分:1)

10个(今天有10个)“标题”中的一些没有“附件”。有些有一个,有些有两个。只有5个标题,其中有一个或两个图像。您只需创建一个新的

HashMap<String, Object> contact

如果有附件。 (附件是图像)。您应该在进入附件循环之前创建“联系人”。此外,每个标题只需要一个图像。如果没有附件,您可以将图像设置为null。在getView中,如果图像为null,则从可绘制的res中设置一些图像。

相关问题