Estoy usando RecyclerView en un fragmento, se genera un NullPointerException y no puedo entender la razón.

Aquí está mi actividad de fragmento:

public class Recharges extends Fragment {

public RecyclerView recyclerView;
private List<GetRecharge> rechargeList = new ArrayList<>();
public RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
ImageView image1, image2;

@Nullable @Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    Toolbar myToolbar = (Toolbar) getActivity().findViewById(R.id.my_toolbar);
    ((AppCompatActivity) getActivity()).setSupportActionBar(myToolbar);

    View rootView = inflater.inflate(R.layout.recharges, container, false);

    recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerview1);
    recyclerView.setHasFixedSize(true);

    final FragmentActivity c = getActivity();

    layoutManager = new LinearLayoutManager(c);
    recyclerView.setLayoutManager(layoutManager);

    adapter = new Adapterrecharge(rechargeList);
    recyclerView.setAdapter(adapter);

    prepareRechargeData();

    return rootView;

}

private void prepareRechargeData() {
    GetRecharge recharge = new GetRecharge("Mad Max: Fury Road" );
    rechargeList.add(recharge);

    adapter.notifyDataSetChanged();
}

}

Aquí la clase de adaptador:

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

private List<GetRecharge> rechargeList;

public class MyViewHolder extends RecyclerView.ViewHolder {
    public TextView title;
    ImageView image;

    public MyViewHolder(View view) {
        super(view);
        title = (TextView) view.findViewById(R.id.title);
    }
}

public Adapterrecharge(List<GetRecharge> rechargeList) {
    this.rechargeList = rechargeList;
}

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

    return new MyViewHolder(itemView);
}

@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
    GetRecharge recharge = rechargeList.get(position);
    holder.title.setText(recharge.getTitle());
}

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

Parece que estoy inflando el diseño correcto pero sigo recibiendo el error. aquí está el error logcat

   java.lang.NullPointerException
   at com.example.aadesh.walletuncle.Adapterrecharge.onBindViewHolder(Adapterrecharge.java:53)
   at com.example.aadesh.walletuncle.Adapterrecharge.onBindViewHolder(Adapterrecharge.java:21)

Aquí está el diseño del elemento de reciclaje.

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/text"/>

Aquí está el diseño principal

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
xmlns:app="http://schemas.android.com/apk/res-auto">

<android.support.v7.widget.Toolbar
    android:id="@+id/my_toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    android:elevation="4dp"
    android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light">

    <TextView
        android:text="Recharge"
        android:textAppearance="@style/Base.TextAppearance.AppCompat.Large"
        android:textColor="#ffffff"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView4"
        android:layout_weight="1" />



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

<android.support.v7.widget.RecyclerView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:scrollbars="vertical"
    android:id="@+id/recyclerview1">


</android.support.v7.widget.RecyclerView>
1
choi saab 24 dic. 2016 a las 14:39

3 respuestas

La mejor respuesta

Hay un par de problemas

  1. está completando los datos de la lista prepareRechargeData () después de haber configurado su adaptador, por lo que su lista de recarga no tiene ningún dato

  2. en tu onCreateViewHolder() estás usando un diseño incorrecto R.layout.rechargelist

  3. en su vista Titular, está dando una identificación incorrecta para la vista de texto R.id.title

Prueba esto:

  @Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    Toolbar myToolbar = (Toolbar) getActivity().findViewById(R.id.my_toolbar);
    ((AppCompatActivity) getActivity()).setSupportActionBar(myToolbar);

    View rootView = inflater.inflate(R.layout.recharges, container, false);

    recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerview1);
    recyclerView.setHasFixedSize(true);

    final FragmentActivity c = getActivity();

    layoutManager = new LinearLayoutManager(c);
    recyclerView.setLayoutManager(layoutManager);

    /*recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.setAdapter((RecyclerView.Adapter) adapter);*/

    prepareRechargeData();
    adapter = new Adapterrecharge(rechargeList);
    recyclerView.setAdapter(adapter);
    adapter.notifyDataSetChanged();

    return rootView;

}

Cambie su adaptador a:

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

private List<GetRecharge> rechargeList;

public class MyViewHolder extends RecyclerView.ViewHolder {
    public TextView title;
    ImageView image;

    public MyViewHolder(View view) {
        super(view);
        title = (TextView) view.findViewById(R.id.text);
    }
}

public Adapterrecharge(List<GetRecharge> rechargeList) {
    this.rechargeList = rechargeList;
}

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

    return new MyViewHolder(itemView);
}

@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
    GetRecharge recharge = rechargeList.get(position);
    holder.title.setText(recharge.getTitle());
}

@Override
public int getItemCount() {
    return rechargeList.size();
}
}
0
rafsanahmad007 24 dic. 2016 a las 16:00

Te has perdido la identificación coincidente de Textview. En vez de

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
   <TextView
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:id="@+id/text"/>
</LinearLayout>

Utilice este

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
   <TextView
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:id="@+id/title"/>
</LinearLayout>

Como está utilizando la identificación incorrecta de Textview en la clase MyViewHolder.

0
Swapnil Meshram 24 dic. 2016 a las 12:20

El problema se debe a que los identificadores no coinciden. El ID de TextView en xml ("texto") y el que está inflado en la clase ViewHolder ("título") son diferentes.

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/text"/>

Clase de adaptador

public MyViewHolder(View view) {
    super(view);
    title = (TextView) view.findViewById(R.id.title);
}
0
Prince Bansal 24 dic. 2016 a las 12:22