Null Pointer Exception-getting data from sqlite to a list

-1

I am tring to make a list of scores, that gets it's data from a database.

the error it gives me is:NullPointerException

here is what i have done:

The activity:

public class ScoresActivity extends Activity {
    ScoreDataSource sds;
    ArrayList<Score>scores;
    ScoreAdapter adapter;
    ListView listview;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listview=(ListView) findViewById(R.id.AllScores);

        sds=new ScoreDataSource(this);

        sds.open();
        scores=sds.getAllCustomers();
        if(scores.size()==0)
        {
             createCustomers();
             scores=sds.getAllCustomers();
        }
        adapter=new ScoreAdapter(this,R.layout.row,scores);
        listview.setAdapter(adapter);
    //  Customer c=cds.getCustomerById(1);
        //Log.i("getid","customer name is " + c.getFirstName());



    }




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


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        switch (item.getItemId()) {
        case R.id.menu_classic:
            scores=sds.getAllCustomersByFIlter("Game==Classic", "waste ASC");
            Log.i("filter", "list count is " + scores.size());
            refreshMyAdapter();
            break;
        case R.id.menu_vscomp :
            scores=sds.getAllCustomersByFIlter("Game==VScomp", "waste ASC");
            Log.i("filter", "list count is " + scores.size());
            refreshMyAdapter();
            break;

        case R.id.menu_allcustomers: 
            scores=sds.getAllCustomers();
            Log.i("filter", "list count is " + scores.size());
            refreshMyAdapter();
            break;
        default:
            break;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        sds.open();
    }
    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        sds.close();
    }
    public void createCustomers()
    {
        Score s1=new Score(0,"a","1",50,"Classic");
        s1=sds.createCustomer(s1);

        Score s2=new Score(0,"b","2",600,"Classic");
        s2=sds.createCustomer(s2);

        Score s3=new Score(0,"c","2",600,"VScomp");
        s3=sds.createCustomer(s3);


    }
    public void refreshMyAdapter()
    {

        adapter=new ScoreAdapter(this,R.layout.row,scores);
        listview.setAdapter(adapter);

    }

}

