2013-03-28 36 views
1

目前,我將數據存儲在我的Application類的靜態屬性中。當應用程序關閉時,數據仍然存在,但當從最近的菜單中清除應用程序(或緩存的進程被終止)時,Application類似乎也會從內存中擦除。在內存中存儲持久性(直到重新啓動)數據的位置?

我需要從活動/片段以及BroadcastReceiver中輕鬆訪問數據。數據在MainActivity啓動時首先加載。你可以在my GitHub project看到我的代碼。

更新

我使用SQLite存儲數據,並且活動時,它開始將數據加載到內存中。但我認爲我不能從BroadcastReceiver這樣做,因爲它們壽命有限,並且SQLite可能長期運行。主要問題是我需要我的BroadcastReceiver才能夠處理與活動相同的數據。

+2

持續直到重新啓動不是真的持久,是嗎? – SirDarius

+0

你不知道。如果你需要一些比應用程序更長的時間,那麼你需要將它寫入磁盤。 –

回答

1

更簡單的方法是使用android preferences。其他方式包括保存到磁盤或在SQLite數據庫中,您可以從閱讀以下內容開始:saving data in android

從Android教程的一個例子:

//Saving the data 
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE); 
SharedPreferences.Editor editor = sharedPref.edit(); 
editor.putInt(getString(R.string.saved_high_score), newHighScore); 
editor.commit(); 

//Loading of the saved data 
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE); 
int defaultValue = getResources().getInteger(R.string.saved_high_score_default); 
long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue); 

您可以使用您的SQLlite操作的AsyncTask

+0

我已經使用SQLite存儲/檢索活動中的數據,但是如果數據尚未加載,「BroadcastReceiver」無法自行加載並修改它,因爲SQLite可能長期運行,可以嗎? ? – Gawdl3y

+0

您可以使用Asynctask進行sql-lite操作 – Atropo

1

另一個有趣的可能性是將數據存儲爲xml文件。您可以使用它,例如簡單的XML庫:http://simple.sourceforge.net/

首先你應該做的註釋在模型類,

@Root 
public class Example { 

@Element 
private String text; 

@Attribute 
private int index; 

public Example() { 
    super(); 
} 

public Example(String text, int index) { 
    this.text = text; 
    this.index = index; 
} 

public String getMessage() { 
    return text; 
} 

public int getId() { 
    return index; 
} 
} 

然後,你可以保存這些對象:

Serializer serializer = new Persister(); 
Example example = new Example("Example message", 123); 
File result = new File("example.xml"); 

serializer.write(example, result); 

爲了得到這個文件再次這應該做的工作:

Serializer serializer = new Persister(); 
File source = new File("example.xml"); 

Example example = serializer.read(Example.class, source); 

這是一個最簡單的e從項目站點獲取xamples,但可以編寫嵌套對象以及列表。 它也是非常有據可查的

+0

儘管這絕對有可能,但我已經使用SQLite來存儲/檢索活動中的數據。另外,'BroadcastReceiver'不能做任何可能長期運行的事情,可以嗎? – Gawdl3y

相關問題