我正在尝试设计一款应用,今天就遇到了这个问题。
试图从SharedPreferences
访问LegalProsecution.java
,我遇到了一些关于它不属于同一类的错误,等等等等等等等等。好的,我在另一个班级AppPreference.java
尝试了这个。
以下是代码:
package ideaman924.camerasilencer;
import android.content.Context;
import android.content.SharedPreferences;
import android.view.View;
public class AppPreference
{
private static AppPreference appprefs;
private SharedPreferences prefs;
public static AppPreference getInstance(Context context)
{
if(appprefs == null) appprefs = new AppPreference(context);
return appprefs;
}
private AppPreference(Context context)
{
prefs = context.getSharedPreferences("ideaman924.camerasilencer.settings",Context.MODE_PRIVATE);
}
public void storeSettings(int num)
{
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("first_run", num);
editor.apply();
}
public int loadSettings()
{
return prefs.getInt("first_run",0);
}
}
这部分应用看起来不错(没有错误),所以我回到了LegalProsecution.java
。但是,当我尝试拨打AppPreferences.java
时,我遇到了问题:
package ideaman924.camerasilencer;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.support.v7.app.AlertDialog;
public class LegalProsecution {
AppPreference appprefs = AppPreference.getInstance(context);
if(appprefs.loadSettings == 1);
else
{
AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
builder1.setTitle(getString(R.string.warning));
builder1.setMessage(getString(R.string.warning_description));
builder1.setCancelable(true);
builder1.setPositiveButton(
"Yes",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//Got promise from user, now setting first_run to 1
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("first_run",1);
editor.apply();
dialog.cancel();
}
}
);
builder1.setNegativeButton(
"No",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//Okay, cool, bye! No CS for you!
dialog.cancel();
System.exit(0);
}
}
);
AlertDialog alert1 = builder1.create();
alert1.show();
}
}
忽略此行下方的任何内容,因为这是错误发生的地方:
AppPreference appprefs = AppPreference.getInstance(context);
所以,基本上,Android Studio抱怨说没有上下文了,这很奇怪,因为我已经上课了。咦?
而且,下面的一行:
if(appprefs.loadSettings == 1);
运行无法找到符号的错误,但我假设上述行的错误未正确初始化。正确?
有人帮忙吗?
编辑:从loadSettings中删除了View v,因为这是不必要的。
答案 0 :(得分:1)
您需要将上下文的实例传递给getInstance(context)
方法。
由于您的LegalProsecution
似乎无法访问上下文,您可以使用对上下文的静态访问创建自己的应用程序类,然后在任何地方使用此上下文。
创建您的应用程序类:
public class MyApp extends Application {
private static MyApp instance;
public static MyApp getInstance() {
return instance;
}
public static Context getContext(){
return instance.getApplicationContext()
}
@Override
public void onCreate() {
super.onCreate();
instance = this;
}
}
将新创建的应用程序添加到清单中的现有<application>
标记中:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.yourapp"
...
>
<application
android:name=".MyApp"
...
>
完成此操作后,您可以在XMLParser中加载属性:
AppPreference appprefs = AppPreference.getInstance(MyApp.getContext());