ScoreDataSource:

    public class ScoreDataSource {

    Context context;
    ScoreOpenHelper helper;
    SQLiteDatabase database;

    String []allColumns={ScoreOpenHelper.COLUMN_ID, ScoreOpenHelper.COLUMN_NAME,
            ScoreOpenHelper.COLUMN_DATE,ScoreOpenHelper.COLUMN_SCORE,ScoreOpenHelper.COLUMN_GAME};

    public ScoreDataSource(Context context)
    {
        this.context=context;
        helper=new ScoreOpenHelper(context);
    }
    public void open()
    {
        database=helper.getWritableDatabase();
        Log.i("data", "Database connection open");
    }
    public void close()
    {
        helper.close();
        Log.i("data", "Database connection close");

    }
    //quearies ...... 
    public Score createCustomer(Score s)
    {
        ContentValues values=new ContentValues();
        values.put(ScoreOpenHelper.COLUMN_NAME, s.getName());
        values.put(ScoreOpenHelper.COLUMN_DATE, s.getScore());
        values.put(ScoreOpenHelper.COLUMN_SCORE, s.getScore());
        values.put(ScoreOpenHelper.COLUMN_GAME, s.getGame());

        long insertId=database.insert(ScoreOpenHelper.TABLE_SCORES, null, values);
        Log.i("data", "Score " + insertId + "insert to database");
        s.setID(insertId);
        return s;


    }
    public ArrayList<Score>getAllCustomers()
    {
        Cursor cursor=database.query(ScoreOpenHelper.TABLE_SCORES, allColumns, null, null, null, null, null);
        ArrayList<Score>l=convertCurserToList(cursor);
        return  l;      
    }
    public ArrayList<Score>getAllCustomersByFIlter(String selection,String OrderBy)
    {
        Cursor cursor=database.query(ScoreOpenHelper.TABLE_SCORES, allColumns, selection, null, null, null, OrderBy);
        ArrayList<Score>l=convertCurserToList(cursor);
        return  l;      
    }


    private ArrayList<Score> convertCurserToList(Cursor cursor) {
        ArrayList<Score>l=new ArrayList<Score>();

        if(cursor.getCount()>0)
        {
            while(cursor.moveToNext())
            {
                long id=cursor.getLong(cursor.getColumnIndex(ScoreOpenHelper.COLUMN_ID));
                String name=cursor.getString(cursor.getColumnIndex(ScoreOpenHelper.COLUMN_NAME));
                String date=cursor.getString(cursor.getColumnIndex(ScoreOpenHelper.COLUMN_DATE));
                int  score=cursor.getInt(cursor.getColumnIndex(ScoreOpenHelper.COLUMN_SCORE));
                String game=cursor.getString(cursor.getColumnIndex(ScoreOpenHelper.COLUMN_GAME));
                Score c=new Score(id,name,date,score,game);
                l.add(c);

            }                   

        }
        return l;
    }
    public Score getCustomerById(long rowId)
    {
        Cursor cursor=database.query(ScoreOpenHelper.TABLE_SCORES, allColumns, ScoreOpenHelper.COLUMN_ID +  "=" + rowId,
                null, null, null, null);
        cursor.moveToFirst();

        if(cursor.getCount()>0)
        {
            long id=cursor.getLong(cursor.getColumnIndex(ScoreOpenHelper.COLUMN_ID));
            String name=cursor.getString(cursor.getColumnIndex(ScoreOpenHelper.COLUMN_NAME));
            String date=cursor.getString(cursor.getColumnIndex(ScoreOpenHelper.COLUMN_DATE));
            int  score=cursor.getInt(cursor.getColumnIndex(ScoreOpenHelper.COLUMN_SCORE));
            String game=cursor.getString(cursor.getColumnIndex(ScoreOpenHelper.COLUMN_GAME));
            Score c=new Score(id,name,date,score,game);
            return c;
        }
        return null;

    }
    public long deleteAll()
    {
        return  database.delete(ScoreOpenHelper.TABLE_SCORES, null, null);      
    }
    public long deleteCustomerByRow(long rowId)
    {
        return  database.delete(ScoreOpenHelper.TABLE_SCORES, ScoreOpenHelper.COLUMN_ID +"=" + rowId, null);        

    }
    public long updateByRow(Score c)
    {
        ContentValues values=new ContentValues();

        values.put(ScoreOpenHelper.COLUMN_ID, c.getID());
        values.put(ScoreOpenHelper.COLUMN_NAME, c.getName());
        values.put(ScoreOpenHelper.COLUMN_DATE, c.getDate());
        values.put(ScoreOpenHelper.COLUMN_SCORE, c.getScore());
        values.put(ScoreOpenHelper.COLUMN_GAME, c.getGame());

        return database.update(ScoreOpenHelper.TABLE_SCORES, values,ScoreOpenHelper.COLUMN_ID +"=" + c.getID(), null);

    }

}

SourceOpenHelp:

    public class ScoreOpenHelper extends SQLiteOpenHelper {


    public static final String DATABASENAME="scoredb.db";
    public static final String TABLE_SCORES="scores";   
    public static final int DATABASEVERSION=2;

    public static final String COLUMN_ID="ID";
    public static final String COLUMN_NAME="Name";
    public static final String COLUMN_DATE="Date";
    public static final String COLUMN_SCORE="Score";
    public static final String COLUMN_GAME="Game";

    private static final String CREATE_TABLE_CUSTOMER="CREATE TABLE IF NOT EXISTS " + 
            TABLE_SCORES + "(" + COLUMN_ID +  " INTEGER PRIMARY KEY AUTOINCREMENT," + COLUMN_NAME + " VARCHAR," 
            + COLUMN_DATE + " VARCHAR,"+ COLUMN_SCORE + " INTEGER,"+ COLUMN_GAME +" VARCHAR"  +   ");";

    SQLiteDatabase database;

    public ScoreOpenHelper(Context context) {
        super(context, DATABASENAME, null, DATABASEVERSION);
        // TODO Auto-generated constructor stub
    }


    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE_CUSTOMER);
        Log.i("data", "Table customer created");
    }



    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_SCORES);
        onCreate(db);

    }
}

