问题描述
我处理片段。
我有一个活动
和不同的片段
。
每个片段
需要访问类(称之为X)
,允许它访问数据库,但由于我有很多碎片,我不希望创建一个不同的实例类X
中,因为我认为这将需要大量的内存。
所以,我该怎么办?
我写了这样的事情(有一个getter),但它不工作!
I'm dealing with fragments.
I have an Activity
and different fragments
.
Each fragment
need the access to a Class(call it X)
that allow it to access a database, but, because I have a lot of fragments, I don't want to create a different instance of the Class X
in every fragment as I think it will require lots of memory
.
So how can I do?
I wrote something like this (with a getter), but it doesn't work!
public class MyActivity {
private ClassX classx;
.....
public ClassX getClassX() {
return classx;
}
.....
}
但不是,我怎么能在片段称之为
?
推荐答案
这是一点点的Java的问题和Android。
This is a little bit more of a Java question and android.
如果你在看访问数据库,查看创建数据库单。
If you looking at accessing the database, look at creating a database singleton.
所以是这样的:
public class Database {
// This starts off null
private static Database mInstance;
/**
* Singleton method, will return the same object each time.
*/
public static final Database getInstance() {
// First time this method is called by Database.getInstance() from anywhere
// in your App. It will create this Object once.
if(mInstance == null) mInstance = new Database();
// Returns the created object from a statically assigned field so its never
// destroyed until you do it manually.
return mInstance;
}
//Private constructor to stop you from creating this object by accident
private Database(){
//Init db object
}
}
于是从碎片和活动,你就可以把你们班的以下字段(更好地利用使用基本活动和碎片,以节省您重复code)。
So then from your fragments and activities you can then place the following field in your class's (Better use use a base activity and fragment to save you repeating code).
public abstract class BaseFragment extends Fragment {
protected final Database mDatabase = Database.getInstance();
}
那么你的混凝土碎片可以延长你的 BaseFragment
如: SearchListFragment延伸BaseFragment
希望这有助于。
值得一读有关单身并的
问候,克里斯
这篇关于呼叫活动的方法从碎片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!