URL查询与邮递员的结果不同

时间:2018-04-28 18:22:38

标签: java url nullpointerexception postman

我试图从openlibrary获取API请求。我在网址中使用了查询:https://openlibrary.org/search.json?author=Plato。这给了我一个结果,但是用我写的代码和Postman我得到一个空的Json。我总是在getItemCount()的docs列表中得到nullpointerexception。有趣的是,应用程序运行了一段时间,比如20秒,比它在public int getItemCount()上给出了nullpointer异常。 检查了很多以前的答案,但没有帮助。 (Android - RecyclerView NullPointerException getItemCount?; What is a NullPointerException, and how do I fix it?

我的界面:

package com.example.mark.retrofitpractice_01.service;

import com.example.mark.retrofitpractice_01.model.WorksByAuthor;
import com.example.mark.retrofitpractice_01.model.WorksBySubject;

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

public interface ApiInterface {

  //@Headers({"Content-Type: application/json", "Accept: application/json"})
  @GET("subjects/{subject}.json")
  Call<WorksBySubject> getContacts(@Path("subject") String subject);


  @Headers({"Content-Type: application/json", "Accept: application/json"})
  @GET("/search.json")
  Call<WorksByAuthor> getAuthor(@Query("author") String author);
}

我的适配器类:

package com.example.mark.retrofitpractice_01.service;

import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.mark.retrofitpractice_01.R;
import com.example.mark.retrofitpractice_01.model.Docs;
import com.example.mark.retrofitpractice_01.model.Work;
import com.example.mark.retrofitpractice_01.model.WorksByAuthor;

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

public class AuthorAdapter extends RecyclerView.Adapter<AuthorAdapter.MyViewHolder> {

  private WorksByAuthor worksByAuthor;
  //private List<Docs> docsList;

  public AuthorAdapter() {
    worksByAuthor = new WorksByAuthor();
  }

  public AuthorAdapter(WorksByAuthor worksByAuthor) {
    this.worksByAuthor = worksByAuthor;
  }

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

  @Override
  public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
    //Docs docs = worksByAuthor.getDocsList().get(position);
    //holder.bookTitle.setText(docs.getTitle_suggest());
    //holder.bookAuthor.setText(docs.getAuthor_name());
    holder.bookTitle.setText(worksByAuthor.getDocsList().get(position).getTitle_suggest());
  }

  @Override
  public int getItemCount() {
    return worksByAuthor.getDocsList().size();
  }`enter code here`


  public static class MyViewHolder extends RecyclerView.ViewHolder {
    private TextView bookTitle;
    //private TextView bookAuthor;

    public MyViewHolder(View itemView) {
      super(itemView);
      bookTitle = itemView.findViewById(R.id.bookTitle);
      //bookAuthor = itemView.findViewById(R.id.authorName);
    }
  }
}

我的结果活动类:

package com.example.mark.retrofitpractice_01;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.example.mark.retrofitpractice_01.model.ApiClient;
import com.example.mark.retrofitpractice_01.model.Docs;
import com.example.mark.retrofitpractice_01.model.WorksByAuthor;
import com.example.mark.retrofitpractice_01.service.ApiInterface;
import com.example.mark.retrofitpractice_01.service.AuthorAdapter;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class AuthorResutlActivity extends AppCompatActivity {

  private RecyclerView recyclerView;
  private RecyclerView.LayoutManager layoutManager;
  private AuthorAdapter authorAdapter;
  private WorksByAuthor worksByAuthor;
  private List<Docs> docsList;
  private ApiInterface apiInterface;

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

    Retrofit.Builder builder = new Retrofit.Builder()
        .baseUrl("https://openlibrary.org/")
        .addConverterFactory(GsonConverterFactory.create());

    Retrofit retrofit = builder.build();

    recyclerView = findViewById(R.id.recyclerViewAuthor);
    layoutManager = new LinearLayoutManager(this);
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setHasFixedSize(true);

    apiInterface = retrofit.create(ApiInterface.class);

    Intent intent = getIntent();
    String author = intent.getStringExtra("author");

    Call<WorksByAuthor> call = apiInterface.getAuthor(author);

    call.enqueue(new Callback<WorksByAuthor>() {
      @Override
      public void onResponse(Call<WorksByAuthor> call, Response<WorksByAuthor> response) {
        WorksByAuthor worksByAuthor = response.body();
        authorAdapter = new AuthorAdapter(worksByAuthor);
        recyclerView.setAdapter(authorAdapter);
      }

      @Override
      public void onFailure(Call<WorksByAuthor> call, Throwable t) {

      }
    });
  }
}

stacktrace:

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.mark.retrofitpractice_01, PID: 3808
                  java.lang.NullPointerException
                      at com.example.mark.retrofitpractice_01.service.AuthorAdapter.getItemCount(AuthorAdapter.java:48)
                      at android.support.v7.widget.RecyclerView.dispatchLayoutStep1(RecyclerView.java:3493)
                      at android.support.v7.widget.RecyclerView.onMeasure(RecyclerView.java:3019)
                      at android.view.View.measure(View.java:16525)
                      at android.widget.RelativeLayout.measureChild(RelativeLayout.java:689)
                      at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:473)
                      at android.view.View.measure(View.java:16525)
                      at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5127)
                      at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
                      at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:141)
                      at android.view.View.measure(View.java:16525)
                      at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5127)
                      at android.support.v7.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:400)
                      at android.view.View.measure(View.java:16525)
                      at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5127)
                      at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
                      at android.view.View.measure(View.java:16525)
                      at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5127)
                      at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
                      at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
                      at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
                      at android.view.View.measure(View.java:16525)
                      at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5127)
                      at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
                      at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2358)
                      at android.view.View.measure(View.java:16525)
                      at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1962)
                      at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1159)
                      at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1341)
                      at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1046)
                      at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5663)
                      at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
                      at android.view.Choreographer.doCallbacks(Choreographer.java:574)
                      at android.view.Choreographer.doFrame(Choreographer.java:544)
                      at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
                      at android.os.Handler.handleCallback(Handler.java:733)
                      at android.os.Handler.dispatchMessage(Handler.java:95)
                      at android.os.Looper.loop(Looper.java:136)
                      at android.app.ActivityThread.main(ActivityThread.java:5113)
                      at java.lang.reflect.Method.invokeNative(Native Method)
                      at java.lang.reflect.Method.invoke(Method.java:515)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:796)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612)
                      at dalvik.system.NativeStart.main(Native Method)
I/Process: Sending signal. PID: 3808 SIG: 9
Application terminated.

1 个答案:

答案 0 :(得分:1)

您可以使用我创建的此适配器类。你永远不会在这个类中得到NullPointerException。可能是你的列表为null,你在onItemCount方法中获得它的大小,就像Levi告诉的那样。

我建议您不要在适配器类中传递WorksByAuthor并仅传递arraylist。因为您的Adapter类应该是通用的。

通过以下适配器类,您需要调用adapter.insertItemsInList(pass_your_list)。 Adapter类本身将检查是否为null。

public class AdapterDemo extends RecyclerView.Adapter<AdapterDemo.MyViewHolder> {

    private ArrayList<String> list = new ArrayList<>();
    private Context context;

    class MyViewHolder extends RecyclerView.ViewHolder {

        MyViewHolder(View view) {
            super(view);
            // TODO: 4/29/2018 add your code here
        }
    }

    public void insertItemInList(String beanChat) {
        if (list == null) list = new ArrayList<>();
        list.add(beanChat);
        notifyItemInserted(list.size() - 1);
    }


    public void insertItemsInList(ArrayList<String> myList) {
        if (list == null) list = new ArrayList<>();
        for (String beanChat : myList) {
            insertItemInList(beanChat);
        }
    }

    public ArrayList<String> getList() {
        if (list == null) list = new ArrayList<>();
        return list;
    }

    public void clearList() {
        if (list == null) return;
        list.clear();
        notifyDataSetChanged();
    }


    public AdapterDemo(Context context) {
        this.context = context;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.layout_nothing_to_display, parent, false);

        return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        String s = list.get(position);

        // TODO: 4/29/2018  your code here
    }

    @Override
    public int getItemCount() {
        if (list == null) list = new ArrayList<>();
        return list.size();
    }
}