0

i am trying to add a listview wich shows the clients, at first just name and visit adress. Have never used listview before and nog keep getting a NPE on line MainActivity.java:86. havent filled or used all field of client. but just want it to work first before i continue. here is my code

Main Activity package com.huntercrm.hunteronline.app.Activities.Main;

import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.example.hunteronlinebeta.app.R;
import com.huntercrm.hunteronline.app.Activities.Main.Drawer.HunterDrawerItems;
import com.huntercrm.hunteronline.app.Activities.Main.Fragments.AddClientsFragment;
import com.huntercrm.hunteronline.app.Activities.Main.Fragments.Clients;
import com.huntercrm.hunteronline.app.Activities.Main.Fragments.SettingsFragment;
import com.mikepenz.materialdrawer.Drawer;
import com.mikepenz.materialdrawer.DrawerBuilder;
import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem;
import java.util.ArrayList;
import java.util.List;


public class MainActivity extends AppCompatActivity {

    private List<Clients> ClientsArray = new ArrayList<Clients>();


    FragmentManager manager;
    private Drawer result;
    boolean login = true;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        manager = getFragmentManager();




        populateClientsList();
        populateListView();

        if(!login){
            Intent intent = new Intent(this, LogInActivity.class);
            startActivity(intent);
        }

        HunterDrawerItems hunterDrawerItems = new HunterDrawerItems(manager);
        IDrawerItem[] drawerItemsArray = new IDrawerItem[hunterDrawerItems.size()];
        hunterDrawerItems.toArray(drawerItemsArray);

        result = new DrawerBuilder()
                .withTranslucentStatusBar(false)
                .withActionBarDrawerToggle(false)
                .withActivity(this)
                .addDrawerItems(drawerItemsArray)
                .build();



    }

    //------------------------------------------------------------------------------------------------------------------

    private void populateClientsList(){
        ClientsArray.add(new Clients("oscar", "0616397853", "oscar@gmail.com", "oscar.com", 11111.11, "Akkrum"));
        ClientsArray.add(new Clients("Ricky", "0612345678", "Ricky@gmail.com", "ricky.com", 222222.22, "ergens"));
        ClientsArray.add(new Clients("Jan", "0623456789", "Jan@gmail.com", "jan.com", 333333.33, "nergens"));
        ClientsArray.add(new Clients("Casper", "0687654321", "Casper@gmail.com", "casper.com", 444444.44, "bij jan"));
        ClientsArray.add(new Clients("John", "0698765432", "John@gmail.com", "john.com", 555555.55, "tinboektoe"));
    }



    private void populateListView(){
        ArrayAdapter<Clients> adapter = new MyListAdapter();
        ListView clientList = (ListView) findViewById(R.id.list);
        // NPE happens in line below
        clientList.setAdapter(adapter);

    }

    private class MyListAdapter extends ArrayAdapter<Clients>{
        public MyListAdapter(){
            super(MainActivity.this, R.layout.clients_view, ClientsArray);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View clientsView = convertView;
            if (clientsView == null){
                clientsView = getLayoutInflater().inflate(R.layout.clients_view, parent, false);
            }

            Clients currentClient = ClientsArray.get(position);

            TextView nameText = (TextView)clientsView.findViewById(R.id.text_name);
            nameText.setText(currentClient.getName());

            TextView visitAddressText = (TextView)clientsView.findViewById(R.id.text_visitCity);
            visitAddressText.setText(currentClient.getVisitAddress());

            return clientsView;
        }
    }

    //------------------------------------------------------------------------------------------------------------------

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_drawer:
                result.openDrawer();
                break;
            case R.id.action_settings:
                SettingsFragment sf = new SettingsFragment();
                FragmentTransaction transaction = manager.beginTransaction();
                transaction.replace(R.id.group, sf, "sfrag");
                transaction.commit();
                break;
            case R.id.action_log_in:
                Intent intent = new Intent(this, LogInActivity.class);
                startActivity(intent);
                break;
            case R.id.action_log_off:
                break;
        }

        return super.onOptionsItemSelected(item);
    }

    public void addClient (View v){
        AddClientsFragment acf = new AddClientsFragment();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.replace(R.id.group, acf, "acfrag");
        transaction.commit();
    }

    public void clearFields (View v){
        AddClientsFragment acf = new AddClientsFragment();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.replace(R.id.group, acf, "acfrag");
        transaction.commit();
    }
}

