使用RecyclerView

时间:2016-06-27 07:48:12

标签: android nullpointerexception android-recyclerview android-cardview recycler-adapter

我已经构建了一个RecyclerView,为此我有一个CardAdapter。以下是文件:

public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> {

private ImageLoader imageLoader;
private Context context;

//List of Workers
List<Worker> workersList;

public class ViewHolder extends RecyclerView.ViewHolder{
    //   public NetworkImageView imageView;
    public TextView textViewName=new TextView(context);
    public RatingBar ratingBar;

    public ViewHolder(View itemView) {
        super(itemView);
itemView.findViewById(R.id.profile_image);
        textViewName = (TextView) itemView.findViewById(R.id.WorkerName);
        ratingBar = (RatingBar) itemView.findViewById(R.id.ratingBar);
        Log.d("Workername",ratingBar.toString());  //no NPE error
    }
}

public CardAdapter(List<Worker> workersList, Context context){
    super();
    //Getting all the workers
    this.workersList = workersList;
    this.context = context;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.workers_list_view, parent, false);
    Log.d("view",v.toString());
    ViewHolder viewHolder = new ViewHolder(v);
    Log.d("textView",viewHolder.textViewName.toString());  //NPEerror on textView
    return viewHolder;
}

@Override
public void onBindViewHolder(ViewHolder holder, final int position) {
    Log.d("pos",""+position);
    Worker worker =  workersList.get(position);
    Log.d("worker",""+worker.getName());
    holder.textViewName.setText(worker.getName());
    holder.ratingBar.setNumStars(worker.getRating());
 }

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

以下是布局文件workers_list_view.xml:

    <android.support.v7.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/cv"
    app:cardBackgroundColor="@color/colorPrimaryDark"
    android:elevation="5dp"
    card_view:cardCornerRadius="@dimen/card_album_radius">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="6dp"
        >

        <LinearLayout
            android:id="@+id/thumbnail"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_marginRight="5dip"
            android:padding="3dip" >

            <ImageView
                android:id="@+id/profile_image"
                android:layout_width="96dp"
                android:layout_height="96dp"
                android:src="@drawable/cover"
                />

        </LinearLayout>

        <TextView
            android:id="@+id/WorkerName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="Name of worker"
            android:layout_alignTop="@+id/thumbnail"
            android:layout_toRightOf="@+id/button2"
            android:layout_toEndOf="@+id/button2" />

        <RatingBar
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/ratingBar"
            android:layout_centerVertical="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true" />

    </RelativeLayout>

</android.support.v7.widget.CardView>

以下是我得到的错误的堆栈跟踪:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.widget.TextView.toString()' on a null object reference
at com.appshaala.vorkal.app.CardAdapter.onCreateViewHolder(CardAdapter.java:60)
at com.appshaala.vorkal.app.CardAdapter.onCreateViewHolder(CardAdapter.java:25)
at android.support.v7.widget.RecyclerView$Adapter.createViewHolder(RecyclerView.java:5482)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4707)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4617)
at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:1994)
at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1390)
at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1353)
at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:574)
at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3028)
at android.support.v7.widget.RecyclerView.onMeasure(RecyclerView.java:2625)
at android.view.View.measure(View.java:18809)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5954)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
at android.view.View.measure(View.java:18809)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5954)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
at android.view.View.measure(View.java:18809)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5954)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
at android.view.View.measure(View.java:18809)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5954)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
at android.view.View.measure(View.java:18809)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5954)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)
at android.view.View.measure(View.java:18809)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5954)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
at com.android.internal.policy.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2643)
at android.view.View.measure(View.java:18809)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2112)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1228)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1464)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1119)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6060)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
at android.view.Choreographer.doCallbacks(Choreographer.java:670)
at android.view.Choreographer.doFrame(Choreographer.java:606)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
at android.os.Handler.handleCallback(Handler.java:746)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)

我调试了代码,发现ViewHolder和ratingBar不为null。它只是带有id WorkerName的textView,它持有空值。我坚持这个错误。

我正在添加我正在使用此卡适配器的类:

 public class ViewWorkerList extends AppCompatActivity {

//Creating a List of workers
private List<Worker> listWorkers;

//Creating Views
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private CardAdapter adapter;

String url = "http://vorkal.com/read_data.php";
ArrayList<HashMap<String, String>> Item_List;
public static final String KEY_SERVICE = "service";

private String service;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Toast.makeText(getApplicationContext(),"2nd page",Toast.LENGTH_LONG);
    Log.d("2pg","2page");
    Intent intent = getIntent();
    service = intent.getStringExtra("service"); //if it's a string you stored.
    setContentView(R.layout.worker_list_main);

    //Initializing our workers list
    listWorkers = new ArrayList<>();
    Worker worker=new Worker();
    worker.setImageUrl("http://vorkal.com/images/vorkal_cover.PNG");
    worker.setName("name");
    worker.setLocation("location");
    worker.setRating(5);
    worker.setId(1);
    worker.setPhone(784512369);
    worker.setOccupation("occupation");
    worker.setPrice(20);
    worker.setReview("Review");
    listWorkers.add(worker);

    /*
    getData();
    //Log.d("listWorkers",listWorkers.get(0).getName());
    //Initializing Views
    recyclerView = (RecyclerView) findViewById(R.id.recyclerView);

    //recyclerView.setAdapter(new CardAdapter(listWorkers, this));
    recyclerView.setHasFixedSize(true);
    layoutManager = new LinearLayoutManager(this);
    recyclerView.setLayoutManager(layoutManager);
    //Finally initializing our adapter
    adapter = new CardAdapter(listWorkers, this);

    //Adding adapter to recyclerview
    recyclerView.setAdapter(adapter);*/

    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Log.d("2pg",response);
                    Toast.makeText(getApplicationContext(),response,Toast.LENGTH_LONG).show();
                    recyclerView = (RecyclerView) findViewById(R.id.recyclerView);

                    //recyclerView.setAdapter(new CardAdapter(listWorkers, this));
                    recyclerView.setHasFixedSize(true);
                    layoutManager = new LinearLayoutManager(getApplicationContext());
                    recyclerView.setLayoutManager(layoutManager);
                    //Finally initializing our adapter
                    adapter = new CardAdapter(listWorkers, getApplicationContext());
                    recyclerView.setAdapter(adapter);
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(getApplicationContext(),error.toString(),Toast.LENGTH_LONG).show();
                }
            }){
        @Override
        protected Map<String,String> getParams(){
            Map<String,String> params = new HashMap<String, String>();
            params.put("tag", "get_list");
            params.put("service", service);
            return params;
        }

    };

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
}

}

2 个答案:

答案 0 :(得分:2)

这是因为当您在Textview中使用textview.toString()时<{1}}为空

onCreateViewHolder()

将这两个陈述移至Log.d("view",v.toString()); Log.d("textView",viewHolder.textViewName.toString()); 。希望能解决你的问题

编辑:答案根据您编辑的问题。

你可以尝试这样的事吗

onBindViewHolder()

答案 1 :(得分:0)

您必须使用以下代码: -

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.workers_list_view, parent, false);

  textViewName = (TextView) v.findViewById(R.id.WorkerName);
    Log.d("view",textViewName.toString());
    ViewHolder viewHolder = new ViewHolder(v);
    Log.d("textView",textViewName);  //NPEerror on textView
    return viewHolder;
}

这里我们已经声明了tvname,然后从中获取文本。