[英]Shared Preference VS Context?
我在Android方面的經驗不是很多,因此到目前為止,我編寫的每段代碼都非常簡單。 現在,我需要實現一個本地化和導航應用程序,因此需要將代碼分解為模塊,以便可以單獨更改每個組件。 我有一些變量需要在不同的類之間共享。 我使用了靜態變量,但是在這里我讀到一些文章,靜態變量不是首選。 然后,我發現了其他一些有關上下文的文章。 因此,我創建了一個名為Globals的類,並在清單文件中添加了以下幾行:
<application android:name="com.example.smartnav.Globals"
package="com.example.smartnav"
android:icon="@drawable/ic_launcher"
android:allowBackup="true"
android:label="@string/app_name"/>
這是Globals類別:
package com.example.smartnav;
import java.util.List;
import android.net.wifi.ScanResult;
import android.app.Application;
public class Globals extends Application {
private Boolean Scanning=false;
private String Logname;
private int interval;
private int numOfScans;
private List<ScanResult> result;
//getters
public Boolean getScannig(){
return Scanning;
}
public int getInterval()
{
return interval;
}
public int getScans()
{
return numOfScans;
}
public List<ScanResult> getRes()
{
return result;
}
public String getLog()
{
return Logname;
}
//setter
public void setScanning(Boolean s){
Scanning= s;
}
public void setRes(List<ScanResult> res)
{
result =res;
}
public void setInterval(int I)
{
interval = I;
}
public void setScans(int S)
{
numOfScans=S;
}
public void setLog(String s)
{
Logname= s;
}
}
現在,我有兩個問題,第一個是我每次嘗試使用Globals類時應用程序都會崩潰,這是代碼:我使用的上下文不正確嗎?
public class MainActivity extends Activity {
private Context context;
public WifiManager Wifi;
private WifiReceiver receiverWifi;
private IntentFilter filter;
private List<ScanResult> result;
private File AppDir;
private static String filename;
private File file;
private FileWriter writer;
private Globals AppState ;
private int Interval;
private int numOfScans;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("Main ","activity created");
//
AppState = ((Globals)getApplicationContext());
context= this;
Wifi=(WifiManager) getSystemService(Context.WIFI_SERVICE);
receiverWifi = new WifiReceiver();
filter= new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
registerReceiver(receiverWifi, filter);
Log.d("Main ","wifi registered");
// create the application directory
AppDir = new File(Environment.getExternalStorageDirectory()+"/SmartNavi/Log");
if(AppDir.isDirectory())
{
filename=Environment.getExternalStorageDirectory()+"/SmartNavi/Log/log.txt";
file = new File(filename);
if(!file.exists())
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
else
{
Date d= new Date();
filename=Environment.getExternalStorageDirectory()+"/SmartNavi/Log/log"+d.getTime()+".txt";
file = new File(filename);
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
else
{
AppDir.mkdirs();
filename=Environment.getExternalStorageDirectory()+"/SmartNavi/Log/log.txt";
file = new File(filename);
if(!file.exists())
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
else
{
Date d= new Date();
filename=Environment.getExternalStorageDirectory()+"/SmartNavi/Log/log"+d.getTime()+".txt";
file = new File(filename);
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//setting pars
Interval=250;
numOfScans=4;
AppState.setInterval(Interval);
AppState.setScans(numOfScans);
AppState.setLog(filename);
Wifi.startScan();
try {
writer = new FileWriter(file, true);
writer.append("Smart Navigation. \n");
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// AsyncScanning.AsyncScan();
}//on create
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
class WifiReceiver extends BroadcastReceiver {
public void onReceive(Context c, Intent intent) {
result=Wifi.getScanResults();
// AppState.setRes(result);
try {
writer = new FileWriter(file, true);
writer.append(result.size()+" s \n");
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}//end of on receive
}// end of class
} // end of smartNav
我的最后一個問題是:我在這里閱讀了一些答案,如果我的應用程序成為后台進程,則上下文中的所有數據都將設置為null,並且我將丟失上下文。 有什么方法可以克服這一點? 還是應該切換到SharedPreferences?
編輯:這里是Logcat的輸出
java.lang.RuntimeException:無法啟動活動ComponentInfo {com.example.smartnav / com.example.smartnav.MainActivity}:java.lang.ClassCastException:android.app.Application無法轉換為com.example.smartnav.Globals
現在,我有兩個問題,第一個是我每次嘗試使用Globals類時應用程序都會崩潰,這是代碼:我使用的上下文不正確嗎?
您應該為此使用getApplication()
方法,或使應用程序類為單例,以便調用Globals.getInstance().getMyVariable()
等。
我的最后一個問題是:我在這里閱讀了一些答案,如果我的應用程序成為后台進程,則上下文中的所有數據都將設置為null,並且我將丟失上下文。 有什么方法可以克服這一點? 還是應該切換到SharedPreferences?
如果您的應用程序變為后台,則Android更有可能殺死您的應用程序,並且這種方式還會破壞您的所有靜態對象。 在Globals
類內部,您不應將數據存儲在靜態變量中,而應存儲在一些持久性存儲中-如果數據較小,則使用SharedPreferences
;如果數據較大,則可以將其存儲在json中並保存到應用程序內存中,或者使用sqlite db。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.