Clients class (out commented a lot of fields, this is purely a test)

package com.huntercrm.hunteronline.app.Activities.Main.Fragments;

import java.math.BigDecimal;

/**
 * Created by Oscar on 19-02-16.
 */
public class Clients {
    private String Name;
    private String Phone;
    private String Email;
    private String URL;
    private Double Turnover;
    private String VisitAddress;
    private String VisitCity;
    private String VisitZipcode;
    private String VisitCountry;
    private String PostalAddress;
    private String PostalCity;
    private String PostalZipcode;
    private String PostalCountry;




    public Clients(String Name, String Phone, String Email, String URL, Double Turnover, String VisitCity){
//                   String VisitAddress, String VisitCity, String VisitZipcode, String VisitCountry,
//                   String PostalAddress, String PostalCity, String PostalZipcode, String PostalCountry){
            super();
            this.Name = Name;
            this.Phone = Phone;
            this.Email = Email;
            this.URL = URL;
            this.Turnover = Turnover;
            this.VisitAddress = VisitAddress;
            this.VisitCity = VisitCity;
            this.VisitZipcode = VisitZipcode;
            this.VisitCountry = VisitCountry;
            this.PostalAddress = PostalAddress;
            this.PostalCity = PostalCity;
            this.PostalZipcode = PostalZipcode;
            this.PostalCountry = PostalCountry;



    }


    public String getName() {
        return Name;
    }

    public String getPhone() {
        return Phone;
    }

    public String getEmail() {
        return Email;
    }

    public String getURL() {
        return URL;
    }

    public Double getTurnover() {
        return Turnover;
    }

    public String getVisitAddress() {
        return VisitAddress;
    }

    public String getVisitCity() {
        return VisitCity;
    }

    public String getVisitZipcode() {
        return VisitZipcode;
    }

    public String getVisitCountry() {
        return VisitCountry;
    }

    public String getPostalAddress() {
        return PostalAddress;
    }

    public String getPostalCity() {
        return PostalCity;
    }

    public String getPostalZipcode() {
        return PostalZipcode;
    }

    public String getPostalCountry() {
        return PostalCountry;
    }

}

Clients Fragement (shows client list)

package com.huntercrm.hunteronline.app.Activities.Main.Fragments;

import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.hunteronlinebeta.app.R;

public class ClientsFragment extends Fragment {

    public ClientsFragment(){
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View rootView = inflater.inflate(R.layout.fragment_clients,
                container, false);

        return rootView;
    }

}

Clients Fragment XML

<RelativeLayout 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="com.huntercrm.hunteronline.app.Activities.Main.Fragments.ClientsFragment">

    <ListView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/list"
            android:layout_alignParentTop="true"
            android:layout_alignParentStart="true"
            android:layout_above="@+id/addClient"/>

    <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Add Client"
            android:id="@+id/addClient"
            android:onClick="addClient"
            android:layout_alignParentBottom="true" android:layout_alignParentStart="true"
            android:layout_alignParentEnd="true"/>


</RelativeLayout>

Clients view XML (layout for listview)

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


    <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="30sp"
            android:text="name will be shown here"
            android:id="@+id/text_name"
            android:layout_alignParentTop="true"
            android:layout_alignParentStart="true"/>
    <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="visit address will be shown here"
            android:textSize="20sp"
            android:id="@+id/text_visitCity"
            android:layout_marginTop="25dp"
            android:layout_below="@+id/text_name"
            android:layout_alignParentEnd="true"/>
