1

I've been working on populating a ListView with data I've retrieved from my sqlite database, the code from my database file DBMainAdapter works perfectly (snippet to save space) I know this because when I call my getAll() inside a separate activity I'm using (not included) i get my ArrayList and I can use it perfectly fine to print out the contents inside however I've noticed that when ever I try to do the same thing inside my ProfileListActivity I keep getting a NullPointerException thrown. What am I doing wrong?!

Error Log:

04-21 06:42:31.669: W/dalvikvm(6107): threadid=1: thread exiting with uncaught exception (group=0xb3a8db90)
04-21 06:42:31.749: E/AndroidRuntime(6107): FATAL EXCEPTION: main
04-21 06:42:31.749: E/AndroidRuntime(6107): Process: com.test.profilekeeper, PID: 6107
04-21 06:42:31.749: E/AndroidRuntime(6107): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.test.profilekeeper/com.test.profilekeeper.ProfileListActivity}: java.lang.NullPointerException
04-21 06:42:31.749: E/AndroidRuntime(6107):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2176)
04-21 06:42:31.749: E/AndroidRuntime(6107):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2226)
04-21 06:42:31.749: E/AndroidRuntime(6107):     at android.app.ActivityThread.access$700(ActivityThread.java:135)
04-21 06:42:31.749: E/AndroidRuntime(6107):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1397)
04-21 06:42:31.749: E/AndroidRuntime(6107):     at android.os.Handler.dispatchMessage(Handler.java:102)
04-21 06:42:31.749: E/AndroidRuntime(6107):     at android.os.Looper.loop(Looper.java:137)
04-21 06:42:31.749: E/AndroidRuntime(6107):     at android.app.ActivityThread.main(ActivityThread.java:4998)
04-21 06:42:31.749: E/AndroidRuntime(6107):     at java.lang.reflect.Method.invokeNative(Native Method)
04-21 06:42:31.749: E/AndroidRuntime(6107):     at java.lang.reflect.Method.invoke(Method.java:515)
04-21 06:42:31.749: E/AndroidRuntime(6107):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
04-21 06:42:31.749: E/AndroidRuntime(6107):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
04-21 06:42:31.749: E/AndroidRuntime(6107):     at dalvik.system.NativeStart.main(Native Method)
04-21 06:42:31.749: E/AndroidRuntime(6107): Caused by: java.lang.NullPointerException
04-21 06:42:31.749: E/AndroidRuntime(6107):     at com.test.profilekeeper.LoadedData.<init>(LoadedData.java:17)
04-21 06:42:31.749: E/AndroidRuntime(6107):     at com.test.profilekeeper.ProfileListActivity.onCreate(ProfileListActivity.java:23)
04-21 06:42:31.749: E/AndroidRuntime(6107):     at android.app.Activity.performCreate(Activity.java:5243)
04-21 06:42:31.749: E/AndroidRuntime(6107):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-21 06:42:31.749: E/AndroidRuntime(6107):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2140)
04-21 06:42:31.749: E/AndroidRuntime(6107):     ... 11 more

Where at com.test.profilekeeper.LoadedData.(LoadedData.java:17) : ArrayList listdata = dbhelper.getAll(); //constructor

Where at com.test.profilekeeper.ProfileListActivity.onCreate(ProfileListActivity.java:23) : LoadedData mydata = new LoadedData();

public class DBMainAdapter{
    DBMain dbhelper;

    public DBMainAdapter(Context context){
        dbhelper = new DBMain(context);
    }

    public long insertprofiledata(String fname, String lname, String age, String gender, String username, String password){
        SQLiteDatabase db = dbhelper.getWritableDatabase();
        ContentValues cv = new ContentValues();

        cv.put(DBMain.FIRSTNAME, fname);
        cv.put(DBMain.LASTNAME, lname);
        cv.put(DBMain.AGE, age);
        cv.put(DBMain.GENDER, gender);
        cv.put(DBMain.USERNAME, username);
        cv.put(DBMain.PASSWORD, password);

        long id = db.insert(DBMain.TABLE_NAME, null, cv);
        return id;
    }

