JSON数据未出现在listview中

时间:2018-01-07 12:24:34

标签: android

我一直在尝试使用来自几个网址的JSON数据填充我的ListView。问题是,它没有出现在ListView中,尽管我的LogCat清楚地表明它已经收到了数据。看看下面的代码。

XML ListView:

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<ListView

    android:id="@android:id/list"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:drawSelectorOnTop="false"
    />
</LinearLayout>

ListView活动:

public ListView mListView;

private static final String EventNamesURL = 
"http://eventsweb23.000webhostapp.com/JSON/EventNames.json";
private static final String EventDatesURL = 
"http://eventsweb23.000webhostapp.com/JSON/EventDates.json";
private static final String EventPlacesURL = 
"http://eventsweb23.000webhostapp.com/JSON/codebeautify.json";
private static final String EventTimesURL = 
"http://eventsweb23.000webhostapp.com/JSON/EventTimes.json";
private static final String EventURLs = 
"http://eventsweb23.000webhostapp.com/JSON/EventURLs.json";
private static final String EventImagesURL = 
"http://eventsweb23.000webhostapp.com/JSON/EventImages.json";

ArrayList<String> NameList = new ArrayList<String>();
ArrayList<String> DatesList = new ArrayList<String>();
ArrayList<String> PlacesList = new ArrayList<String>();
ArrayList<String> TimesList = new ArrayList<String>();
ArrayList<String> URLList = new ArrayList<String>();
ArrayList<String> ImagesList = new ArrayList<String>();
ArrayList<String> EventList = new ArrayList<>();

public String title;
public String place;
public String imageUrl;
public String time;
public String date;
public String url;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_listview);

    Context context = this;
    mListView = (ListView) findViewById(android.R.id.list);
    EventsAdapter adapter = new EventsAdapter(context, EventList);
    mListView.setAdapter(adapter);
    adapter.notifyDataSetChanged();

    new FetchNameDataTask().execute(EventNamesURL);
    new FetchDateDataTask().execute(EventDatesURL);
    new FetchPlaceDataTask().execute(EventPlacesURL);
    new  FetchTimeDataTask().execute(EventTimesURL);
    new FetchURLDataTask().execute(EventURLs);
    new FetchImageDataTask().execute(EventImagesURL);


    setList();

    }





//Thread for fetching event names
public class FetchNameDataTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {

        //getCookieUsingCookieHandler();

        InputStream inputStream = null;
        String result = null;
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(params[0]);

        httpGet.setHeader("Content-Type", "application/json");

        try {

            HttpResponse response = client.execute(httpGet);
            inputStream = response.getEntity().getContent();


            // convert inputstream to string
            if (inputStream != null) {
                result = convertInputStreamToString(inputStream);
                Log.i("App", "Data received: " + result);

            } else
                result = "Failed to fetch data";

            return result;

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

        return null;
    }

    @Override
    protected void onPostExecute(String dataFetched) {
        //parse the JSON data and then display
        parseJSONEvents(dataFetched);
    }


    private String convertInputStreamToString(InputStream inputStream) 
    throws IOException, JSONException {
        BufferedReader bufferedReader = new BufferedReader(new 
   InputStreamReader(inputStream, "UTF-8"));
        StringBuilder responseStrBuilder = new StringBuilder();
        String line = "";
        String result = "";
        while ((line = bufferedReader.readLine()) != null)
            //responseStrBuilder.append(line + "\n");
            result += line;

        inputStream.close();
        return result;

    }

    public void parseJSONEvents(String data) {

        try {
            JSONArray jsonMainNode = new JSONArray(data);

            int jsonArrLength = jsonMainNode.length();

            for (int i = 0; i < jsonArrLength; i++) {
                //listviewActivity listviewActivity1 = new 
            listviewActivity();
                JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
                title = jsonChildNode.getString("event_name");
                //NameList.add(listviewActivity.title);
                EventList.add(title);

            }


        } catch (Exception e) {
            Log.i("App", "Error parsing data: " + e.getMessage());

        }

    }


}

//Thread for fetching event dates
private class FetchDateDataTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {

        //getCookieUsingCookieHandler();

        InputStream inputStream = null;
        String result = null;
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(params[0]);

        httpGet.setHeader("Content-Type", "application/json");

        try {

            HttpResponse response = client.execute(httpGet);
            inputStream = response.getEntity().getContent();


            // convert inputstream to string
            if (inputStream != null) {
                result = convertInputStreamToString(inputStream);
                Log.i("App", "Data received: " + result);

            } else
                result = "Failed to fetch data";

            return result;

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

        return null;
    }

