将JSON响应中的数据放入适配器(ListView)时出错

时间:2017-12-27 01:29:49

标签: android listview android-arrayadapter

我最近学会了如何使用ListView,所以我对它并不十分熟悉。将JSON响应中的数据添加到ListView时,我遇到了问题。当我将硬编码的字符串添加到ListView中时,它工作正常。但是在从JSON响应中放入数据时什么都不给。 这是我的活动(SupportedAds.java

public class SupportedAds extends AppCompatActivity {

String[] Title;
String[] Content;
ListView list;
Offers offer;
ArrayList<Offers> offers = new ArrayList<>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_supported_ads);
    list = findViewById(R.id.list);


/* Getting Supported Ads from the api*/
    RequestQueue queue = Volley.newRequestQueue(SupportedAds.this);
    final String URL_SUPPORTED_ADS = "http://lb-89089438.us-east-2.elb.amazonaws.com/api/offers";

    StringRequest postRequest = new StringRequest(Request.Method.POST, URL_SUPPORTED_ADS,
            new Response.Listener<String>()
            {
                @Override
                public void onResponse(String response) {
                    JSONArray jsonResponse;
                    String offerContent;
                    String offerTitle;
                    // response
                    Log.wtf("POST api/offers", response);
                    try {
                        jsonResponse = new JSONArray(response);
                        Title = new String[jsonResponse.length()];
                        Content = new String[jsonResponse.length()];

                        for(int i=0; i < jsonResponse.length(); i++)
                        {
                            JSONObject jsonobject = jsonResponse.getJSONObject(i);
                            offerContent  = jsonobject.getString("offercontent");
                            offerTitle = jsonobject.getString("offertitle");

                            offer = new Offers();
                            offer.setTitle(offerTitle);
                            offer.setContent(offerContent);
                            Log.e("Title", offerTitle); // shows correct values. No problem in JSON parsing or POST request
                            Log.e("Content", offerContent); // shows correct values. No problem in JSON parsing or POST request
                            offers.add(offer);
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener()
            {
                @Override
                public void onErrorResponse(VolleyError error) {
                    // error
                    Log.d("POST api/offers", error.toString());
                }
            }
    ) {
        @Override
        protected Map<String, String> getParams()
        {
            return new HashMap<>();
        }
    };
    queue.add(postRequest);
/* Getting Supported Ads from the api*/

    /* If i use these hard coded values, it works fine */
    /*offer = new Offers();
    offer.setTitle("Ad1");
    offer.setContent("Advertisement #01 Description");
    offers.add(offer);

    offer = new Offers();
    offer.setTitle("Ad2");
    offer.setContent("Advertisement #02 Description");
    offers.add(offer);

    offer = new Offers();
    offer.setTitle("Ad3");
    offer.setContent("Advertisement #03 Description");
    offers.add(offer);*/

    list.setAdapter(new MyAdapter(getApplicationContext(), offers));

}

private class MyAdapter extends BaseAdapter {

    private Context context;
    private ArrayList<Offers> offers;

    public MyAdapter(Context context, ArrayList<Offers> offers) {
        this.context = context;
        this.offers = offers;
    }

    @Override
    public int getCount() {
        return offers.size();
    }

    @Override
    public Object getItem(int position) {
        return offers.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        TwoLineListItem twoLineListItem;

        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            twoLineListItem = (TwoLineListItem) inflater.inflate(
                    android.R.layout.simple_list_item_2, null);
        } else {
            twoLineListItem = (TwoLineListItem) convertView;
        }

        TextView text1 = twoLineListItem.getText1();
        TextView text2 = twoLineListItem.getText2();

        text1.setText(offers.get(position).getTitle());
        text2.setText(offers.get(position).getContent());

        return twoLineListItem;
    }
}
}

当我尝试使用来自JSON响应的数据时(没有显示数据 - 抱歉为背景颜色) nothing being displayed

当我使用硬编码的字符串时(在这种情况下工作正常 - 抱歉为背景颜色) works fine in this case

布局文件(activity_supported_ads.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:background="@color/lightgreen"
tools:context="com.fyp.mrisecondscreen.activity.SupportedAds">

<ListView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/list">

</ListView>

</RelativeLayout>

来自POST请求的响应(我确信我在JSON响应解析中没有问题,因为我使用Log.e来显示提取的值并且它们是正确的)

[
{
"offercontent": "Sample Description",
"offertitle": "Ad 1",

},
{
"offercontent": "42 inch TV",
"offertitle": "TV ",

},
{
"offercontent": "Coke Ad Offer description here",
"offertitle": "Coke",

},
{
"offercontent": "Cola Ad Offer description here",
"offertitle": "Cola Offer",

},
{
"offercontent": "Nestle Ad Offer description here",
"offertitle": "Nestle Cerelac Offer",
},
{
"offercontent": "New Year sale",
"offertitle": "Chocolate",

}
]

请帮助我,花了好几个小时后我无法解决..

1 个答案:

答案 0 :(得分:0)

您的代码list.setAdapter(new MyAdapter(getApplicationContext(), offers));在请求完成之前执行,因此没有要显示的数据。该行应在onResponse方法内完成解析后执行。