    public ArrayList<String[]> getAll(){
        SQLiteDatabase db = dbhelper.getWritableDatabase();
        String[] columns = {DBMain.UID, DBMain.FIRSTNAME, DBMain.LASTNAME, DBMain.AGE, DBMain.GENDER};
        Cursor curs = db.query(DBMain.TABLE_NAME, columns, null, null, null, null, null);

        int index1 = curs.getColumnIndex(DBMain.UID);
        int index2 = curs.getColumnIndex(DBMain.FIRSTNAME);
        int index3 = curs.getColumnIndex(DBMain.LASTNAME);
        int index4 = curs.getColumnIndex(DBMain.AGE);
        int index5 = curs.getColumnIndex(DBMain.GENDER);

        StringBuffer buffer = new StringBuffer();

        while(curs.moveToNext()){
            String uid = curs.getString(index1);
            String fname = curs.getString(index2);
            String lname = curs.getString(index3);
            String age = curs.getString(index4);
            String gender = curs.getString(index5);

            buffer.append(uid+","+fname+","+lname+","+age+","+gender+" ");
        }

        String[] row = buffer.toString().split(" ");
        String profilebuilder[][] = new String[row.length][row[0].length()];

        for(int i = 0; i < row.length; i++){
            String[] profile = row[i].split(",");
            for(int j = 0; j < profile.length; j++){
                profilebuilder[i][j] = profile[j];
            }
        }

        String[] ids = new String[profilebuilder.length];
        String[] firstname = new String[profilebuilder.length];
        String[] ages = new String[profilebuilder.length];
        String[] genders = new String[profilebuilder.length];

        for(int k = 0; k < profilebuilder.length; k++){
            for(int l = 0; l < profilebuilder[0].length; l++){
                ids[k] = profilebuilder[k][0];
                firstname[k] = profilebuilder[k][1];
                ages[k] = profilebuilder[k][3];
                genders[k] = profilebuilder[k][4];
            }
        }

        ArrayList<String[]> alldata = new ArrayList<String[]>();
        alldata.add(ids);
        alldata.add(firstname);
        alldata.add(ages);
        alldata.add(genders);       

        return alldata;
    }
}

    public class LoadedData {
        DBMainAdapter dbhelper;

        String[] ids;
        String[] firstnames;
        String[] ages;
        String[] genders;

        public LoadedData(){
            ArrayList<String[]> listdata = dbhelper.getAll();

            ids =  new String[listdata.get(0).length];
            firstnames = new String[listdata.get(0).length];
            ages = new String[listdata.get(0).length];
            genders  = new String[listdata.get(0).length];

            ids = listdata.get(0);
            firstnames = listdata.get(1);
            ages = listdata.get(2);
            genders = listdata.get(3);
        }

        public String[] getIds() {
            return ids;
        }

        public String[] getFirstnames() {
            return firstnames;
        }

        public String[] getAges() {
            return ages;
        }

        public String[] getGenders() {
            return genders;
        }
    }


public class ProfileListActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        LoadedData mydata = new LoadedData();
        populateListView(mydata);   
    }

    private void populateListView(LoadedData mydata) {
        ArrayAdapter<LoadedData> adapter = new MyListAdapter(mydata);
        ListView list = (ListView) findViewById(R.id.listView);
        list.setAdapter(adapter);
    }

    private class MyListAdapter extends ArrayAdapter<LoadedData>{
        LoadedData mdata;
        public MyListAdapter(LoadedData data){
            super(ProfileListActivity.this, R.layout.row);
            this.mdata = data;
        }

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

            TextView first_name = (TextView) itemView.findViewById(R.id.nameListTextView);
            TextView id = (TextView) itemView.findViewById(R.id.idListTextView);
            TextView age = (TextView) itemView.findViewById(R.id.ageListTextView);
            ImageView img = (ImageView) itemView.findViewById(R.id.imageViewList);

            id.setText(mdata.getIds()[position]);
            first_name.setText(mdata.getFirstnames()[position]);
            age.setText(mdata.getAges()[position]);

            if(mdata.getGenders()[position].equalsIgnoreCase("Male")){
                img.setImageResource(R.raw.man_thumb);
            }else{
                img.setImageResource(R.raw.woman_thumb);
            }   

            return itemView;
        }
    }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