ScoreAdapter:

    public class ScoreAdapter extends ArrayAdapter<Score> {

    Context context;
    int layoutResourceId;
    ArrayList<Score>data;

    public ScoreAdapter(Context context, int textViewResourceId,
            List<Score> objects) {
        super(context, textViewResourceId, objects);
        this.context=context;
        this.layoutResourceId=textViewResourceId;
        this.data=(ArrayList<Score>) objects;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        View row;
        LayoutInflater inflater= ((Activity) context).getLayoutInflater();
        row=inflater.inflate(layoutResourceId, parent,false);
        Score s=data.get(position);
        TextView name=(TextView) row.findViewById(R.id.name);
        TextView date=(TextView) row.findViewById(R.id.date);
        TextView score=(TextView) row.findViewById(R.id.score);
        //Button btn=(Button) row.findViewById(R.id.btnDelete);


        name.setText(s.getName());
        date.setText(s.getDate());
        score.setText(s.getScore());

        return row;



    }
}

i have tried doing it couple of times, asked a friend. nothing helped. if you need me to add the menu or the xml's of row or where the listview tell me.

Thank for the help

EDIT:

The new Stack Trace:

03-13 12:56:09.109: I/data(949): Database connection open
03-13 12:56:09.160: I/data(949): Database connection open
03-13 12:56:09.339: W/ResourceType(949): No package identifier when getting value for resource number 0x00000032
03-13 12:56:09.349: D/AndroidRuntime(949): Shutting down VM
03-13 12:56:09.349: W/dalvikvm(949): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
03-13 12:56:09.499: E/AndroidRuntime(949): FATAL EXCEPTION: main
03-13 12:56:09.499: E/AndroidRuntime(949): android.content.res.Resources$NotFoundException: String resource ID #0x32
03-13 12:56:09.499: E/AndroidRuntime(949):  at android.content.res.Resources.getText(Resources.java:230)
03-13 12:56:09.499: E/AndroidRuntime(949):  at android.widget.TextView.setText(TextView.java:3769)
03-13 12:56:09.499: E/AndroidRuntime(949):  at com.example.snake.ScoreAdapter.getView(ScoreAdapter.java:43)
03-13 12:56:09.499: E/AndroidRuntime(949):  at android.widget.AbsListView.obtainView(AbsListView.java:2159)
03-13 12:56:09.499: E/AndroidRuntime(949):  at android.widget.ListView.measureHeightOfChildren(ListView.java:1246)
03-13 12:56:09.499: E/AndroidRuntime(949):  at android.widget.ListView.onMeasure(ListView.java:1158)
03-13 12:56:09.499: E/AndroidRuntime(949):  at android.view.View.measure(View.java:15518)
03-13 12:56:09.499: E/AndroidRuntime(949):  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4825)
03-13 12:56:09.499: E/AndroidRuntime(949):  at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
03-13 12:56:09.499: E/AndroidRuntime(949):  at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
03-13 12:56:09.499: E/AndroidRuntime(949):  at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
03-13 12:56:09.499: E/AndroidRuntime(949):  at android.view.View.measure(View.java:15518)
03-13 12:56:09.499: E/AndroidRuntime(949):  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4825)
03-13 12:56:09.499: E/AndroidRuntime(949):  at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
03-13 12:56:09.499: E/AndroidRuntime(949):  at android.view.View.measure(View.java:15518)
03-13 12:56:09.499: E/AndroidRuntime(949):  at android.widget.LinearLayout.measureVertical(LinearLayout.java:847)
03-13 12:56:09.499: E/AndroidRuntime(949):  at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
03-13 12:56:09.499: E/AndroidRuntime(949):  at android.view.View.measure(View.java:15518)
03-13 12:56:09.499: E/AndroidRuntime(949):  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4825)
03-13 12:56:09.499: E/AndroidRuntime(949):  at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
03-13 12:56:09.499: E/AndroidRuntime(949):  at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2176)
03-13 12:56:09.499: E/AndroidRuntime(949):  at android.view.View.measure(View.java:15518)
03-13 12:56:09.499: E/AndroidRuntime(949):  at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1874)
03-13 12:56:09.499: E/AndroidRuntime(949):  at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1089)
03-13 12:56:09.499: E/AndroidRuntime(949):  at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1265)
03-13 12:56:09.499: E/AndroidRuntime(949):  at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:989)
03-13 12:56:09.499: E/AndroidRuntime(949):  at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4351)
03-13 12:56:09.499: E/AndroidRuntime(949):  at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
03-13 12:56:09.499: E/AndroidRuntime(949):  at android.view.Choreographer.doCallbacks(Choreographer.java:562)
03-13 12:56:09.499: E/AndroidRuntime(949):  at android.view.Choreographer.doFrame(Choreographer.java:532)
03-13 12:56:09.499: E/AndroidRuntime(949):  at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
03-13 12:56:09.499: E/AndroidRuntime(949):  at android.os.Handler.handleCallback(Handler.java:725)
03-13 12:56:09.499: E/AndroidRuntime(949):  at android.os.Handler.dispatchMessage(Handler.java:92)
03-13 12:56:09.499: E/AndroidRuntime(949):  at android.os.Looper.loop(Looper.java:137)
03-13 12:56:09.499: E/AndroidRuntime(949):  at android.app.ActivityThread.main(ActivityThread.java:5041)
03-13 12:56:09.499: E/AndroidRuntime(949):  at java.lang.reflect.Method.invokeNative(Native Method)
03-13 12:56:09.499: E/AndroidRuntime(949):  at java.lang.reflect.Method.invoke(Method.java:511)
03-13 12:56:09.499: E/AndroidRuntime(949):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
03-13 12:56:09.499: E/AndroidRuntime(949):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
03-13 12:56:09.499: E/AndroidRuntime(949):  at dalvik.system.NativeStart.main(Native Method)
android
sqlite
android-listview
asked on Stack Overflow Mar 12, 2014 by Omer • edited Mar 13, 2014 by Omer

1 Answer

1

Since the NPE is in listview.setAdapter(adapter), listview is null. It is null because findViewById(R.id.AllScores) returns null. It returns null because the layout activity_main does not contain a view with such id, or the resource ids and binary XML files are out of sync. In the first case, add the listview to the layout. In the latter case, clean and rebuild the project.

For the follow-up exception stacktrace:

03-13 12:56:09.499: E/AndroidRuntime(949): android.content.res.Resources$NotFoundException: String resource ID #0x32
03-13 12:56:09.499: E/AndroidRuntime(949):  at android.content.res.Resources.getText(Resources.java:230)
03-13 12:56:09.499: E/AndroidRuntime(949):  at android.widget.TextView.setText(TextView.java:3769)
03-13 12:56:09.499: E/AndroidRuntime(949):  at com.example.snake.ScoreAdapter.getView(ScoreAdapter.java:43)

... in your adapter getView(), use setText(String.valueOf(intValue)) instead of setText(intValue) so the int is not treated as a resource id. (It's probably the score what is int there.)

answered on Stack Overflow Mar 12, 2014 by laalto • edited Mar 13, 2014 by laalto

User contributions licensed under CC BY-SA 3.0