1

I have managed to created a JSON endpoint on my website. This JSON is fed into my android project,parsed and stored in a list view. The issue i'm having is that, rather than printing each JSON object in each element of the list, a JSON object is being added - making each element of the list longer.

An example of the list:

Data1

Data1 Data2

Data1 Data2 Data3

Data1 Data2 Data3 Data4

I am looking for:

Data1

Data2

Data3

My code is as follows, could anybody please be so kind as to point out where I may be going wrong?

public void setTextToTextView(JSONArray jsonArray){
        String s = "";
        CharSequence news_title = getResources().getText(R.string.news_title);
        ArrayList<String> arrayList = new ArrayList<String>();
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,R.layout.simplerow,R.id.rowTextView, arrayList);
        for (int i=0; i<jsonArray.length(); i++){
            JSONObject jsonResponse;
            try {
                jsonResponse = jsonArray.getJSONObject(i);
                s = s +
                        Html.fromHtml(news_title.toString())
                        +jsonResponse.getString("subject")+"\n"+
                        "Posted By :"+jsonResponse.getString("postedby")+"\n"+"\n";
                arrayList.add(s);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        Log.e("JSON Response:", arrayList.toString());
        arrayAdapter.add(s);
        this.newsResponseListView.setAdapter(arrayAdapter);
    }

1 Answer 1

0

the variable s is global inside the method setTextToTextView() and you are using it in loop as :

 s = s + Html.fromHtml(news_title.toString())
                        +jsonResponse.getString("subject")+"\n"+
                        "Posted By :"+jsonResponse.getString("postedby")+"\n"+"\n";

Therefore it appends previous data to next data.

What should I change?

Just remove String s (first declaration) and write this inside loop:

     String s =Html.fromHtml(news_title.toString())
                            +jsonResponse.getString("subject")+"\n"+
                            "Posted By :"+jsonResponse.getString("postedby")+"\n"+"\n";
     arrayList.add(s);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @VVJ, I don't know how I didn't notice that!

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.