CLO
  • 21
  • 3
  • Init DBHelper matey :) – Skynet Apr 21 '14 at 12:39
  • @Nun'eChai Cheers mate! ^^ – CLO Apr 21 '14 at 13:10
  • @CLO - Can you really write a `Private` class inside a `Public` class? If yes, then how will you instantiate the `Private` class? And is there any specific reason to write a `Private` class inside a `Public` one? – Knowledge Craving Apr 21 '14 at 13:20
  • @CLO - And I'm also not sure about the curly braces, wrapping the classes, because as I can see now, there are a couple of nesting classes that can mess up big time. So my request is that you check your formatted code again, and rectify it if anything is missing. Thanks! – Knowledge Craving Apr 21 '14 at 13:22
  • @KnowledgeCraving I'm pretty sure it's permissible, I was trying to get my ProfileListActivity to be a self contained class together with my ArrayAdapter so I nested it inside and thought I'd encapsulate it for good practices..I'm still learning :) – CLO Apr 21 '14 at 13:48
  • @CLO - Okay, but still I will suggest to refrain putting a `Private` class in a `Public` class (considering the Best Practices), as I don't see any way of instantiating the inner class. – Knowledge Craving Apr 21 '14 at 14:32
  • 1
    I see what you're saying but in actual fact you can, the private inner class is my array adapter and I instantiated it inside the oncreate method of my outer class ProfileListActivity and it's working perfectly. But your point is duly noted, I prefer to stay conventional myself to avoid any creepy bugs that are too hard to track especially when working on much bigger projects. Thanks for you input man, I appreciate it. I think I just became an active member of stackoverflow..this service is greatness! – CLO Apr 21 '14 at 16:10

1 Answers1

5

You forgot to initialize dbhelper object in the LoadedData class. Make a public constructor in the class like below,

public DBMainAdapter(Context context)
{
    dbhelper = new DBMain(context);
} 

Also in getAll() method of DBMainAdapter class write following statement before the while loop,

curs.moveToFirst();
Lucifer
  • 29,392
  • 25
  • 90
  • 143
  • Duuuuuude!! Thank you so much man I completely for about that I was focusing on my the arraylist itself this whole time haha! I'm still learning :) I still have a problem though unfortunately with my list view :( I took a snapshot for you, i(.)imgur(.)com/k5sbzNi(.)png – CLO Apr 21 '14 at 13:10
  • @CLO, sorry I am not able to access the link of snapshot. – Lucifer Apr 21 '14 at 13:11
  • alright one minute I'll try a different service, thanks a lot dude you're very helpful and kind :D – CLO Apr 21 '14 at 13:14
  • @CLO, you welcome. Since you are new to this site let me guide you, how you should accept the answer. Just tick the tick mark beside the answer which is best solution for your problem. :) – Lucifer Apr 21 '14 at 13:15
  • http://postimg.org/image/6mq60eqht/full/ – CLO Apr 21 '14 at 13:15
  • @CLO , are you still getting NullPointerException ? – Lucifer Apr 21 '14 at 13:18
  • Yup! But this time it's an issue with setting an adapter for my listview widget for some very odd reason, as a matter of fact everything about my project has been very odd lol – CLO Apr 21 '14 at 13:20
  • @CLO, Is it possible for you to send me a copy of your project via email ? – Lucifer Apr 21 '14 at 13:25
  • I just sent you a copy of my project files. Thanks a lot! – CLO Apr 21 '14 at 13:46
  • I fixed it! It was a simple error, I forgot to change the parameters to for my arrayadapter. Thank you once again for all your help! – CLO Apr 21 '14 at 15:56
  • oh ok, I was still looking into your code. btw nice app, simple one :) – Lucifer Apr 21 '14 at 16:19