0

thanks for all the help so far. I have successfully created my database and viewed it with sqlite browser. I want to retrieve the values in each column separately. This is my code in DBHelper class:

public TingTingUser getCurrentUser(int id){
    SQLiteDatabase currDB = databaseManager.getWritableDatabase();
    Cursor cursor = currDB.query(true, TABLE_NAME, new String[]{COL_ID, COL_USER_ID, COL_FULL_NAME, COL_GENDER, COL_DOB, COL_MOBILE_NUM, COL_OCCUPATION, COL_ORGANIZATION}, COL_ID + "=?", new String[]{String.valueOf(id)}, null, null, null, null);

    if (cursor != null && cursor.moveToFirst()){
        TingTingUser user = new TingTingUser(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5), cursor.getString(6), cursor.getString(7));
        return user;
    }

    return null;

}

In log-cat, the values are coming correctly but in my activity class, it throws an exception. Here is my code for retrieving the individual values:

My DatabaseUtils class:

public class DatabaseUtils extends AppCompatActivity {

private static final String TAG = DatabaseUtils.class.getSimpleName();

protected static DBHelper helper;
public static Context context;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    helper = new DBHelper(this);
    context = this;

}

public static String getUserPhoneNumber(){
    TingTingUser user = helper.getCurrentUser(1);
    String number = user.getMobileNumber();

    Log.d(TAG, "Phone Number from DB is:\t" + number);

    if (number == null){
        return null;
    }
    return number;
}

public static String getUserNameFromDB(){
    TingTingUser user = helper.getCurrentUser(1);
    String name = user.getDisplayName();

    if (name == null){
        return null;
    }
    return name;

}

public static boolean saveGalleryImageToDB(Uri uri){
    helper.open();

    InputStream inputStream = null;
    try {
        inputStream = context.getContentResolver().openInputStream(uri);
        byte[] inputData = AppUtils.ImageUtils.getBytes(inputStream);
        helper.saveGalleryImage(inputData);
        helper.close();
        return true;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    finally {
        helper.close();
    }
    return false;

}

public static boolean loadImage(Context context, ImageView imageView){
    try{
        helper.open();
        byte[] bytes = helper.getImage();
        helper.close();
        Bitmap bitmap = AppUtils.ImageUtils.getImage(bytes);
        Uri uri = AppUtils.ImageUtils.getImageUri(context, bitmap);
        imageView.setImageBitmap(AppUtils.ImageUtils.getImage(bytes));
        return true;
    } catch (Exception ex){
        ex.printStackTrace();
    }
    return false;
}

}

Retrieving the phone number in activity sample code:

String phone = DatabaseUtils.getUserPhoneNumber();
Log.d(TAG, "Phone Number form DB is:\t" + phone);

TingTingUser is my user's model class with basic info demoed in DatabaseUtils class.

Exception message in logcat:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.billionusers.tingting.model.TingTingUser com.billionusers.tingting.db.DBHelper.getCurrentUser(int)' on a null object reference at com.billionusers.tingting.db.DatabaseUtils.getUserPhoneNumber(DatabaseUtils.java:39) at com.billionusers.tingting.activities.EditProfileActivity.onCreate(EditProfileActivity.java:89) at android.app.Activity.performCreate(Activity.java:5990) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)  at android.app.ActivityThread.access$800(ActivityThread.java:151)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:135)  at android.app.ActivityThread.main(ActivityThread.java:5254)  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:903)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 

How to solve this error guys? Thanks.

Here is a snapshot of my table: enter image description here

I want to get the column values separately. Please have a look and guide me. Thanks again guys.

Anand Rajput
  • 469
  • 1
  • 8
  • 21
  • where are you calling String phone = DatabaseUtils.getUserPhoneNumber(); – Abdul Waheed Nov 06 '17 at 13:04
  • In my activity where I want the db values to be used, sorry the classes are too lengthy, will take up space – Anand Rajput Nov 06 '17 at 13:05
  • you are calling this from another activity? – Abdul Waheed Nov 06 '17 at 13:05
  • There are a lot of things wrong here - turn your `DatabaseHelper` class into a singleton. There's a good tutorial here - http://www.androiddesignpatterns.com/2012/05/correctly-managing-your-sqlite-database.html - and access it directly, rather than via a static method on an `Activity`. Your specific error is caused by your attempts to access the database via a static method on an `Activity` class, when the `Activity` itself hasn't been created. Also, please don't store a `static` reference to an `Activity` - there's no reason to and it's a prime cause of memory leaks. – PPartisan Nov 06 '17 at 13:05
  • @AbdulWaheed, yes in user profile activity to populate views – Anand Rajput Nov 06 '17 at 13:07
  • @PPartisan, good idea but that's not the problem I think cos I have to do this severally in different activities that's why I implemented this way. Can you help out here? – Anand Rajput Nov 06 '17 at 13:08
  • Follow the advice in that blog post. For a globally accessible context, use the advice outlined here https://stackoverflow.com/questions/14057273/android-singleton-with-global-context - then whenever your need an instance of your Database, use `DbHelper.getInstance(App.get()).anyMethodOnYourDbHelperClass()` – PPartisan Nov 06 '17 at 13:10

2 Answers2

0

This is happening because you are not initialzing dbHelper. You are initializing that in activity onCreate method that means if you call that static method from other activity you will be able to access that method due to static. As you suggested you are calling from profileactity that means onCreate is not being. And due to this dbHelper is not initialized. To overcome this you should initialize dbhelper in that method (getUserPhoneNumber()) HOPE that helps you

Abdul Waheed
  • 4,540
  • 6
  • 35
  • 58
  • I have initialized in getUserPhoneNumber() method but it throws another exception. I'll edit the question so you can have a look at my table and tell me how to retireve the values individually. Thanks – Anand Rajput Nov 06 '17 at 14:07
0

Check in initialization of the database object.

nullpointer exception is specially caused when database object is not initialized properly.

Andy Rubin
  • 25
  • 7