Get the Context in the Sington class.



  • Class MyObject in which the patter is used Singleton

    public class MyObject  {
    
    private static MyObject _instance = null;
    private String mMessage;
    
    
    private MyObject() {
       DBHelper dbHelper = new DBHelper(*Context*); // Здесь аргументом передается Context
       SQLiteDatabase database = dbHelper.getWritableDatabase();
       // Получаем нужные поля из БД
    }
    
    public static MyObject getInstance(){
        if(_instance==null){
            _instance = new MyObject();
        }
        return _instance;
    }
    

    }

    Designer DBHelper I need you to tell me. Context to connect to the OBD system and subsequently obtain the necessary data.
    There's a way to store. Context in the Singleton class Applicationwhere received Context using method getApplicationContext()

    How?



  • Do it.

    private Context context;
    private MyObject() {
       DBHelper dbHelper = new DBHelper(context); // Здесь аргументом передается Context
       SQLiteDatabase database = dbHelper.getWritableDatabase();
       // Получаем нужные поля из БД
    }
    

    public static MyObject getInstance(Context appContext){
    if(_instance==null){
    context = appContext;
    _instance = new MyObject();
    }
    return _instance;
    }

    from any activism you'll be taking. this.getApplicationContext()




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2