My news page in my app isn't retrieving any news and only a blank white page is being displayed instead of a newsfeed

huangapple 未分类评论52阅读模式
英文:

My news page in my app isn't retrieving any news and only a blank white page is being displayed instead of a newsfeed

问题

我目前正在使用 Android Studio 4.0 进行工作构建版本号为 AI-193.6911.18.40.6514223

在进入新闻页面后我看到一个空白页面似乎 API 没有检索到应该显示的新闻我已经仔细检查了整个应用程序以查找任何拼写错误以防它与 API 参数不匹配)。一切看起来都是正确的但 API 并未检索到数据

以下是与问题相关的代码

newspage.java:

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.widget.Toast;

import com.example.nvirone.API.ApiClient;
import com.example.nvirone.API.ApiInterface;
import com.example.nvirone.Models.Article;
import com.example.nvirone.Models.News;

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

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class Newspage extends AppCompatActivity {
    // ...
    // (代码略,与问题相关的其余部分)
    // ...
    
    public void LoadJson(){
        ApiInterface apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
        String country = Utils.getCountry();

        Call<News> call;
        call = apiInterface.getNews(country, API_KEY);
        call.enqueue(new Callback<News>() {
            @Override
            public void onResponse(Call<News> call, Response<News> response) {
                if (response.isSuccessful() && response.body().getArticle()!=null){
                    articles.clear();
                    articles = response.body().getArticle();
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFailure(Call<News> call, Throwable t) {
                Toast.makeText(Newspage.this, "无结果", Toast.LENGTH_LONG).show();
            }
        });
    }
}

以上是与问题相关的代码部分。如果您还有其他需要帮助的地方,请随时提问。

英文:

I am currently working on Android Studio 4.0, Build #AI-193.6911.18.40.6514223.

Upon entering the news page, I am being shown a blank page. It appears that the API is not retrieving the news it's supposed to. I've double checked my entire app for any typos (in case it doesn't match the API parameters). Everything appears right but the API is not retrieving the data.

I have attached below the code with respect to the problem.

newspage.java:

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.widget.Toast;

import com.example.nvirone.API.ApiClient;
import com.example.nvirone.API.ApiInterface;
import com.example.nvirone.Models.Article;
import com.example.nvirone.Models.News;

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

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class Newspage extends AppCompatActivity {
    public static final String API_KEY = &quot;(unique API key)&quot;;
    private RecyclerView recyclerView;
    private Adapter adapter;
    private RecyclerView.LayoutManager layoutManager;
    private List&lt;Article&gt; articles = new ArrayList&lt;&gt;();
    private String TAG = Newspage.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_newspage);
        recyclerView = findViewById(R.id.recyclerView);
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new Adapter(articles, Newspage.this);
        recyclerView.setAdapter(adapter);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setNestedScrollingEnabled(false);
        LoadJson();
    }
public void LoadJson(){
    ApiInterface apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
    String country = Utils.getCountry();

    Call&lt;News&gt; call;
    call = apiInterface.getNews(country, API_KEY);
    call.enqueue(new Callback&lt;News&gt;() {
        @Override
        public void onResponse(Call&lt;News&gt; call, Response&lt;News&gt; response) {
            if (response.isSuccessful() &amp;&amp; response.body().getArticle()!=null){
                articles.clear();
                articles = response.body().getArticle();
                adapter.notifyDataSetChanged();
            }
        }

        @Override
        public void onFailure(Call&lt;News&gt; call, Throwable t) {
            Toast.makeText(Newspage.this,&quot;NO result&quot;,Toast.LENGTH_LONG).show();
        }
    });
    }
}

Newsindetail.java:

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class NewInDetail extends AppCompatActivity {
    WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_in_detail);
        Intent intent = getIntent();
        String url = intent.getStringExtra(&quot;url&quot;);
        webView = findViewById(R.id.webView);
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setLoadsImagesAutomatically(true);
        webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        webView.setWebViewClient(new WebViewClient());
        webView.loadUrl(url);
    }
}

Adapter:

package com.example.nvirone;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.example.nvirone.Models.Article;
import com.squareup.picasso.Picasso;

import java.util.List;

public class Adapter extends RecyclerView.Adapter&lt;Adapter.MyViewHolder&gt; {
    private List&lt;Article&gt; articles;
    private Context context;
    private AdapterView.OnItemClickListener OnItemClickListener;
    private OnItemClickListener onItemCLickListener;


    public Adapter(List&lt;Article&gt; articles, Context context) {
        this.articles = articles;
        this.context = context;
    }


    public Adapter() {

    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holders, int position) {
        final MyViewHolder holder = holders;
        final Article model = articles.get(position);
        RequestOptions requestOptions = new RequestOptions();
        requestOptions.placeholder(Utils.getRandomDrawbleColor());
        requestOptions.error(Utils.getRandomDrawbleColor());
        requestOptions.diskCacheStrategy(DiskCacheStrategy.ALL);
        requestOptions.centerCrop();

        Glide.with(context).load(model.getUrlToImage()).apply(requestOptions)
                .listener(new RequestListener&lt;Drawable&gt;() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target&lt;Drawable&gt; target, boolean isFirstResource) {
                        holder.progressBar.setVisibility(View.GONE);
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(Drawable resource, Object model, Target&lt;Drawable&gt; target, DataSource dataSource, boolean isFirstResource) {
                        holder.progressBar.setVisibility(View.GONE);
                        return false;
                    }
                })
                .transition(DrawableTransitionOptions.withCrossFade())
                .into(holder.imageView);
        holder.title.setText(model.getTitle());
        holder.desc.setText(model.getDescription());
        holder.source.setText(model.getSource().getName());
        holder.time.setText(&#39;\u2022&#39; + Utils.DateToTimeFormat(model.getPublishedAt()));
        holder.published.setText(Utils.DateToTimeFormat(model.getPublishedAt()));
        holder.author.setText(model.getAuthor());
        String imageURL = model.getUrlToImage();
        Picasso.get().load(imageURL).into(holder.imageView);
        holder.cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(context,NewInDetail.class);
                intent.putExtra(&quot;url&quot;,model.getUrl());
                context.startActivity(intent);
            }
        });
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item,parent,false);
        return new MyViewHolder(view, onItemCLickListener);
    }

    @Override
    public int getItemCount() {
        return articles.size();
    }
    public void setOnItemClickListener(OnItemClickListener onItemClickListener){
        this.onItemCLickListener = onItemClickListener;
    }

    public interface OnItemClickListener{
        void onItemClick(View view, int position);
    }

    public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

        TextView title, desc, author, published, source, time;
        ImageView imageView;
        ProgressBar progressBar;
        OnItemClickListener onItemClickListener;
        CardView cardView;
        public MyViewHolder(@NonNull View itemView, OnItemClickListener onItemClickListener) {
            super(itemView);
            itemView.setOnClickListener(this);
            title  = itemView.findViewById(R.id.title);
            desc = itemView.findViewById(R.id.desc);
            author = itemView.findViewById(R.id.author);
            published = itemView.findViewById(R.id.publishedAt);
            source = itemView.findViewById(R.id.source);
            time = itemView.findViewById(R.id.time);
            imageView = itemView.findViewById(R.id.img);
            progressBar = itemView.findViewById(R.id.progress_load_photo);
            cardView = itemView.findViewById(R.id.cardView);

            this.onItemClickListener = onItemCLickListener;
        }
        @Override
        public void onClick(View view) {
            onItemClickListener.onItemClick(view, getAdapterPosition());
        }
    }
}

ApiClient:

package com.example.nvirone.API;

import java.security.cert.CertificateException;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class ApiClient {
    public static final String BaseURL = &quot;https://newsapi.org/v2/&quot;;
    public static Retrofit retrofit ;

    public static Retrofit getApiClient(){
        if(retrofit==null){
            retrofit = new Retrofit.Builder().baseUrl(BaseURL).client(getUnsafeOkHttpClient().build()).addConverterFactory(GsonConverterFactory.create()).build();
        }
        return retrofit;
    }
    public static OkHttpClient.Builder getUnsafeOkHttpClient(){
        try {
            // Create a trust manager that does not validate certificate chains
            final TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                        }

                        @Override
                        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                        }

                        @Override
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return new java.security.cert.X509Certificate[]{};
                        }
                    }
            };

            // Install the all-trusting trust manager
            final SSLContext sslContext = SSLContext.getInstance(&quot;SSL&quot;);
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

            // Create an ssl socket factory with our all-trusting manager
            final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
            builder.hostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
            return builder;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}

ApiInterface:

package com.example.nvirone.API;

import com.example.nvirone.Models.News;

import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;

public interface ApiInterface {
    @GET(&quot;top-headlines&quot;)
    Call&lt;News&gt; getNews(

            @Query(&quot;country&quot;) String country,
            @Query(&quot;apiKey&quot;) String apiKey
    );
}

Utils:

package com.example.nvirone;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;

import org.ocpsoft.prettytime.PrettyTime;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Random;

public class Utils {

    public static ColorDrawable[] vibrantLightColorList =
            {
                    new ColorDrawable(Color.parseColor(&quot;#ffeead&quot;)),
                    new ColorDrawable(Color.parseColor(&quot;#93cfb3&quot;)),
                    new ColorDrawable(Color.parseColor(&quot;#fd7a7a&quot;)),
                    new ColorDrawable(Color.parseColor(&quot;#faca5f&quot;)),
                    new ColorDrawable(Color.parseColor(&quot;#1ba798&quot;)),
                    new ColorDrawable(Color.parseColor(&quot;#6aa9ae&quot;)),
                    new ColorDrawable(Color.parseColor(&quot;#ffbf27&quot;)),
                    new ColorDrawable(Color.parseColor(&quot;#d93947&quot;))
            };

    public static ColorDrawable getRandomDrawbleColor() {
        int idx = new Random().nextInt(vibrantLightColorList.length);
        return vibrantLightColorList[idx];
    }

    public static String DateToTimeFormat(String oldstringDate){
        PrettyTime p = new PrettyTime(new Locale(getCountry()));
        String isTime = null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(&quot;yyyy-MM-dd&#39;T&#39;HH:mm:ss&#39;Z&#39;&quot;,
                    Locale.ENGLISH);
            Date date = sdf.parse(oldstringDate);
            isTime = p.format(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return isTime;
    }

    public static String DateFormat(String oldstringDate){
        String newDate;
        SimpleDateFormat dateFormat = new SimpleDateFormat(&quot;E, d MMM yyyy&quot;, new Locale(getCountry()));
        try {
            Date date = new SimpleDateFormat(&quot;yyyy-MM-dd&#39;T&#39;HH:mm:ss&#39;Z&#39;&quot;,Locale.CHINA).parse(oldstringDate);
            assert date != null;
            newDate = dateFormat.format(date);
        } catch (ParseException e) {
            e.printStackTrace();
            newDate = oldstringDate;
        }

        return newDate;
    }

    public static String getCountry(){
        Locale locale = Locale.getDefault();
        String country = locale.getCountry();
        return country.toLowerCase();
    }
}

Parameters according to the API:

NEWS:

package com.example.nvirone.Models;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

import java.util.List;

public class News {
    @SerializedName(&quot;status&quot;)
    @Expose
    private String status;

    @SerializedName(&quot;totalResults&quot;)
    @Expose
    private int totalResult;

    @SerializedName(&quot;articles&quot;)
    @Expose
    private List&lt;Article&gt; article;

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public int getTotalResult() {
        return totalResult;
    }

    public void setTotalResult(int totalResult) {
        this.totalResult = totalResult;
    }

    public List&lt;Article&gt; getArticle() {
        return article;
    }

    public void setArticle(List&lt;Article&gt; article) {
        this.article = article;
    }
}

Article :

package com.example.nvirone.Models;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Article {
    @SerializedName(&quot;source&quot;)
    @Expose
    private Source source;

    @SerializedName(&quot;author&quot;)
    @Expose
    private String author;

    @SerializedName(&quot;title&quot;)
    @Expose
    private String title;

    @SerializedName(&quot;description&quot;)
    @Expose
    private String description;

    @SerializedName(&quot;url&quot;)
    @Expose
    private String url;

    @SerializedName(&quot;urlToImage&quot;)
    @Expose
    private String urlToImage;

    @SerializedName(&quot;publishedAt&quot;)
    @Expose
    private String publishedAt;

    public Source getSource() {
        return source;
    }

    public void setSource(Source source) {
        this.source = source;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUrlToImage() {
        return urlToImage;
    }

    public void setUrlToImage(String urlToImage) {
        this.urlToImage = urlToImage;
    }

    public String getPublishedAt() {
        return publishedAt;
    }

    public void setPublishedAt(String publishedAt) {
        this.publishedAt = publishedAt;
    }
}

Source:

package com.example.nvirone.Models;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Source {
    @SerializedName(&quot;id&quot;)
    @Expose
    private String id;

    @SerializedName(&quot;name&quot;)
    @Expose
    private String name;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

The cardview that is supposed to display the newsfeed :

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;FrameLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    android:layout_width=&quot;match_parent&quot;
    android:layout_height=&quot;wrap_content&quot;
    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;
    xmlns:tools=&quot;http://schemas.android.com/tools&quot;&gt;
    &lt;androidx.cardview.widget.CardView
        android:id=&quot;@+id/cardView&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:layout_marginLeft=&quot;11dp&quot;
        android:layout_marginRight=&quot;11dp&quot;
        android:layout_marginTop=&quot;7dp&quot;
        android:layout_marginBottom=&quot;7dp&quot;
        app:cardElevation=&quot;@dimen/cardview_default_elevation&quot;
        app:cardCornerRadius=&quot;15dp&quot;&gt;
        &lt;RelativeLayout
            android:layout_width=&quot;match_parent&quot;
            android:layout_height=&quot;wrap_content&quot;&gt;
            &lt;ImageView
                android:layout_width=&quot;match_parent&quot;
                android:layout_height=&quot;200dp&quot;
                android:id=&quot;@+id/img&quot;
                android:scaleType=&quot;centerCrop&quot;
                android:transitionName=&quot;img&quot;
                tools:ignore= &quot;UnusedAttribute&quot;/&gt;
            &lt;ImageView
                android:layout_width=&quot;match_parent&quot;
                android:layout_height=&quot;80dp&quot;
                android:id=&quot;@+id/shadow_bottom&quot;
                android:src=&quot;@drawable/bottom_shadow&quot;
                android:layout_alignBottom=&quot;@+id/img&quot; /&gt;
            &lt;ProgressBar
                android:layout_width=&quot;match_parent&quot;
                android:layout_height=&quot;wrap_content&quot;
                style=&quot;@android:style/Widget.ProgressBar.Small&quot;
                android:id=&quot;@+id/progress_load_photo&quot;
                android:layout_marginTop=&quot;70dp&quot; /&gt;
            &lt;TextView
                android:layout_width=&quot;match_parent&quot;
                android:layout_height=&quot;30dp&quot;
                android:id=&quot;@+id/author&quot;
                android:drawablePadding=&quot;10dp&quot;
                android:ellipsize=&quot;end&quot;
                android:maxLines=&quot;1&quot;
                android:textColor=&quot;@android:color/white&quot;
                android:singleLine=&quot;true&quot;
                android:text=&quot;Author&quot;
                android:gravity=&quot;bottom&quot;
                android:layout_marginRight=&quot;160dp&quot;
                android:layout_alignLeft=&quot;@+id/title&quot;
                android:layout_alignStart=&quot;@+id/title&quot;
                android:layout_alignRight=&quot;@+id/layoutDate&quot;
                android:layout_alignTop=&quot;@+id/layoutDate&quot;
                android:layout_alignEnd=&quot;@+id/layoutDate&quot;/&gt;
            &lt;FrameLayout
                android:id=&quot;@+id/layoutDate&quot;
                android:layout_width=&quot;wrap_content&quot;
                android:layout_height=&quot;wrap_content&quot;
                android:layout_below=&quot;@+id/img&quot;
                android:background=&quot;@drawable/round_white&quot;
                android:padding=&quot;5dp&quot;
                android:layout_alignParentRight=&quot;true&quot;
                android:layout_marginRight=&quot;20dp&quot;
                android:layout_marginTop=&quot;50dp&quot;&gt;
                &lt;ImageView
                    android:src=&quot;@drawable/ic_date&quot;
                    android:layout_width=&quot;18dp&quot;
                    android:layout_height=&quot;18dp&quot;
                    android:layout_marginLeft=&quot;5dp&quot;
                    android:layout_marginRight=&quot;5dp&quot;/&gt;
                &lt;TextView
                    android:layout_width=&quot;wrap_content&quot;
                    android:layout_height=&quot;wrap_content&quot;
                    android:textColor=&quot;#606060&quot;
                    android:id=&quot;@+id/publishedAt&quot;
                    android:layout_marginLeft=&quot;27dp&quot;
                    android:layout_marginRight=&quot;10dp&quot;
                    android:text=&quot;01 January 2000&quot;/&gt;
            &lt;/FrameLayout&gt;
            &lt;TextView
                android:layout_width=&quot;match_parent&quot;
                android:layout_height=&quot;wrap_content&quot;
                android:fontFamily=&quot;sans-serif-light&quot;
                android:textStyle=&quot;bold&quot;
                android:textColor=&quot;@color/colorTextTitle&quot;
                android:layout_marginLeft=&quot;16dp&quot;
                android:layout_marginRight=&quot;16dp&quot;
                android:text=&quot;Title&quot;
                android:textSize=&quot;17sp&quot;
                android:layout_marginTop=&quot;10dp&quot;
                android:layout_below=&quot;@id/img&quot;
                android:id=&quot;@+id/title&quot;/&gt;
            &lt;TextView
                android:id=&quot;@+id/desc&quot;
                android:layout_width=&quot;wrap_content&quot;
                android:layout_height=&quot;20dp&quot;
                android:layout_marginRight=&quot;16dp&quot;
                android:layout_below=&quot;@+id/title&quot;
                android:layout_marginLeft=&quot;16dp&quot;
                android:layout_marginTop=&quot;5dp&quot;
                android:text=&quot;Desc&quot;/&gt;
            &lt;TextView
                android:id=&quot;@+id/source&quot;
                android:layout_width=&quot;wrap_content&quot;
                android:layout_height=&quot;20dp&quot;
                android:layout_below=&quot;@+id/desc&quot;
                android:layout_marginLeft=&quot;16dp&quot;
                android:layout_marginTop=&quot;10dp&quot;
                android:layout_marginBottom=&quot;10dp&quot;
                android:fontFamily=&quot;sans-serif-light&quot;
                android:textStyle=&quot;bold&quot;
                android:textColor=&quot;@color/colorTextTitle&quot;
                android:ellipsize=&quot;end&quot;
                android:singleLine=&quot;true&quot;
                android:drawablePadding=&quot;10dp&quot;
                android:maxLines=&quot;1&quot;
                android:text=&quot;Source&quot;/&gt;
            &lt;TextView
                android:id=&quot;@+id/time&quot;
                android:layout_width=&quot;wrap_content&quot;
                android:layout_height=&quot;20dp&quot;
                android:layout_below=&quot;@+id/desc&quot;
                android:layout_marginTop=&quot;10dp&quot;
                android:layout_marginBottom=&quot;10dp&quot;
                android:layout_toRightOf=&quot;@+id/source&quot;
                android:ellipsize=&quot;end&quot;
                android:singleLine=&quot;true&quot;
                android:drawablePadding=&quot;10dp&quot;
                android:maxLines=&quot;1&quot;
                android:text=&quot;Time&quot;/&gt;


        &lt;/RelativeLayout&gt;


    &lt;/androidx.cardview.widget.CardView&gt;

&lt;/FrameLayout&gt;

EDIT :
I have added some code in the API interface as follows and the same problem has come up again after trying to use this query :

@GET(&quot;everything&quot;)
Call&lt;News&gt; getNewsSearch(

    @Query(&quot;q&quot;) String Keyword,
    @Query(&quot;language&quot;) String language,
    @Query(&quot;SortBy&quot;) String sortBy,
    @Query(&quot;apiKey&quot;) String apiKey

    );

答案1

得分: 0

你需要将以下方法添加到你的 Adapter.java 中:

public void addArticles(List<Article> articles) {
    this.articles.addAll(articles);
    int count = getItemCount();
    notifyItemRangeInserted(count, count + articles.size());
}

然后在你的 NewsPage.java 中这样使用它:

public void LoadJson() {
   ApiInterface apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
   String country = Utils.getCountry();

   Call<News> call;
   call = apiInterface.getNews(country, API_KEY);
   call.enqueue(new Callback<News>() {

      @Override
      public void onResponse(Call<News> call, Response<News> response) {
         List<Article> newArticles = response.body().getArticle();
         if (response.isSuccessful() && newArticles != null) {
            adapter.addArticles(newArticles);
         }
      }

      @Override
      public void onFailure(Call<News> call, Throwable t) {
         Toast.makeText(NewsPage.this, "NO result", Toast.LENGTH_LONG).show();
      }
   });
}
英文:

You need to add this method in your Adapter.java:

public void addArticles(List&lt;Article&gt; articles) {
    this.articles.addAll(articles);
    int count = getItemCount();
    notifyItemRangeInserted(count, count + articles.size());
}

And use it this way in your NewsPage.java:

public void LoadJson() {
   ApiInterface apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
   String       country      = Utils.getCountry();

   Call&lt;News&gt; call;
   call = apiInterface.getNews(country, API_KEY);
   call.enqueue(new Callback&lt;News&gt;() {

      @Override
      public void onResponse(Call&lt;News&gt; call, Response&lt;News&gt; response) {
         List&lt;Article&gt; newArticles = response.body().getArticle();
         if (response.isSuccessful() &amp;&amp; newArticles != null) {
            adapter.addArticles(newArticles);
         }
      }

      @Override
      public void onFailure(Call&lt;News&gt; call, Throwable t) {
         Toast.makeText(NewsPage.this, &quot;NO result&quot;, Toast.LENGTH_LONG).show();
      }
   });
}

huangapple
  • 本文由 发表于 2020年5月29日 23:58:32
  • 转载请务必保留本文链接:https://java.coder-hub.com/62090011.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定