Home > Software design >  How to implement a listview with an adapter in a fragment in Android Studio
How to implement a listview with an adapter in a fragment in Android Studio

Time:03-14

I'm new to Android Studio and I'm trying to implement a listview in a fragment with an adapter. After launching my application I have this error message

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference

It seems to be something with my adapter. Here's my code:

MainActivity.java

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA)
                == PackageManager.PERMISSION_DENIED){
            ActivityCompat.requestPermissions(MainActivity.this, new String[] {Manifest.permission.CAMERA}, 123);
        } else {
        }

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation);
        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new HomeFragment()).commit();

        bottomNav.setSelectedItemId(R.id.nav_home);

        bottomNav.setOnItemSelectedListener(new NavigationBarView.OnItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                Fragment fragment = null;

                switch (item.getItemId()){

                   case R.id.nav_home:
                       fragment = new HomeFragment();
                        break;
                    case R.id.nav_profil:
                        fragment = new ProfilFragment();
                        break;
                   case R.id.nav_camera:
                      fragment = new CameraFragment();
                        break;

                }

                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, fragment).commit();
                return true;
        }

   });

}

}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    tools:context=".MainActivity">

    <FrameLayout
        android:id="@ id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@ id/bottom_navigation"/>

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@ id/bottom_navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        app:menu="@menu/bttom_navigation"
        app:itemIconTint="@color/white"
        android:background="@android:color/holo_blue_dark"/>

</RelativeLayout>

HomeFragment.java

public class HomeFragment extends Fragment {

    String mTitle[] = {"1987", "Congorama", "Bon cop bad cop 2"};
    String mDescription[] = {"Lieu: Québec", "Lieu: Saint-Michel", "Lieu: Montréal"};
    int images[] = {R.drawable.mille, R.drawable.congorama, R.drawable.bcb2};


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

        View view = inflater.inflate(R.layout.fragment_home, container, false);

        ListView listView = (ListView) getActivity().findViewById(R.id.Listview);
        MyAdapter myadapter = new MyAdapter( getContext(), mTitle, mDescription, images);
        listView.setAdapter(myadapter);

        // Inflate the layout for this fragment
        return view;
    }

}

fragment_home.xml

<?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">

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@ id/Listview"
        >

    </ListView>
</LinearLayout>

MyAdapter.java

public class MyAdapter extends BaseAdapter {

    Context context;
    String listFilm[];
    String lieuFilm[];
    int listImages[];
    LayoutInflater inflater;

    public MyAdapter(Context ctx, String[] nomFilm, String[] desFilm, int[] images ){

        this.context = ctx;
        this.listFilm = nomFilm;
        this.lieuFilm = desFilm;
        this.listImages = images;
        inflater = LayoutInflater.from(ctx);


    }

    @Override
    public int getCount() {
        return listFilm.length;
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        convertView = inflater.inflate(R.layout.row, null);
        TextView txtview = (TextView) convertView.findViewById(R.id.textView1);
        TextView txtview2 = (TextView)  convertView.findViewById(R.id.textView2);
        ImageView imgview = (ImageView) convertView.findViewById(R.id.image);

        txtview.setText(listFilm[position]);
        txtview2.setText(lieuFilm[position]);
        imgview.setImageResource(listImages[position]);
        return convertView;
    }
}

row.xml

<?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="wrap_content"
    android:orientation="horizontal"
    android:padding="16dp">

    <ImageView
        android:layout_width="75dp"
        android:layout_height="75dp"
        android:src="@mipmap/ic_launcher"
        android:id="@ id/image"
        />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Main Title"
        android:textColor="#000"
        android:layout_margin="5dp"
        android:textSize="20sp"
        android:id="@ id/textView1"
        />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Sub Title"
            android:textColor="#a9a9a9"
            android:layout_margin="5dp"
            android:textSize="15sp"
            android:id="@ id/textView2"
            />

    </LinearLayout>

</LinearLayout>

The error points out to the line 32 of my HomeFragment, wHich is my listView.setAdapter(myadapter);

CodePudding user response:

No, there is nothing wrong with your adapter, but it is wrong with your listview.

HomeFragment.java

    public class HomeFragment extends Fragment {
    
        String mTitle[] = {"1987", "Congorama", "Bon cop bad cop 2"};
        String mDescription[] = {"Lieu: Québec", "Lieu: Saint-Michel", "Lieu: Montréal"};
        int images[] = {R.drawable.mille, R.drawable.congorama, R.drawable.bcb2};
    
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
    
            View view = inflater.inflate(R.layout.fragment_home, container, false);
    

...

            ListView listView = (ListView) view.findViewById(R.id.Listview); //use listview from inflater view instead of getActivity
          
...

  MyAdapter myadapter = new MyAdapter( getContext(), mTitle, mDescription, images);
            listView.setAdapter(myadapter);
    
            // Inflate the layout for this fragment
            return view;
        }
    
    }

CodePudding user response:

public class HomeFragment extends Fragment {

String mTitle[] = {"1987", "Congorama", "Bon cop bad cop 2"};
String mDescription[] = {"Lieu: Québec", "Lieu: Saint-Michel", "Lieu: Montréal"};
int images[] = {R.drawable.mille, R.drawable.congorama, R.drawable.bcb2};


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

    View view = inflater.inflate(R.layout.fragment_home, container, false);

    ListView listView = (ListView) getActivity().findViewById(R.id.Listview);
    MyAdapter myadapter = new MyAdapter( getContext(), mTitle, mDescription, images);
    listView.setAdapter(myadapter);

    // Inflate the layout for this fragment
    return view;
}

}

You have to use :=

ListView listView = (ListView) view.findViewById(R.id.Listview);

instead of this code :=

ListView listView = (ListView) getActivity().findViewById(R.id.Listview);

  • Related