从JSON提取数据并填充ListView

时间:2018-11-12 13:55:27

标签: java android

我正在尝试使用监护人API进行项目,该API从JSON获取数据,并在ListView中将所有新闻显示在屏幕上,我已经尝试了所有可能的方法,并且还记录了信息以验证代码流,并且所有工作正常,没有错误和崩溃,唯一的问题是它没有在屏幕上显示数据,屏幕为空白,请帮助我

此处输出: Blank Screen

这是AndroidManifest.xml

    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.hannan.newsfeed">
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>
        </activity>
    </application>

</manifest>

这是MainActivity.java

package com.example.hannan.newsfeed;

import android.content.Intent;
import android.os.AsyncTask;
import android.support.v4.content.AsyncTaskLoader;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private static final String LOG_TAG = MainActivity.class.getSimpleName();
    private static final String GAURDIAN_URL = "https://content.guardianapis.com/search?api-key=d7262a1a-2583-4342-9b57-85ed0f621416";
    private NewsAdapter mAdapter;

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

        ListView listView = findViewById(R.id.list);

        mAdapter = new NewsAdapter(this, new ArrayList<NewsModel>());

        listView.setAdapter(mAdapter);

        NewsAsyncTask task = new NewsAsyncTask();
        task.execute(GAURDIAN_URL);


    }


    private class NewsAsyncTask extends AsyncTask<String, Void, List<NewsModel>> {

        @Override
        protected List<NewsModel> doInBackground(String... urls) {
            Log.i(LOG_TAG, "TEST: In doInBackground");
            if (urls.length < 1 || urls[0] == null) {
                Log.i(LOG_TAG, "TEST: No urls available");
                return null;
            }
            List<NewsModel> result = QueryUtils.fetch_data(urls[0]);
            Log.i(LOG_TAG, "TEST: In fetch_data() method of QueryUtils class");
            return result;


        }

        @Override
        protected void onPostExecute(List<NewsModel> newsModels) {
            Log.i(LOG_TAG, "TEST: Completed doInBackground() Method");
            mAdapter.clear();
            Log.i(LOG_TAG, "TEST: Adapter Cleared");
            if (newsModels != null && !newsModels.isEmpty()) {
                Log.i(LOG_TAG, "TEST:Data added to Adapter");
                mAdapter.addAll();

            } else {
                Log.i(LOG_TAG, "TEST: No data in Model");
            }
        }
    }

}

这是NewsAdapter.java

    package com.example.hannan.newsfeed;

import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class NewsAdapter extends ArrayAdapter {
    private static final String LOG_TAG = MainActivity.class.getSimpleName();

    public NewsAdapter(@NonNull Context context, ArrayList<NewsModel> newslist) {
        super(context, 0, newslist);
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        if (convertView == null) {
            LayoutInflater.from(getContext()).inflate(R.layout.list_news, parent, false);
        }

        NewsModel currentNews = (NewsModel) getItem(position);

        TextView news_title = convertView.findViewById(R.id.news_title);
        TextView news_section = convertView.findViewById(R.id.news_section);
        TextView news_date = convertView.findViewById(R.id.news_date);

        news_title.setText(currentNews.getmNewsTitle());
        news_section.setText(currentNews.getmNewsSection());
        news_date.setText(currentNews.getmNewsDate());

        return convertView;
    }

}

这是NewsModel.java

    package com.example.hannan.newsfeed;

public class NewsModel {

    private String mNewsTitle;
    private String mNewsSection;
    private String mNewsDate;
    private String mNewsUrl;

    NewsModel(String news_title,String news_section, String news_date, String news_url){
        mNewsTitle = news_title;
        mNewsSection = news_section;
        mNewsDate = news_date;
        mNewsUrl = news_url;
    }

    public String getmNewsTitle() {
        return mNewsTitle;
    }

    public String getmNewsSection() {
        return mNewsSection;
    }

    public String getmNewsDate() {
        return mNewsDate;
    }

    public String getmNewsUrl() {
        return mNewsUrl;
    }
}

这是QueryUtils.java

 package com.example.hannan.newsfeed;

import android.text.TextUtils;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import javax.net.ssl.HttpsURLConnection;

public class QueryUtils {
    private static final String LOG_TAG = QueryUtils.class.getSimpleName();

    private QueryUtils() {

    }

    public static ArrayList<NewsModel> fetch_data(String requestedUrl) {
        URL url = createURL(requestedUrl);
        Log.i(LOG_TAG, "TEST: URL Requested");
        String jsonResponse = null;
        try {
            jsonResponse = makeHttpRequest(url);
            Log.i(LOG_TAG, "TEST: JSON Response created");
        } catch (IOException e) {
            e.printStackTrace();
        }
        ArrayList<NewsModel> listnews = extractResponseFromJson(jsonResponse);

        return listnews;
    }

    private static URL createURL(String stringUrl) {
        URL url = null;
        try {
            url = new URL(stringUrl);
            Log.i(LOG_TAG, "TEST: URL Created " + url);
        } catch (MalformedURLException e) {
            Log.e(LOG_TAG, "TEST:Problem Building URL..", e);
        }
        return url;
    }

    private static String makeHttpRequest(URL url) throws IOException {
        String jsonResponse = "";
        if (url == null) {
            return jsonResponse;
        }

        HttpsURLConnection urlConnection = null;
        InputStream is = null;
        try {
            urlConnection = (HttpsURLConnection) url.openConnection();
            urlConnection.setReadTimeout(10000);
            urlConnection.setConnectTimeout(15000);
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();

            if (urlConnection.getResponseCode() == 200) {
                is = urlConnection.getInputStream();
                jsonResponse = readFromStream(is);
                Log.i(LOG_TAG, "TEST: Connected with HTTP");
            } else {
                Log.e(LOG_TAG, "TEST:Error Response Code:" + urlConnection.getResponseCode());
            }
        } catch (IOException e) {
            Log.e(LOG_TAG, "TEST:Problem retrieving Data", e);
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            if (is != null) {
                is.close();
            }

        }
        return jsonResponse;
    }

    private static String readFromStream(InputStream inputStream) throws IOException {
        StringBuilder stringBuilder = new StringBuilder();
        Log.i(LOG_TAG, "TEST: String builder created");
        if (inputStream != null) {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
            BufferedReader reader = new BufferedReader(inputStreamReader);
            String line = reader.readLine();
            while (line != null) {
                stringBuilder.append(line);
                line = reader.readLine();
            }
        }
        Log.i(LOG_TAG, "TEST: returning String builder");
        return stringBuilder.toString();
    }

    private static ArrayList<NewsModel> extractResponseFromJson(String newsJson) {
        Log.i(LOG_TAG, "TEST: In extractResponseFromJson() method..");
        if (TextUtils.isEmpty(newsJson)) {
            Log.i(LOG_TAG, "TEST: newsJson is empty");
            return null;
        }
        ArrayList<NewsModel> newslist = new ArrayList<>();
        Log.i(LOG_TAG, "TEST: ArrayList created");
        try {
            JSONObject baseObject = new JSONObject(newsJson);
            Log.i(LOG_TAG, "TEST: JSON object created");
            JSONObject responseArray = baseObject.getJSONObject("response");
            Log.i(LOG_TAG, "JSON object fetched" + responseArray);
            JSONArray resultArray = responseArray.getJSONArray("results");
            for (int i = 0; i < resultArray.length(); i++) {
                Log.i(LOG_TAG, "TEST: In for loop");
                JSONObject currentNews = resultArray.getJSONObject(i);

                String title = currentNews.getString("webTitle");


                String section_name = currentNews.getString("sectionName");

                String published_date = currentNews.getString("webPublicationDate");

                String url = currentNews.getString("webUrl");

                NewsModel news = new NewsModel(title, section_name, published_date, url);

                newslist.add(news);
                Log.i(LOG_TAG, "TEST: JSON data Added to Model");

            }
        } catch (JSONException e) {
            e.printStackTrace();
            Log.e(LOG_TAG, "Error fetching Data from JSON");
        }

        return newslist;
    }
}

这是main_activity.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"
    tools:context=".MainActivity">

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

</RelativeLayout>

这是list_news.xml

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    xmlns:tools="http://schemas.android.com/tools">

    <TextView
        android:id="@+id/news_title"
        android:layout_width="match_parent"
        android:padding="8dp"
        android:textSize="20sp"
        android:layout_height="wrap_content"
        tools:text="News Title"/>

    <TextView
        android:id="@+id/news_section"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/news_title"
        tools:text="News Section"
        android:textSize="14sp"
        android:layout_alignParentLeft="true"
        android:padding="8dp"/>
    <TextView
        android:id="@+id/news_date"
        android:textSize="12sp"
        android:padding="8dp"
        tools:text="News Date"
        android:layout_below="@id/news_title"
        android:layout_alignParentRight="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout>

0 个答案:

没有答案