Home Retrieving a Single ROW from Database
Reply: 2

Retrieving a Single ROW from Database

Tanav Sharma
1#
Tanav Sharma Published in 2018-01-12 22:55:31Z

I have a listview, when a user clicks on an item from the listview, it calls a function getRow, which takes the id of the clicked item and retrieves the Name of the clicked item.

However, when I click the item, i am able to retrieve the ID, but it doesn't want to run the query to retrieve the rest of the information.

Here is my code, and logcat:

UserDbHelper.java (class)

public class UserDbHelper extends SQLiteOpenHelper {

    SQLiteDatabase db;
    UserDbHelper userDb;
    private static final String DATABASE_NAME = "USERINFO.db";
    private static final int DATABASE_VERSION = 1;
    private static final String CREATE_QUERY =

            "CREATE TABLE "+ UserContract.NewUserInfo.TABLE_NAME+"("+ UserContract.NewUserInfo.USER_ROWID+" integer primary key autoincrement, "+ UserContract.NewUserInfo.USER_NAME+" TEXT,"+
                    UserContract.NewUserInfo.USER_MOBILE+" TEXT,"+ UserContract.NewUserInfo.USER_EMAIL+" TEXT);";

    public static final String[] ALL_KEYS = new String[] {UserContract.NewUserInfo.USER_ROWID, UserContract.NewUserInfo.USER_NAME, UserContract.NewUserInfo.USER_MOBILE, UserContract.NewUserInfo.USER_EMAIL};

    public UserDbHelper(Context context){
        super(context,DATABASE_NAME,null,DATABASE_VERSION);
        Log.d("DATABASE OPERATIONS", "DATABASE CREATED/ OPENED...");

    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL(CREATE_QUERY);
        Log.d("DATABASE OPERATIONS", "TABLE CREATED...");


    }

    public void addInformations(String name, String mob, String email, SQLiteDatabase sqLiteDatabase){
        ContentValues contentValues = new ContentValues();
        contentValues.put(UserContract.NewUserInfo.USER_NAME,name);
        contentValues.put(UserContract.NewUserInfo.USER_MOBILE,mob);
        contentValues.put(UserContract.NewUserInfo.USER_EMAIL,email);

        sqLiteDatabase.insert(UserContract.NewUserInfo.TABLE_NAME,null,contentValues);
        Log.d("DATABASE OPERATIONS", "ONE ROW INSERTED....");
    }

    public Cursor getInformations(SQLiteDatabase sqLiteDatabase){
        Cursor cursor;

        String[] projections = {UserContract.NewUserInfo.USER_NAME, UserContract.NewUserInfo.USER_MOBILE, UserContract.NewUserInfo.USER_EMAIL};
        cursor = sqLiteDatabase.query(UserContract.NewUserInfo.TABLE_NAME, projections,null,null,null,null,null);

        return cursor;
    }

    // Get a specific row (by rowId)
    public Cursor getRow(long rowId) {
        String where = UserContract.NewUserInfo.USER_ROWID +"="+ rowId;
        Log.e("ID= ",where);

        String select = "SELECT "+ UserContract.NewUserInfo.USER_NAME+" FROM "+ UserContract.NewUserInfo.TABLE_NAME+ " WHERE "+where;
        Log.e("query = ", select);
        db.execSQL(select);

        return null;
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }
}

