改造:java.lang.NullPointerException

时间:2017-09-20 17:39:19

标签: android retrofit2

NullPointerException并且没有附加适配器;每次我在gennymotion上测试这个应用程序时都会跳过布局。我已经阅读了与同一问题相关的其他问题,但没有任何帮助。

logcat的

09-20 13:21:13.738 4658-4658 / com.example.kiran.detailapp E / AndroidRuntime:FATAL EXCEPTION:main                                                                            过程:com.example.kiran.detailapp,PID:4658                                                                            java.lang.NullPointerException:尝试调用接口方法' int java.util.List.size()'在null对象引用上                                                                                在com.example.kiran.detailapp.RecyclerAdapter.getItemCount(RecyclerAdapter.java:38)                                                                                在android.support.v7.widget.RecyclerView.dispatchLayoutStep1(RecyclerView.java:3493)                                                                                在android.support.v7.widget.RecyclerView.onMeasure(RecyclerView.java:3019)                                                                                在android.view.View.measure(View.java:17430)                                                                                在android.widget.RelativeLayout.measureChild(RelativeLayout.java:697)                                                                                在android.widget.RelativeLayout.onMeasure(RelativeLayout.java:481)                                                                                在android.view.View.measure(View.java:17430)                                                                                在android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)                                                                                在android.widget.FrameLayout.onMeasure(FrameLayout.java:430)                                                                                在android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)                                                                                在android.view.View.measure(View.java:17430)                                                                                在android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)                                                                                在android.support.v7.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:393)                                                                                在android.view.View.measure(View.java:17430)                                                                                在android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)                                                                                在android.widget.FrameLayout.onMeasure(FrameLayout.java:430)                                                                                在android.view.View.measure(View.java:17430)                                                                                在android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)                                                                                在android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)                                                                                在android.widget.LinearLayout.measureVertical(LinearLayout.java:722)                                                                                在android.widget.LinearLayout.onMeasure(LinearLayout.java:613)                                                                                在android.view.View.measure(View.java:17430)                                                                                在android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)                                                                                在android.widget.FrameLayout.onMeasure(FrameLayout.java:430)                                                                                在com.android.internal.policy.impl.PhoneWindow $ DecorView.onMeasure(PhoneWindow.java:2560)                                                                                在android.view.View.measure(View.java:17430)                                                                                在android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2001)                                                                                在android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1166)                                                                                在android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1372)                                                                                在android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1054)                                                                                在android.view.ViewRootImpl $ TraversalRunnable.run(ViewRootImpl.java:5779)                                                                                在android.view.Choreographer $ CallbackRecord.run(Choreographer.java:767)                                                                                在android.view.Choreographer.doCallbacks(Choreographer.java:580)                                                                                在android.view.Choreographer.doFrame(Choreographer.java:550)                                                                                在android.view.Choreographer $ FrameDisplayEventReceiver.run(Choreographer.java:753)                                                                                在android.os.Handler.handleCallback(Handler.java:739)                                                                                在android.os.Handler.dispatchMessage(Handler.java:95)                                                                                在android.os.Looper.loop(Looper.java:135)                                                                                在android.app.ActivityThread.main(ActivityThread.java:5221)                                                                                at java.lang.reflect.Method.invoke(Native Method)                                                                                在java.lang.reflect.Method.invoke(Method.java:372)                                                                                在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:899)                                                                                在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

Contact.java

package com.example.kiran.detailapp;
import com.google.gson.annotations.SerializedName;
public class Contact {
    @SerializedName("name")
    private String Name;

    @SerializedName("email")
    private String Email;

    public String getName() {
        return Name;
    }

    public void setName(String name) {
        Name = name;
    }

    public String getEmail() {
        return Email;
    }

    public void setEmail(String email) {
        Email = email;
    }
}

ApiClient.java

    package com.example.kiran.detailapp;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class ApiClient {

    public static final String BASE_URL = "http://10.0.3.2/ContactApp/";

    public static Retrofit retrofit = null;

    public static Retrofit getApiClient()
    {
        retrofit = new Retrofit.Builder().baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create()).build();
        return retrofit;
    }
}

ApiInterface.java

    package com.example.kiran.detailapp;

import java.util.List;

import retrofit2.Call;
import retrofit2.http.POST;
public interface ApiInterface {


    @POST("ReadContacts.php")
    Call<List<Contact>> getContacts();
}

RecyclerAdapter.java

    package com.example.kiran.detailapp;

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

import org.w3c.dom.Text;

import java.util.List;

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

    private List<Contact> contacts;
    public RecyclerAdapter(List<Contact> contacts)
    {
        this.contacts = contacts;
    }

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

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        holder.Name.setText(contacts.get(position).getName());
        holder.Email.setText(contacts.get(position).getEmail());
    }

    @Override
    public int getItemCount() {
        return contacts.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {
        TextView Name,Email;
        public MyViewHolder(View itemView) {
            super(itemView);
            Name = (TextView) itemView.findViewById(R.id.name);
            Email = (TextView) itemView.findViewById(R.id.email);

        }
    }
}

MainActivity.java

    package com.example.kiran.detailapp;

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

import java.util.List;

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

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private RecyclerView.LayoutManager layoutManager;
    private RecyclerAdapter adapter;
    private List<Contact> contacts;
    private ApiInterface apiInterface;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        adapter = new RecyclerAdapter(contacts);
        recyclerView = (RecyclerView) findViewById(R.id.Recycleview);
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setHasFixedSize(true);

        apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
        Call<List<Contact>> call = apiInterface.getContacts();
        call.enqueue(new Callback<List<Contact>>() {
            @Override
            public void onResponse(Call<List<Contact>> call, Response<List<Contact>> response) {
                contacts = response.body();

                recyclerView.setAdapter(adapter);
                adapter.notifyDataSetChanged();
            }

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

            }
        });
    }
}

2 个答案:

答案 0 :(得分:2)

你忘了初始化arraylist

 private List<Contact> contacts;

然后在onCreate()执行此操作

contacts= new ArrayList<>();

答案 1 :(得分:1)

我在代码中看到了一些问题。

1)你的contacts var在适配器内未初始化。

2)您已在后台线程中运行的onResponse方法中设置了recyclelerview。

<强>解决方案:

您需要初始化联系人,然后在onResponse方法中为其提供值,并在activity's runOnUiThread方法上设置适配器。

希望这段代码有用。

1)初始化联系人

private List<Contact> contacts = new ArrayList<>();

2)在onResponse方法中给出预期值并在那里初始化适配器并从onCreate方法中删除初始化。

call.enqueue(new Callback<List<Contact>>() {
        @Override
        public void onResponse(Call<List<Contact>> call, Response<List<Contact>> response) {
            contacts = response.body();
            adapter = new RecyclerAdapter(contacts);
            runOnUiThread(() -> {
                recyclerView.setAdapter(adapter);
                adapter.notifyDataSetChanged();
            });

        }

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

        }