[英]Shared Preference VS Context?
I'm not that much experienced in Android, so every piece of code I have written so far was very simple. 我在Android方面的经验不是很多,因此到目前为止,我编写的每段代码都非常简单。 Now I need to implement a localization and navigation application, so I need to break my code into modules so that I can change each component alone.
现在,我需要实现一个本地化和导航应用程序,因此需要将代码分解为模块,以便可以单独更改每个组件。 I have some variables that I need to share them between different classes.
我有一些变量需要在不同的类之间共享。 I used static variables but I read in some posts here that static variables are not preferred.
我使用了静态变量,但是在这里我读到一些文章,静态变量不是首选。 Then I found some other posts talking about Context.
然后,我发现了其他一些有关上下文的文章。 So I created a class named Globals and I added the following lines in my Manifest file:
因此,我创建了一个名为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"/>
And here is the Globals Class : 这是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;
}
}
Now I have two questions, the first one is that my application keeps crashing whenever I try to use the Globals class, here is the code: Did I use context incorrectly? 现在,我有两个问题,第一个是我每次尝试使用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
My last question is this : I have read on some answers here that if my application becomes a background process then all the data in the context will be set to null, and I will lose my context. 我的最后一个问题是:我在这里阅读了一些答案,如果我的应用程序成为后台进程,则上下文中的所有数据都将设置为null,并且我将丢失上下文。 Is there is any method to overcome this point?
有什么方法可以克服这一点? or should I switch to SharedPreferences ?
还是应该切换到SharedPreferences?
Edit :Here is the output of Logcat 编辑:这里是Logcat的输出
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.smartnav/com.example.smartnav.MainActivity}: java.lang.ClassCastException: android.app.Application cannot be cast to com.example.smartnav.Globals
java.lang.RuntimeException:无法启动活动ComponentInfo {com.example.smartnav / com.example.smartnav.MainActivity}:java.lang.ClassCastException:android.app.Application无法转换为com.example.smartnav.Globals
Now I have two questions, the first one is that my application keeps crashing whenever I try to use the Globals class, here is the code: Did I use context incorrectly?
现在,我有两个问题,第一个是我每次尝试使用Globals类时应用程序都会崩溃,这是代码:我使用的上下文不正确吗?
you should use getApplication()
method for that, or make your application class singleton, so you would call Globals.getInstance().getMyVariable()
etc. 您应该为此使用
getApplication()
方法,或使应用程序类为单例,以便调用Globals.getInstance().getMyVariable()
等。
My last question is this : I have read on some answers here that if my application becomes a background process then all the data in the context will be set to null, and I will lose my context.
我的最后一个问题是:我在这里阅读了一些答案,如果我的应用程序成为后台进程,则上下文中的所有数据都将设置为null,并且我将丢失上下文。 Is there is any method to overcome this point?
有什么方法可以克服这一点? or should I switch to SharedPreferences ?
还是应该切换到SharedPreferences?
if your app becomes background then Android is more likely to kill your app, and this way also destroy all your static objects. 如果您的应用程序变为后台,则Android更有可能杀死您的应用程序,并且这种方式还会破坏您的所有静态对象。 Inside your
Globals
class you should not store your data in static variables but rather in some persistant storage - if its small then use SharedPreferences
, if its large then you can store it in json and save to application memory, or use sqlite db. 在
Globals
类内部,您不应将数据存储在静态变量中,而应存储在一些持久性存储中-如果数据较小,则使用SharedPreferences
;如果数据较大,则可以将其存储在json中并保存到应用程序内存中,或者使用sqlite db。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.