使用循环视图时改进空引用

时间:2017-07-31 03:58:28

标签: java android nullpointerexception retrofit2

我正在尝试使用recycleview和cardview实现简单的改造示例。这是我的端点url http://anggitprayogo.com/api/user。但它在logcat中给我错误。

07-31 10:48:13.022 25960-25960/com.example.anggit.myacademic E/RecyclerView: No adapter attached; skipping layout 07-31 10:48:14.092 25960-25960/com.example.anggit.myacademic E/AndroidRuntime: FATAL EXCEPTION: main
                                                                               Process: com.example.anggit.myacademic, PID: 25960
                                                                               java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setAdapter(android.support.v7.widget.RecyclerView$Adapter)' on a null object reference
                                                                                   at com.example.anggit.myacademic.Fragment.SeminarFragment$1.onResponse(SeminarFragment.java:138)
                                                                                   at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:68)
                                                                                   at android.os.Handler.handleCallback(Handler.java:739)
                                                                                   at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                   at android.os.Looper.loop(Looper.java:135)
                                                                                   at android.app.ActivityThread.main(ActivityThread.java:5283)
                                                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                                                   at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)
                                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)

之后,应用程序崩溃了。

这是我的代码

Model.java

package com.example.anggit.myacademic.Model;

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

import java.util.List;

/**
 * Created by Anggit on 19/07/2017.
 */
public class Model {
    @SerializedName("user")
    @Expose
    private List<User> user = null;

    public List<User> getUser() {
        return user;
    }

    public void setUser(List<User> user) {
        this.user = user;
    }

    /**
     * Created by Anggit on 30/07/2017.
     */
    public static class User {
        @SerializedName("id")
        @Expose
        private Integer id;
        @SerializedName("created_at")
        @Expose
        private String createdAt;
        @SerializedName("updated_at")
        @Expose
        private String updatedAt;
        @SerializedName("username")
        @Expose
        private String username;
        @SerializedName("name")
        @Expose
        private String name;
        @SerializedName("email")
        @Expose
        private String email;
        @SerializedName("password")
        @Expose
        private String password;
        @SerializedName("img")
        @Expose
        private String img;
        @SerializedName("remember_token")
        @Expose
        private Object rememberToken;

        public Integer getId() {
            return id;
        }

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

        public String getCreatedAt() {
            return createdAt;
        }

        public void setCreatedAt(String createdAt) {
            this.createdAt = createdAt;
        }

        public String getUpdatedAt() {
            return updatedAt;
        }

        public void setUpdatedAt(String updatedAt) {
            this.updatedAt = updatedAt;
        }

        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        public String getName() {
            return name;
        }

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

        public String getEmail() {
            return email;
        }

        public void setEmail(String email) {
            this.email = email;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }

        public String getImg() {
            return img;
        }

        public void setImg(String img) {
            this.img = img;
        }

        public Object getRememberToken() {
            return rememberToken;
        }

        public void setRememberToken(Object rememberToken) {
            this.rememberToken = rememberToken;
        }
    }
}

UserApiInterface.java

package com.example.anggit.myacademic.RestApi;

import com.example.anggit.myacademic.Model.Model;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.GET;

/**
 * Created by Anggit on 30/07/2017.
 */
public interface UserApiInterface {
    @GET("user")
    Call<Model> getUsers();
}

SeminarAdapter.java

package com.example.anggit.myacademic.Adapter;

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.anggit.myacademic.Model.Model;
import com.example.anggit.myacademic.R;

import java.util.ArrayList;

/**
 * Created by Anggit on 30/07/2017.
 */
public class SeminarAdapter extends RecyclerView.Adapter<SeminarAdapter.ViewHolder>{
    private ArrayList<Model.User> android;

    public SeminarAdapter(ArrayList<Model.User> android) {
        this.android = android;
    }

    @Override
    public SeminarAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.single_seminar, viewGroup, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(SeminarAdapter.ViewHolder viewHolder, int i) {

        viewHolder.nama.setText(android.get(i).getName());
        viewHolder.username.setText(android.get(i).getUsername());
        viewHolder.email.setText(android.get(i).getEmail());
    }

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

    public class ViewHolder extends RecyclerView.ViewHolder{
        private TextView nama,username,email;
        public ViewHolder(View view) {
            super(view);

            nama = (TextView)view.findViewById(R.id.nama);
            username = (TextView)view.findViewById(R.id.username);
            email = (TextView)view.findViewById(R.id.email);

        }
    }
}

SeminarFragment.java

package com.example.anggit.myacademic.Fragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.anggit.myacademic.Adapter.SeminarAdapter;
import com.example.anggit.myacademic.Model.Model;
import com.example.anggit.myacademic.R;
import com.example.anggit.myacademic.RestApi.UserApiInterface;

import java.util.ArrayList;
import java.util.Arrays;

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

/**
 * Created by Anggit on 18/07/2017.
 */
public class SeminarFragment extends Fragment{

    private static final String TAG = "RecyclerViewFragment";
    private static final String KEY_LAYOUT_MANAGER = "layoutManager";

    public static final String BASE_API_URL = "http://anggitprayogo.com/api/";

    private RecyclerView recyclerView;
    private ArrayList<Model.User> data;
    private SeminarAdapter adapter;

    private enum LayoutManagerType {
        GRID_LAYOUT_MANAGER,
        LINEAR_LAYOUT_MANAGER
    }

    protected LayoutManagerType mCurrentLayoutManagerType;

    protected RecyclerView mRecyclerView;
    protected RecyclerView.LayoutManager mLayoutManager;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    public SeminarFragment() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_seminar, container, false);
        rootView.setTag(TAG);

        // BEGIN_INCLUDE(initializeRecyclerView)
        mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerViewSeminar);

        // LinearLayoutManager is used here, this will layout the elements in a similar fashion
        // to the way ListView would layout elements. The RecyclerView.LayoutManager defines how
        // elements are laid out.
        mLayoutManager = new LinearLayoutManager(getActivity());

        mCurrentLayoutManagerType = LayoutManagerType.LINEAR_LAYOUT_MANAGER;

        if (savedInstanceState != null) {
            // Restore saved layout manager type.
            mCurrentLayoutManagerType = (LayoutManagerType) savedInstanceState
                    .getSerializable(KEY_LAYOUT_MANAGER);
        }
        setRecyclerViewLayoutManager(mCurrentLayoutManagerType);

        loadJSON();

        return rootView;
    }

    public void setRecyclerViewLayoutManager(LayoutManagerType layoutManagerType) {
        int scrollPosition = 0;

        // If a layout manager has already been set, get current scroll position.
        if (mRecyclerView.getLayoutManager() != null) {
            scrollPosition = ((LinearLayoutManager) mRecyclerView.getLayoutManager())
                    .findFirstCompletelyVisibleItemPosition();
        }

        switch (layoutManagerType) {
            case GRID_LAYOUT_MANAGER:
                mLayoutManager = new GridLayoutManager(getActivity(), 60);
                mCurrentLayoutManagerType = LayoutManagerType.GRID_LAYOUT_MANAGER;
                break;
            case LINEAR_LAYOUT_MANAGER:
                mLayoutManager = new LinearLayoutManager(getActivity());
                mCurrentLayoutManagerType = LayoutManagerType.LINEAR_LAYOUT_MANAGER;
                break;
            default:
                mLayoutManager = new LinearLayoutManager(getActivity());
                mCurrentLayoutManagerType = LayoutManagerType.LINEAR_LAYOUT_MANAGER;
        }

        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.scrollToPosition(scrollPosition);
    }


    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        // Save currently selected layout manager.
        savedInstanceState.putSerializable(KEY_LAYOUT_MANAGER, mCurrentLayoutManagerType);
        super.onSaveInstanceState(savedInstanceState);
    }

    private void loadJSON(){
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_API_URL)
        .addConverterFactory(GsonConverterFactory.create())
                .build();
        UserApiInterface request = retrofit.create(UserApiInterface.class);
        Call<Model> call = request.getUsers();
        call.enqueue(new Callback<Model>() {
            @Override
            public void onResponse(Call<Model> call, Response<Model> response) {

                Model jsonResponse = response.body();
                data = new ArrayList<>(jsonResponse.getUser());
                adapter = new SeminarAdapter(data);
                recyclerView.setAdapter(adapter);
            }

            @Override
            public void onFailure(Call<Model> call, Throwable t) {
                Log.d("Error", t.getMessage());
            }
        });
    }

}

这是我的布局xml 的 fragment_seminar.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/recyclerViewSeminar"></android.support.v7.widget.RecyclerView>
</LinearLayout>

代码完全像我上面的附件。

感谢帮助..

0 个答案:

没有答案