简体   繁体   中英

How to fix 'Attempt to invoke 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference' error in Android

I've been trying to setup a new custom ArrayAdapter for a layout element in Android (something that I have done dozens of times) but it seems I've been getting a null object reference error somewhere in my code whenever I start the activity.

I have checked every detail and nothing seems to be out of the ordinary.

My CustomAdapter file (CustomAdapterRangliste):

package ba.unsa.etf.rma.klase;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.ArrayList;

import ba.unsa.etf.rma.R;

public class CustomAdapterRangliste extends ArrayAdapter<RangLista> {
    private Context mContext;
    private int resources;
    private ArrayList<RangLista> rang;

    public CustomAdapterRangliste(Context context, int res, ArrayList<RangLista> rang) {
        super(context, res, rang);
        mContext = context;
        resources = res;
        this.rang = rang;
    }



    public View getView(int position, View convertView, ViewGroup parent) {

        LayoutInflater inflater = LayoutInflater.from(mContext);
        convertView = inflater.inflate(R.layout.rangliste, parent, false);
         //View view = inflater.inflate(R.layout.activity_igraj_kviz_akt, null);

        TextView textView = (TextView) convertView.findViewById(R.id.etRangliste);
        final RangLista rangIgraca = rang.get(position);
        textView.setText(rangIgraca.toString());
        return convertView;
    }
}

The layout element (rangliste.xml)

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/etRangliste"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="696dp"
        android:text="TextView"
        android:textSize="24sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

Code that I use to initialize and bind the CustomAdapter (in an activity implementing the fragment):

  final ListView rangLista = (ListView) findViewById(R.id.lvRanglista);
        final ArrayList<RangLista> ranking = new ArrayList<>();
        final CustomAdapterRangliste rangAdapter = new CustomAdapterRangliste(this, R.layout.rangliste, ranking);
        rangLista.setAdapter(rangAdapter);

The layout file with the ListView element (fragment_ranglista.xml):

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".fragmenti.RanglistaFrag">

    <!-- TODO: Update blank fragment layout -->

    <ListView
        android:id="@+id/lvRanglista"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#4FD80000"
        android:scrollbars="vertical" />

</FrameLayout>

Fragment file:

package ba.unsa.etf.rma.fragmenti;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import ba.unsa.etf.rma.R;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link RanglistaFrag.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link RanglistaFrag#newInstance} factory method to
 * create an instance of this fragment.
 */
public class RanglistaFrag extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public RanglistaFrag.OnFragmentInteractionListener2 mListener;
    public void postaviListener (RanglistaFrag.OnFragmentInteractionListener2 mListener)
    {
        this.mListener=mListener;
    }
    public RanglistaFrag() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment ba.unsa.etf.rma.fragmenti.RanglistaFrag.
     */
    // TODO: Rename and change types and number of parameters
    public static RanglistaFrag newInstance(String param1, String param2) {
        RanglistaFrag fragment = new RanglistaFrag();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_ranglista, container, false);
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
    /*    if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }*/
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        /*if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }*/
    }

    @Override
    public void onDetach() {
        super.onDetach();
       // mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener2 {
        // TODO: Update argument type and name
        public void azuriranjeRangliste();
    }
}

I can't figure out what I've been doing wrong, none of the similar questions helped me, I checked for lines that were left out but without success

The error means that when you call this rangLista.setAdapter(rangAdapter); the variable rangLista is null. This can happen in multiple ways, but what I'd check first is if you're inflating the correct layout, because most likely the line findViewById(R.id.lvRanglista); is returning null.

Check if your layout file contains the list view with the id you're using in findViewById .

确保TextView与R.layout.rangliste文件中的ID链接

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM