创建了Singleton-class:
SQL> select count(1) from new_table union all
2 select count(1) from new_table1 union all
3 select count(1) from new_table2;
COUNT(1)
----------
1000000
1000000
1000000
在MyApplication类中已初始化它:
public class DataManager
{
private static DataManager mDataManager;
private static Database mDatabase;
private static DaoSession mDaoSession;
private static List<Task> mTasks;
public static void initInstance(Context context)
{
if (mDataManager == null)
{
mDataManager = new DataManager();
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(context, "TASKS");
mDatabase = helper.getWritableDb();
mDaoSession = new DaoMaster(mDatabase).newSession();
mTasks = mDaoSession.queryBuilder(Task.class).build().list();
}
}
public static DataManager getInstance()
{
return mDataManager;
}
public Database getDatabase()
{
return mDatabase;
}
public DaoSession getDaoSession()
{
return mDaoSession;
}
public List<Task> getTaskList()
{
return mTasks;
}
public void updateTaskList()
{
mTasks = mDaoSession.queryBuilder(Task.class).build().list();
}
}
清单中指定的MyApplication:
public class MyApplication extends Application
{
@Override
public void onCreate()
{
super.onCreate();
DataManager.initInstance(getApplicationContext());
}
}
在MainActivity类onCreate方法中,我得到了列表并将其放到<application
android:name=".MyApplication"
...
:
RecyclerView
在onDestroy中清除了会话并关闭了数据库:
public class MainActivity extends AppCompatActivity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List<Task> tasks = DataManager.getInstance().getTasksList();
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.rvMainRecycler);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
MainRecyclerViewAdapter mainRecyclerViewAdapter = new MainRecyclerViewAdapter(tasks);
recyclerView.setAdapter(mainRecyclerViewAdapter);
}
...
在其他活动中,在按钮上设置了监听器:
@Override
protected void onDestroy()
{
DataManager.getInstance().getDaoSession().clear();
DataManager.getInstance().getDatabase().close();
super.onDestroy();
}
我想知道的是:
btnInsert.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
TaskDao taskDao = DataManager.getInstance().getDaoSession().getTaskDao();
Task task = new Task(/*здесь некоторые параметры*/);
taskDao.insertOrReplaceInTx(task);
taskDao.detachAll();
}
});
- 是否有必要?
taskDao.detachAll();
- 是否有必要清除会话?
DataManager.getInstance().getDaoSession().clear();
- 并关闭数据库?
在DataManager.getInstance().getDatabase().close();
之前调用它们是否正确?
P.S。在清单文件中,我只为所有活动设置纵向方向,因此不会在屏幕旋转时重新创建活动。也许我和Singleton一起徒劳无功?