</RelativeLayout>

Logcat:

02-22 14:24:56.730    9638-9638/com.example.hunteronlinebeta.app D/AndroidRuntime﹕ Shutting down VM
02-22 14:24:56.730    9638-9638/com.example.hunteronlinebeta.app E/AndroidRuntime﹕ FATAL EXCEPTION: main Process: com.example.hunteronlinebeta.app, PID: 9638
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.hunteronlinebeta.app/com.huntercrm.hunteronline.app.Activities.Main.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2808)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2873)
at android.app.ActivityThread.access$900(ActivityThread.java:181)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1482)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6145)
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:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at com.huntercrm.hunteronline.app.Activities.Main.MainActivity.populateListView(MainActivity.java:86)
at com.huntercrm.hunteronline.app.Activities.Main.MainActivity.onCreate(MainActivity.java:49)
at android.app.Activity.performCreate(Activity.java:6374)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2752)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2873)
at android.app.ActivityThread.access$900(ActivityThread.java:181)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1482)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6145)
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:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
D.Blazer
  • 192
  • 1
  • 2
  • 12
  • your ListView is null. – Shark Feb 22 '16 at 13:32
  • Looks like `clientsListView` is not available in layout `activity_main` – Rohit5k2 Feb 22 '16 at 13:34
  • @shark, i know that my ListView is empty, a hint on why or how to fix this would be nice though, intead of stating the obvious – D.Blazer Feb 23 '16 at 14:30
  • I see that you misunderstood me... You "keep getting NPE when trying to set adapter", and I'm telling you that your listView is null and that you have to make sure it's not null before setting the adapter. Stating the obvious would be `"marked for closure -> off-topic > "why isn't this code working"`. ListView being null has nothing to do with it being empty. – Shark Feb 23 '16 at 14:58

1 Answers1

3

This is the id of your ListView in the layout:

android:id="@+id/list"

This is how you are trying to find it in your activity onCreate():

clientlist = (ListView) findViewById(R.id.clientsListView)

The ids don't match, you can't find the view and you get a NPE.

Danail Alexiev
  • 7,624
  • 3
  • 20
  • 28
  • My apologies, that was a leftover from me trying to fix the problem myself. edited my code. this does not solve the problem though, get same NPE on same location – D.Blazer Feb 22 '16 at 13:58
  • @D.Blazer So, it looks like the `ListView` is in your fragment and you are trying to set it's adapter from the hosting activity. Is this right? If so, you should totally change your approach. Move all code, related to the `ListView` - initialising a class field, setting the adapter, etc. to the fragment that actually hosts it, and add this fragment to the activity. Right now I can't even find the code where you add your fragment to the view. – Danail Alexiev Feb 22 '16 at 14:03
  • Thx, moving the code fixed my problem. – D.Blazer Feb 23 '16 at 08:20
  • still cant get my custom adapter working cause of empty Listview. been looking everywhere. might be i am reading around it. but cant seem to find the flaw in my code that makes it stay empty. declaring it like `ListView clientsView = (ListView)getActivity().findViewById(android.R.id.list);` id in html is `android:id="@android:id/list"` but clientsView stays null here. and cant find anything online that is about this problem specific – D.Blazer Feb 23 '16 at 14:25
  • @D.Blazer you are still trying to find your `ListView` via the activity. This is wrong. You should move the `clientsView` initialisation to the `onViewCreated()` or `onCreateView()` method in the fragment. There you have the inflated fragment view and you can find it using `findViewById()`. Don't forget to actually set the adapter to your list and put data into it. If after you have added data nothing is shown, maybe you forgot to call `notifyDataSetChanged()`. – Danail Alexiev Feb 23 '16 at 14:37
  • Yes, that fixed it. thanks for your patients and explanation dude. :D – D.Blazer Feb 23 '16 at 15:32