LoginSignup
1
1

More than 3 years have passed since last update.

【Android】Daoの中でContextをセットする正しい順番

Posted at

注意

  • コンストラクタの中でContextをつめるべき。
  • 地の文で書くと、ContextがカラのままHelperにセットされてしまう。

OK

HogeAppDao.java
public class HogeAppDao {
    private Context mContext;
    private HugaHelper hugaHelper = new HugaHelper(mContext);

    public HogeAppDao(Context context) {
        mContext = context;
        hugaHelper = new HugaHelper(mContext);
    }

    //すべてのユーザーの情報を取得するメソッド
    public List<UserInfoEntity> selectAll() {
       ...
    };
}

NG

HogeAppDao.java
public class HogeAppDao {
    private Context mContext;
    private HugaHelper hugaHelper = new HugaHelper(mContext);

    public HogeAppDao(Context context) {
        mContext = context;
    }

    hugaHelper = new HugaHelper(mContext);

    //すべてのユーザーの情報を取得するメソッド
    public List<UserInfoEntity> selectAll() {
       ...
    };
}
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1