ListView.java (Activity that handles the click events)

    public class ListActivity extends AppCompatActivity {

        ListView listView;
        SQLiteDatabase sqLiteDatabase;;
        UserDbHelper user;
        Cursor cursor;
        ListDataAdapter listDataAdapter;


        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_list);

            listView = (ListView)  findViewById(R.id.list_view);
            listDataAdapter = new ListDataAdapter(getApplicationContext(),R.layout.row_layout);
            listView.setAdapter(listDataAdapter);

            user = new UserDbHelper(getApplicationContext());
            sqLiteDatabase = user.getReadableDatabase();

            cursor = user.getInformations(sqLiteDatabase);

            if(cursor.moveToFirst()){
                do{
                    String name, mob, email;
                    name = cursor.getString(0);
                    mob = cursor.getString(1);
                    email = cursor.getString(2);

                    DataProvider dataProvider = new DataProvider(name,mob,email);

                    listDataAdapter.add(dataProvider);
                }while(cursor.moveToNext());
            }

            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long ldatabase) {
                    Cursor cursor = user.getRow(i);
                    if(cursor.moveToFirst()){
                        long idDb = cursor.getLong(0);
                        String message = "ID is: " +idDb;
                        Toast.makeText(ListActivity.this, message, Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
}

The OnItemClickListener, gets the id of the clicked item, passes that value to the UserDbHelper class, to the function getRow, where the function takes the id, and runs a query, however when it wants to run the query it, it crashes my app.

I also printed the ID in the logcat to check if i was getting an id, which i was.

Here is the LOGCAT:

01-12 17:40:47.574 13309-13309/bluwyreinc.rohansfitness E/ID=: _id=6
01-12 17:40:47.574 13309-13309/bluwyreinc.rohansfitness E/query =: SELECT user_name FROM user_info WHERE _id=6
01-12 17:40:47.575 13309-13309/bluwyreinc.rohansfitness E/AndroidRuntime: FATAL EXCEPTION: main
                                                                          Process: bluwyreinc.rohansfitness, PID: 13309
                                                                          java.lang.NullPointerException: Attempt to invoke virtual method 'void android.database.sqlite.SQLiteDatabase.execSQL(java.lang.String)' on a null object reference
                                                                              at bluwyreinc.rohansfitness.UserDbHelper.getRow(UserDbHelper.java:68)
                                                                              at bluwyreinc.rohansfitness.ListActivity$1.onItemClick(ListActivity.java:54)
                                                                              at android.widget.AdapterView.performItemClick(AdapterView.java:343)
                                                                              at android.widget.AbsListView.performItemClick(AbsListView.java:1665)
                                                                              at android.widget.AbsListView$PerformClick.run(AbsListView.java:4075)
                                                                              at android.widget.AbsListView$10.run(AbsListView.java:6552)
                                                                              at android.os.Handler.handleCallback(Handler.java:751)
                                                                              at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                              at android.os.Looper.loop(Looper.java:154)
                                                                              at android.app.ActivityThread.main(ActivityThread.java:6823)
                                                                              at java.lang.reflect.Method.invoke(Native Method)
                                                                              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1563)
                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1451)
01-12 17:40:48.090 3104-3160/? E/ActivityTrigger: activityResumeTrigger: not whiteListedbluwyreinc.rohansfitness/bluwyreinc.rohansfitness.MainActivity/1
halfer
2#
halfer Reply to 2018-01-14 19:03:52Z

The problem is in your this method:

public Cursor getRow(long rowId) {
        String where = UserContract.NewUserInfo.USER_ROWID +"="+ rowId;
        Log.e("ID= ",where);

        String select = "SELECT "+ UserContract.NewUserInfo.USER_NAME+" FROM "+ UserContract.NewUserInfo.TABLE_NAME+ " WHERE "+where;
        Log.e("query = ", select);

        // Here db is null.
        db.execSQL(select);

        return null;
    }

Pass it sqLiteDatabase and It should be returning the cursor, something like this:

public Cursor getRow(SQLiteDatabase sqLiteDatabase, long rowId) {
        String where = UserContract.NewUserInfo.USER_ROWID +"="+ rowId;
        Log.e("ID= ",where);

        String select = "SELECT "+ UserContract.NewUserInfo.USER_NAME+" FROM "+ UserContract.NewUserInfo.TABLE_NAME+ " WHERE "+where;
        Log.e("query = ", select);
        cursor = sqLiteDatabase.query(select);

        return cursor;
    }
AdricoM
3#
AdricoM Reply to 2018-01-12 23:01:09Z

You never set any value to db field, so when you try to use it, it's null and causes your crash. You should ensure db is not null before using it

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.349236 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO