dimanche 7 juin 2015

java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.List on a null object reference

I am creating an android app. I have been struggling on this error trying to fix it with various solutions from every where on google.

Point of the App: Time Attendance. User Data is stored in a database. From the database all users must be displayed a Recycler view. I used an adapter and a databean class to try and get this to work. Any help is appreciated.

All the code I have is as follows:

UsersHelper.class (Database creation)

 package za.co.kashvirsingh.timecard.database;

    import android.content.Context;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;
    import android.util.Log;
    import android.widget.Toast;

    /**
     * Created by Kashvir on 6/3/15.
     */
    public class UsersHelper extends SQLiteOpenHelper
    {
        //DB variables
        private static final String DATABASE_NAME = "Time_attendance.db";
        public static final String TABLE_NAME = "Time_attendance_users";
        private static final int DATABASE_VERSION = 1;

        //DB column variables
        public static final String user_id = "_id";
        private static final String user_hash = "user_hash";
        public static final String user_name = "user_name";
        public static final String user_password = "user_password";
        public static final String user_time_allocation = "user_time_allocation";

        //DB Create Table
        private static final String CREATE_TABLE = "CREATE TABLE "+ TABLE_NAME + " (" + user_id +" INTEGER PRIMARY KEY AUTOINCREMENT , "
                + user_hash + " VARCHAR(255), "
                + user_name + " VARCHAR(255), "
                + user_password + " INTEGER, "
                + user_time_allocation + " VARCHAR(255));";

        //DB Drop Table if Table exists
        private static final String DROP_TABLE = "DROP TABLE IF EXISTS " + TABLE_NAME;

        private Context context;

        public UsersHelper(Context context) {
            super(context,DATABASE_NAME,null,DATABASE_VERSION);
            this.context = context;
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            Log.d("UsersHelper: ", "OnCreate");
            try
            {
                db.execSQL(CREATE_TABLE);
            }
            catch (android.database.SQLException e)
            {
                Toast.makeText(context,"SQLException: "+e,Toast.LENGTH_LONG).show();
            }

        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.d("UserHelper: ", "onUpgrade");
            try
            {
                db.execSQL(DROP_TABLE);
                onCreate(db);
                Log.d("UserHelper: ", "Table Dropped");
            }
            catch (android.database.SQLException e)
            {
                Toast.makeText(context, "SQLException: "+e, Toast.LENGTH_LONG).show();
            }


        }
    }

TimeAttendanceAdapter.class (Database action Methods)

 package za.co.kashvirsingh.timecard.adapters;

            import android.content.ContentValues;
            import android.content.Context;
            import android.database.Cursor;
            import android.database.sqlite.SQLiteDatabase;
            import android.util.Log;
            import android.widget.Toast;

            import java.util.ArrayList;
            import java.util.List;

            import za.co.kashvirsingh.timecard.database.UsersHelper;

            /**
             * Created by kashvir on 6/3/15.
             *
             * Adapter for the db methods
             * View
             * Delete
             * Add
             */
            public class TimeAttendanceAdapter
            {
                //user database
                UsersHelper users;
                Context context;

                //Initializing
                public TimeAttendanceAdapter(Context context)
                {
                    users = new UsersHelper(context);
                    this.context = context;
                }

                //Adding users to the dataBase
                public long addUser(String userName, String userPassword, String userTime)
                {
                    SQLiteDatabase db = users.getWritableDatabase();

                    ContentValues contentValues = new ContentValues();
                    contentValues.put(users.user_name, userName);
                    contentValues.put(users.user_password, userPassword);
                    contentValues.put(users.user_time_allocation, userTime);
                    //Add Hash

                    //If id is negative new user was not added
                    long id = db.insert(users.TABLE_NAME, null, contentValues);
                    return id;
                }

                //View all user Data
                public List<DataBean> getAllUsers()
                {
                    List<DataBean> list=new ArrayList<>();
                    SQLiteDatabase db = users.getWritableDatabase();
                    String[] columns = {users.user_id,
                            users.user_name,
                            users.user_time_allocation,};
                    Cursor cursor = db.query(users.TABLE_NAME, columns, null, null, null, null, null);


            //        String query = "SELECT * FROM " + users.TABLE_NAME;
            //
            //        Cursor cursor = db.rawQuery(query, null);
                    if(cursor != null)
                    {
                        while (cursor.moveToNext()) {
                            int index = cursor.getColumnIndex(users.user_id);
                            int index2 = cursor.getColumnIndex(users.user_name);
                            int index3 = cursor.getColumnIndex(users.user_password);
                            int index4 = cursor.getColumnIndex(users.user_time_allocation);
                            int cid = cursor.getInt(index);
                            String name = cursor.getString(index2);
                            String password = cursor.getString(index3);
                            String time = cursor.getString(index4);
                            DataBean bean = new DataBean(name, password, time);
                            list.add((bean));
                        }
                        if (list != null)
                            return list;
                        else {
                            System.out.println("list is null");
                            Log.d("getAllUsers: ", "list is null");
                            return null;
                        }
                    }

                    Log.d("getAllUsers: ", cursor.toString());
                    Toast.makeText(context, cursor.toString(), Toast.LENGTH_LONG).show();
                    return null;

                }
                public DataBean getBean(String name)
                {
                    SQLiteDatabase db = users.getReadableDatabase();
                    String[] columns = {users.user_id,
                            users.user_name,
                            users.user_time_allocation,};
                    Cursor cursor = db.query(users.TABLE_NAME, columns, null, null, null, null, null);
                    DataBean bean = null;
                    if (cursor.moveToFirst()) {
                        int index = cursor.getColumnIndex(users.user_id);
                        int index2 = cursor.getColumnIndex(users.user_name);
                        int index3 = cursor.getColumnIndex(users.user_time_allocation);
                        int index4 = cursor.getColumnIndex(users.user_password);
                        int id = cursor.getInt(index);
                        String personName = cursor.getString(index2);
                        String time = cursor.getString(index3);
                        String password = cursor.getString(index4);
                        bean = new DataBean(id, name, time, password);
                    }
                    return bean;
                }


            }

OnCreate Method that calls the RecyclerView

protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_user_admin);



                RecyclerView userRecList = (RecyclerView) findViewById(R.id.userRecList);
                userRecList.setHasFixedSize(true);
                userRecList.setLayoutManager(new LinearLayoutManager(this));
                userRecList.setItemAnimator(new DefaultItemAnimator());

                users.getAllUsers();

                userRecList.setAdapter(new MyAdapter(users.getAllUsers(), R.layout.list_item));

                FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
                fab.attachToRecyclerView(userRecList);
                fab.setOnClickListener(new View.OnClickListener(){
                    public void onClick(View v)
                    {
                        goToAdd();
                    }
                });


            }

List_item.xml

<?xml version="1.0" encoding="utf-8"?>
                <LinearLayout xmlns:android="http://ift.tt/nIICcg"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical">

                    <TextView
                        android:id="@android:id/text1"
                        xmlns:android="http://ift.tt/nIICcg"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:drawablePadding="8dp"
                        android:gravity="center_vertical"
                        android:paddingBottom="8dp"
                        android:paddingLeft="16dp"
                        android:paddingRight="16dp"
                        android:paddingTop="8dp"
                        android:textColor="#212121"
                        android:textSize="18sp"/>

                    <TextView
                        android:id="@+id/userName"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:drawablePadding="8dp"
                        android:gravity="center_vertical"
                        android:paddingBottom="8dp"
                        android:paddingLeft="16dp"
                        android:paddingRight="16dp"
                        android:paddingTop="8dp"
                        android:textColor="#212121"
                        android:textSize="18sp"/>

                    <TextView
                        android:id="@+id/userTime"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:drawablePadding="8dp"
                        android:gravity="center_vertical"
                        android:paddingBottom="8dp"
                        android:paddingLeft="16dp"
                        android:paddingRight="16dp"
                        android:paddingTop="8dp"
                        android:textColor="#212121"
                        android:textSize="18sp"/>

                    <TextView
                        android:id="@+id/userNickName"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:drawablePadding="8dp"
                        android:gravity="center_vertical"
                        android:paddingBottom="8dp"
                        android:paddingLeft="16dp"
                        android:paddingRight="16dp"
                        android:paddingTop="8dp"
                        android:textColor="#212121"
                        android:textSize="18sp"/>

                </LinearLayout>

DataBean.class

    package za.co.kashvirsingh.timecard.adapters;

                /**
                 * Created by Kashvir on 6/4/15.
                 */
                public class DataBean {
                        //private variables
                        protected int _id;
                        protected String _name;
                        protected String _password;
                        protected String _time;

                        // Empty constructor
                        public DataBean(){

                        }
                        // constructor
                        public DataBean(int id, String name, String password, String time){
                            this._id = id;
                            this._name = name;
                            this._password = password;
                            this._time = time;

                            setName(name);
                            setTime(time);
                            setID(id);
                            setPassword(password);
                        }

                        // constructor
                        public DataBean(String name, String password, String time){
                            this._name = name;
                            this._password = password;
                            this._time = time;

                            setName(name);
                            setTime(time);

                            setPassword(password);
                        }


                        // getting ID
                        public int getID(){
                            return this._id;
                        }

                        // setting id
                        public void setID(int id){
                            this._id = id;
                        }

                        // getting name
                        public String getName(){
                            return this._name;
                        }

                        // setting name
                        public void setName(String name){
                            this._name = name;
                        }

                        // getting CardValue
                        public String getTime(){
                            return this._time;
                        }

                        // setting CardValue
                        public void setTime(String time){
                            this._time = time;
                        }
                        // getting CardCode
                        public String getPassword(){
                            return this._password;
                        }

                        // setting CardCode
                        public void setPassword(String password){
                            this._password = password;
                        }

                }


**MyAdapter.class**

    package za.co.kashvirsingh.timecard.adapters;

                import android.support.v7.widget.RecyclerView;
                import android.view.LayoutInflater;
                import android.view.View;
                import android.view.ViewGroup;
                import android.widget.TextView;

                import java.util.List;

                import za.co.kashvirsingh.timecard.R;


                /**
                 * Created by kashvir on 6/3/15.
                 */
                public class MyAdapter extends RecyclerView.Adapter<MyAdapter.userViewHolder>{
                    private List<DataBean> items;
                    private int itemLayout;


                    public MyAdapter(List<DataBean> items, int itemLayout){
                        this.items = items;
                        this.itemLayout = itemLayout;
                    }


                    @Override
                    public userViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                        View v = LayoutInflater.from(parent.getContext()).inflate(itemLayout, parent, false);
                        return new userViewHolder(v);
                    }

                    @Override
                    //Stuff to be displayed
                    public void onBindViewHolder(userViewHolder holder, int position) {
                        DataBean item = items.get(position);
                        if (holder != null) {
                            holder.userName.setText(item.getName());
                            holder.userTime.setText(item.getTime());
                        }
                    }


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


                    /**
                     * Created by KAshvir on 6/4/15.
                     */
                    public static class userViewHolder extends RecyclerView.ViewHolder {
                        TextView userName;
                        TextView userTime;
                        TextView userNickName;

                        public userViewHolder(View v) {
                            super(v);
                            userName =  (TextView) v.findViewById(R.id.userName);
                            userTime = (TextView)  v.findViewById(R.id.userTime);
                            userNickName = (TextView) v.findViewById(R.id.userNickName);
                        }
                    }
                }

ERROR:

06-07 16:42:00.495    2070-2070/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
                                    Process: za.co.kashvirsingh.timecard, PID: 2070
                                    java.lang.RuntimeException: Unable to start activity ComponentInfo{za.co.kashvirsingh.timecard/za.co.kashvirsingh.timecard.activities.UserAdmin}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.List za.co.kashvirsingh.timecard.adapters.TimeAttendanceAdapter.getAllUsers()' on a null object reference
                                    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
                                    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
                                    at android.app.ActivityThread.access$800(ActivityThread.java:144)
                                    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
                                    at android.os.Handler.dispatchMessage(Handler.java:102)
                                    at android.os.Looper.loop(Looper.java:135)
                                    at android.app.ActivityThread.main(ActivityThread.java:5221)
                                    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:899)
                                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
                                    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.List za.co.kashvirsingh.timecard.adapters.TimeAttendanceAdapter.getAllUsers()' on a null object reference
                                    at za.co.kashvirsingh.timecard.activities.UserAdmin.onCreate(UserAdmin.java:45)
                                    at android.app.Activity.performCreate(Activity.java:5937)
                                    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
                                    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
                                                at android.app.ActivityThread.access$800(ActivityThread.java:144)
                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                at android.os.Looper.loop(Looper.java:135)
                                                at android.app.ActivityThread.main(ActivityThread.java:5221)
                                                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:899)
                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

Thanks in advanced.

Aucun commentaire:

Enregistrer un commentaire