    @Override
    protected void onPostExecute(String dataFetched) {
        //parse the JSON data and then display
        parseJSONEvents(dataFetched);
    }


    private String convertInputStreamToString(InputStream inputStream) 
    throws IOException, JSONException {
        BufferedReader bufferedReader = new BufferedReader(new 
    InputStreamReader(inputStream, "UTF-8"));
        StringBuilder responseStrBuilder = new StringBuilder();
        String line = "";
        String result = "";
        while ((line = bufferedReader.readLine()) != null)
            //responseStrBuilder.append(line + "\n");
            result += line;

        inputStream.close();
        return result;

    }

    private void parseJSONEvents(String data) {

        try {
            JSONArray jsonMainNode = new JSONArray(data);

            int jsonArrLength = jsonMainNode.length();

            for (int i = 0; i < jsonArrLength; i++) {
                //listviewActivity listviewActivity2 = new 
            listviewActivity();
                JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
                date = jsonChildNode.getString("event_date");
                //DatesList.add(listviewActivity.date);
                EventList.add(date);
            }


        } catch (Exception e) {
            Log.i("App", "Error parsing data: " + e.getMessage());

        }
    }

}

//Thread for fetching event places
private class FetchPlaceDataTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {

        //getCookieUsingCookieHandler();

        InputStream inputStream = null;
        String result = null;
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(params[0]);

        httpGet.setHeader("Content-Type", "application/json");

        try {

            HttpResponse response = client.execute(httpGet);
            inputStream = response.getEntity().getContent();


            // convert inputstream to string
            if (inputStream != null) {
                result = convertInputStreamToString(inputStream);
                Log.i("App", "Data received: " + result);

            } else
                result = "Failed to fetch data";

            return result;

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

        return null;
    }

    @Override
    protected void onPostExecute(String dataFetched) {
        //parse the JSON data and then display
        parseJSONEvents(dataFetched);
    }


    private String convertInputStreamToString(InputStream inputStream) 
    throws IOException, JSONException {
        BufferedReader bufferedReader = new BufferedReader(new 
    InputStreamReader(inputStream, "UTF-8"));
        StringBuilder responseStrBuilder = new StringBuilder();
        String line = "";
        String result = "";
        while ((line = bufferedReader.readLine()) != null)
            //responseStrBuilder.append(line + "\n");
            result += line;

        inputStream.close();
        return result;

    }

    private void parseJSONEvents(String data) {

        try {
            JSONArray jsonMainNode = new JSONArray(data);

            int jsonArrLength = jsonMainNode.length();

            for (int i = 0; i < jsonArrLength; i++) {
                //listviewActivity listviewActivity3 = new listviewActivity();
                JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
                place = jsonChildNode.getString("event_place");
                //PlacesList.add(listviewActivity.place);
                EventList.add(place);
            }


        } catch (Exception e) {
            Log.i("App", "Error parsing data: " + e.getMessage());

        }
    }
}

//Thread for fetching event times
private class FetchTimeDataTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {

        //getCookieUsingCookieHandler();

        InputStream inputStream = null;
        String result = null;
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(params[0]);

        httpGet.setHeader("Content-Type", "application/json");

        try {

            HttpResponse response = client.execute(httpGet);
            inputStream = response.getEntity().getContent();


            // convert inputstream to string
            if (inputStream != null) {
                result = convertInputStreamToString(inputStream);
                Log.i("App", "Data received: " + result);

            } else
                result = "Failed to fetch data";

            return result;

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

        return null;
    }

    @Override
    protected void onPostExecute(String dataFetched) {
        //parse the JSON data and then display
        parseJSONEvents(dataFetched);
    }


    private String convertInputStreamToString(InputStream inputStream) 
    throws IOException, JSONException {
        BufferedReader bufferedReader = new BufferedReader(new 
    InputStreamReader(inputStream, "UTF-8"));
        StringBuilder responseStrBuilder = new StringBuilder();
        String line = "";
        String result = "";
        while ((line = bufferedReader.readLine()) != null)
            //responseStrBuilder.append(line + "\n");
            result += line;

        inputStream.close();
        return result;

    }

    private void parseJSONEvents(String data) {

        try {
            JSONArray jsonMainNode = new JSONArray(data);

            int jsonArrLength = jsonMainNode.length();

            for (int i = 0; i < jsonArrLength; i++) {
                //listviewActivity listviewActivity4 = new 
            listviewActivity();
                JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
                time = jsonChildNode.getString("event_time");
                //TimesList.add(listviewActivity.time);
                EventList.add(time);
            }


        } catch (Exception e) {
            Log.i("App", "Error parsing data: " + e.getMessage());

        }
    }
}

//Thread for fetching event URLs
private class FetchURLDataTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {

        //getCookieUsingCookieHandler();

        InputStream inputStream = null;
        String result = null;
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(params[0]);

        httpGet.setHeader("Content-Type", "application/json");

        try {

            HttpResponse response = client.execute(httpGet);
            inputStream = response.getEntity().getContent();


            // convert inputstream to string
            if (inputStream != null) {
                result = convertInputStreamToString(inputStream);
                Log.i("App", "Data received: " + result);

            } else
                result = "Failed to fetch data";

            return result;

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

        return null;
    }

    @Override
    protected void onPostExecute(String dataFetched) {
        //parse the JSON data and then display
        parseJSONEvents(dataFetched);
    }


    private String convertInputStreamToString(InputStream inputStream) 
    throws IOException, JSONException {
        BufferedReader bufferedReader = new BufferedReader(new 
    InputStreamReader(inputStream, "UTF-8"));
        StringBuilder responseStrBuilder = new StringBuilder();
        String line = "";
        String result = "";
        while ((line = bufferedReader.readLine()) != null)
            //responseStrBuilder.append(line + "\n");
            result += line;

        inputStream.close();
        return result;

    }

    private void parseJSONEvents(String data) {

        try {
            JSONArray jsonMainNode = new JSONArray(data);

            int jsonArrLength = jsonMainNode.length();

            for (int i = 0; i < jsonArrLength; i++) {
                //listviewActivity listviewActivity5 = new 
            listviewActivity();
                JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
                url = jsonChildNode.getString("event_url");
                //URLList.add(listviewActivity.url);
                EventList.add(url);
            }


        } catch (Exception e) {
            Log.i("App", "Error parsing data: " + e.getMessage());

        }
    }
}

//Thread for fecthing event image URLs
private class FetchImageDataTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {

        //getCookieUsingCookieHandler();

        InputStream inputStream = null;
        String result = null;
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(params[0]);

        httpGet.setHeader("Content-Type", "application/json");

        try {

            HttpResponse response = client.execute(httpGet);
            inputStream = response.getEntity().getContent();


            // convert inputstream to string
            if (inputStream != null) {
                result = convertInputStreamToString(inputStream);
                Log.i("App", "Data received: " + result);

            } else
                result = "Failed to fetch data";

            return result;

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

        return null;
    }

    @Override
    protected void onPostExecute(String dataFetched) {
        //parse the JSON data and then display
        parseJSONEvents(dataFetched);
    }


    private String convertInputStreamToString(InputStream inputStream) 
    throws IOException, JSONException {
        BufferedReader bufferedReader = new BufferedReader(new 
    InputStreamReader(inputStream, "UTF-8"));
        StringBuilder responseStrBuilder = new StringBuilder();
        String line = "";
        String result = "";
        while ((line = bufferedReader.readLine()) != null)
            //responseStrBuilder.append(line + "\n");
            result += line;

        inputStream.close();
        return result;

    }

    private void parseJSONEvents(String data) {

        try {
            JSONArray jsonMainNode = new JSONArray(data);

            int jsonArrLength = jsonMainNode.length();

            for (int i = 0; i < jsonArrLength; i++) {
                //listviewActivity listviewActivity6 = new 
            listviewActivity();
                JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
                imageUrl = jsonChildNode.getString("img_url");
                //ImagesList.add(listviewActivity.imageUrl);
                EventList.add(imageUrl);
            }


        } catch (Exception e) {
            Log.i("App", "Error parsing data: " + e.getMessage());

        }


    }
}

public ArrayList getArrayList(){
    return EventList;
}

public void setList() {

    //final ArrayList<listviewActivity> List =  getArrayList();

    String[] listItems = new String[EventList.size()];

    for (int i = 0; i < EventList.size(); i++) {
        EventList.get(i);
        listItems[i] = title;
    }



    final Context context = this;
    mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        public void onItemClick(AdapterView<?> parent, View view, int 
      position, long id) {

            //1
            EventList.get(position);

            //2
            Intent detailIntent = new Intent(context, event_detail.class);

            //3
            detailIntent.putExtra("title", title);
            detailIntent.putExtra("url", url);

            //4
            startActivity(detailIntent);
        }

    });

我几乎为每个异步任务使用相同的代码,唯一的区别是从中获取数据的URL。每个异步任务都成功从其URL中提取JSON并将其显示在LogCat上。

ListView适配器:

public class EventsAdapter extends BaseAdapter{

LayoutInflater minflater;
Context mcontext;
ArrayList<String> mDataSource;



public EventsAdapter(Context context, ArrayList<String> items){
    mcontext = context;
    mDataSource = items;
    minflater = (LayoutInflater) 
mcontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

}

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

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

}

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

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

    //Get view for row item
    View rowView = minflater.inflate(R.layout.list_item_event, parent, 
false);

    //Get the title element
    TextView titleTextView = (TextView) 
