1

i am getting JSON data from http://abinet.org/?json=1 and displaying the titles in a ListView. the code is working fine but the problem is, it is skipping few titles in my ListView and one title is being repeated.

You can see the json data from url given above by copy paste it in JSON editor online http://www.jsoneditoronline.org/
i want titles in the "posts" array to be displayed in ListView, however it is being displayed like this:

enter image description here

if you see the JSON data from the link above, its missing like 3 titles (they should come between the first and second title) and 5th title is being repeated. Dont know why this is happening. What minor adjustments i need to do? Please help me.

this is my code :

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);

    }



   }

 } 

this is my JsonParser class (although its not required):

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;
}
} 

and this is adapter class:

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;
}
}

Please help me. I am stuck at this for more than a week now. I think there is just something to be changed in my MainActivity class.

2
  • Could you post the GetContacts Async method? What do you pass into your onPostExecute?
    – BigT
    May 27, 2014 at 22:04
  • GetContacts Async method is in the first code. In my onPostExecute i just set the adapter. The adapter puts all the titles in the listview. May 27, 2014 at 22:10

1 Answer 1

1

Some of the 10 (well today there are 10 ) 'titles' have no 'attachments'. Some have one and some have two. There are only 5 titles wich have one or two images. You only create a new

HashMap<String, Object> contact

if there are attachments. (The attachment are the images). You should create the 'contact' before you enter the attachments loop. Further you only need one image for each title. You can set the image null if there are no attachments. In getView if the image is null you set some image from your drawable res.

22
  • Damm !! i never noticed there were empty arrays in some of the attachments. now i see the problem. so now how am i suppose to get the images. The image url is also in the "content" tag of "posts array" but that has more things in it. Is it possible to get only the image url (which is the first line of content) from it? Btw thanks a lot for the help!! May 28, 2014 at 9:35
  • You just have to do the changes I suggested. It will take you five minutes.
    – greenapps
    May 28, 2014 at 9:38
  • i cannot set images from drawables. its a news website. The news titles will change daily. i have to get images from the url. those url's which are not given in attachment how am i suppose to do get from content setcion? May 28, 2014 at 9:48
  • You only set one from drawable if there is no image specified. When attachments.size() == 0. Otherwise you download the specified image as you do now. Then what would you display if there is no image specified? Of course the news changes dayly. Other titles othes images. Everybody knows that.
    – greenapps
    May 28, 2014 at 9:51
  • there might not be image url in the attachment for some titles but for those titles i can get the image url from the "concent" tag. the content tag also has the image url in it. May 28, 2014 at 9:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.