gpt4 book ai didi

java - 共享偏好 VS 上下文?

转载 作者:行者123 更新时间:2023-12-01 13:22:18 25 4
gpt4 key购买 nike

我对 Android 的经验不是很多,所以到目前为止我编写的每一段代码都非常简单。现在我需要实现一个本地化和导航应用程序,因此我需要将代码分解为模块,以便我可以单独更改每个组件。我有一些变量需要在不同的类之间共享它们。我使用了静态变量,但我在一些帖子中读到静态变量不是首选。然后我发现了一些其他谈论上下文的帖子。因此,我创建了一个名为 Globals 的类,并在 list 文件中添加了以下几行:

 <application android:name="com.example.smartnav.Globals" 
package="com.example.smartnav"
android:icon="@drawable/ic_launcher"
android:allowBackup="true"

android:label="@string/app_name"/>

这是全局类:

    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

我的最后一个问题是:我在这里读到了一些答案,如果我的应用程序成为后台进程,那么上下文中的所有数据将被设置为空,我将失去我的上下文。有什么方法可以克服这一点吗?或者我应该切换到 SharedPreferences ?

编辑:这是 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

最佳答案

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?

您应该使用 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. Is there is any method to overcome this point? or should I switch to SharedPreferences ?

如果您的应用程序成为后台,那么 Android 更有可能杀死您的应用程序,这样也会破坏您的所有静态对象。在您的 Globals 类中,您不应将数据存储在静态变量中,而应存储在某些持久存储中 - 如果数据较小,则使用 SharedPreferences,如果数据较大,则可以将其存储在json 并保存到应用程序内存,或使用 sqlite db。

关于java - 共享偏好 VS 上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21956655/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com