rowView.findViewById(R.id.event_list_title);

    //Get the date element
    TextView dateTextView = (TextView) 
rowView.findViewById(R.id.event_list_date);

    //Get the time element
    TextView timeTextView = (TextView) 
rowView.findViewById(R.id.event_list_time);

    //Get the time element
    TextView placeTextView = (TextView) 
rowView.findViewById(R.id.event_list_place);

    //Get the thumbnail element
    ImageView thumbnailImageView = (ImageView) 
rowView.findViewById(R.id.event_list_thumbnail);

    //1
    listviewActivity listviewActivity = (listviewActivity) 
getItem(position);

    //2
    titleTextView.setText(listviewActivity.title);
    dateTextView.setText(listviewActivity.date);
    timeTextView.setText(listviewActivity.time);
    placeTextView.setText(listviewActivity.place);

    //3

Picasso.with(mcontext)
.load(listviewActivity.imageUrl)
.placeholder(R.mipmap.ic_launcher)
.resize(250,250).centerCrop().into(thumbnailImageView);

return rowView;
  }
}

我还使用了第二个XML Layout,它将包含我在ListView Activity中充气的URL中的JSON数据。

这是:

<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">

<ImageView
    android:id="@+id/event_list_thumbnail"
    android:layout_width="90dp"
    android:layout_height="90dp"
    android:layout_alignParentStart="true"
    android:layout_centerVertical="true"
    android:layout_marginBottom="6dp"
    android:layout_marginStart="4dp"
    android:layout_marginTop="6dp"
    android:scaleType="centerInside"
    tools:src="@mipmap/ic_launcher"
    android:layout_marginLeft="4dp"
    android:layout_alignParentLeft="true" />


<RelativeLayout
    android:id="@+id/recipe_list_text_layout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:layout_toEndOf="@id/event_list_thumbnail"
    android:layout_toRightOf="@id/event_list_thumbnail">

    <TextView
        android:id="@+id/event_list_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:textSize="18sp"
        tools:text="Event Name"
        />

    <TextView
        android:id="@+id/event_list_date"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/event_list_title"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="2dp"
        android:ellipsize="end"
        android:maxLines="3"
        android:textSize="16sp"
        tools:text="Date"
        />

    <TextView
        android:id="@+id/event_list_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/event_list_date"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="2dp"
        android:ellipsize="end"
        android:maxLines="3"
        android:textSize="16sp"
        tools:text="Time"
        />

    <TextView
        android:id="@+id/event_list_place"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/event_list_time"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="2dp"
        android:ellipsize="end"
        android:maxLines="3"
        android:textSize="16sp"
        tools:text="Place"
        />

   </RelativeLayout>
</RelativeLayout>

就像我之前说的那样,我在检索JSON数据时没有问题。我的问题是将数据填充到ListView中。如果有人能向我解释为什么我的数据没有出现以及我可以做些什么来解决它,那将非常感激。

1 个答案:

答案 0 :(得分:0)

您应该使用单个json API来获取所有事件数据。 您还声明了许多arraylist:NameList ,DatesList,但您已经注释了将项目添加到列表的语句。喜欢这个

 //DatesList.add(listviewActivity.date);

我找到的解决方案是

 public void parseJSONEvents(String data) {

    try {
        JSONArray jsonMainNode = new JSONArray(data);

        int jsonArrLength = jsonMainNode.length();

        for (int i = 0; i < jsonArrLength; i++) {
            //listviewActivity listviewActivity1 = new 
        listviewActivity();
            JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
            title = jsonChildNode.getString("event_name");
            //NameList.add(listviewActivity.title);
            EventList.add(title);

        }
adapter.notifyDataSetChanged();

    } catch (Exception e) {
        Log.i("App", "Error parsing data: " + e.getMessage());

    }

}

adapter.notifyDataSetChanged();方法中for循环后调用parseJSONEvents

将所有这些代码评论为:

 /*   listviewActivity listviewActivity = (listviewActivity) 
    getItem(position);

    //2
    titleTextView.setText(listviewActivity.title);
    dateTextView.setText(listviewActivity.date);
    timeTextView.setText(listviewActivity.time);
    placeTextView.setText(listviewActivity.place);

    //3

Picasso.with(mcontext)
.load(listviewActivity.imageUrl)
.placeholder(R.mipmap.ic_launcher)
.resize(250,250).centerCrop().into(thumbnailImageView); */

并添加此行

titleTextView.setText(mDataSource.get(position));