【问题标题】:getSharedPreferences error in non-activity class非活动类中的 getSharedPreferences 错误
【发布时间】:2014-11-12 20:18:57
【问题描述】:

我意识到这个问题已被多次提及,但我尝试的任何方法都对我不起作用。尝试访问 SharedPreferences 时仍然出现错误。

我从主 Activity (McsHome) 启动各种对话框来帮助用户添加位置。

下面是第一个Dialog,它只是简单地弹出一条消息,说明需要添加一个位置(PopupMessage.java):

public class PopupMessage extends DialogFragment {

    String message = "";
    AddLocation addLocation;


    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        addLocation = new AddLocation();

        // Use the Builder class for convenient dialog construction
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage(message)
               .setPositiveButton("Add Location", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                       addLocation.show(getFragmentManager(), "PopupMsgFragment");
                   }
               })
               .setNegativeButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
              //
            };
        });
        // Create the AlertDialog object and return it
        return builder.create();
    }
}

这为用户提供了添加位置的选项,当单击该按钮时会弹出另一个对话框(AddLocation.java):

public class AddLocation extends DialogFragment {

    EditText mcsDomain;
    EditText friendlyName;
    EditText password;
    ProcessLocation addLoc;
    String message = "";

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        LayoutInflater inflater = getActivity().getLayoutInflater();
        View layout = inflater.inflate(R.layout.add_location_dialog, null); // Pass null as the parent view because its going in the dialog layout
        mcsDomain = (EditText) layout.findViewById(R.id.mcsDomain);
        friendlyName = (EditText) layout.findViewById(R.id.friendlyName);
        password = (EditText) layout.findViewById(R.id.password);

        builder.setView(layout)
                .setTitle("Add/Update Location")
        // Add action buttons
               .setPositiveButton("Add/Update", new DialogInterface.OnClickListener() {
                   @Override

                   public void onClick(DialogInterface dialog, int id) {

                       // Passes the chosen location parameters to the ProcessLocation class
                       addLoc.processLocation(mcsDomain.getText().toString(),friendlyName.getText().toString(),password.getText().toString());

                   }
               })
               .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {

                   }
               });      
        return builder.create();
    }

AddLocation.java 使用包含 3 个 EditText 字段的 XML 布局。这些值被传递给第三个类,ProcessLocation.java,其中包括方法processLocation()

public class ProcessLocation {


    SharedPreferences domainToName;
    SharedPreferences nameToDomain;


     public void processLocation(String domain, String name, String password) {

            domainToName = getSharedPreferences("domainToName",  MODE_PRIVATE);
            nameToDomain = getSharedPreferences("nameToDomain",  MODE_PRIVATE);
        //  final Editor domainEdit = domainToName.edit();
        //  final Editor nameEdit = nameToDomain.edit();

            if (nameToDomain.contains(name)) {
                   System.out.println("Name Doesn't Exist");
                }

        }

}

我在MODE_PRIVATE 上遇到错误,我认为这与上下文有关。我已经玩了几个小时没有运气(或理解)的上下文。我知道我连续弹出几个对话框。如果我添加“扩展活动”,错误就会消失,但是当尝试getSharedPreferences 时应用会崩溃。

通过浏览其他帖子,我确信这与从我的 McsHome.java 活动传递上下文有关,但我尝试过的一切都失败了。

【问题讨论】:

  • 你试过 this.MODE_PRIVATE 还是 getActivity().MODE_PRIVATE?
  • 试试Context.MODE_PRIVATE,大写C,导入android.content.Context;
  • 对我的评论的解释(我保证你应该在尝试任何过于复杂的东西之前尝试一下)是 MODE_PRIVATE 是 Context 类中的公共静态常量。因此,您可以通过 Context.MODE_PRIVATE 访问它,而无需访问您当前的上下文(因为它不依赖于您当前的上下文,它只是一个常量)。

标签: java android android-activity sharedpreferences android-context


【解决方案1】:

首先,在AddLocation 中,您声明了成员变量addLoc,但您从未将其分配给任何东西。如果你确实让它编译,它会在这里抛出一个NullPointerException

addLoc.processLocation(mcsDomain.getText().toString(), friendlyName.getText().toString(),
        password.getText().toString());

getSharedPreferences()Context 类的方法。在ProcessLocation.processLocation() 中,您正在尝试调用它。 ProcessLocation 类中不存在此方法。

您需要执行以下操作:

1) ProcessLocation 需要有一个Context 引用,这样它才能调用getSharedPreferences()。最简单的方法是在ProcessLocation 中声明一个Context 类型的成员变量,并在ProcessLocation 的构造函数中对其进行初始化。像这样:

public class ProcessLocation {
    Context context;
    SharedPreferences domainToName;
    SharedPreferences nameToDomain;
    // Constructor
    ProcessLocation(Context context) {
        this.context = context;
    }

2) 你需要创建一个ProcessLocation 的实例。在AddLocation 中,在使用变量addLoc 之前,您需要对其进行初始化。像这样:

    // Create instance of ProcessLocation and pass it the activity (Activity is a Context)
    addLoc = new ProcessLocation(getActivity);

3) 在ProcessLocation.processLocation() 中使用Context,如下所示:

    public void processLocation(String domain, String name, String password) {
        domainToName = context.getSharedPreferences("domainToName",  Context.MODE_PRIVATE);
        nameToDomain = context.getSharedPreferences("nameToDomain",  Context.MODE_PRIVATE);
        ...
    }

太晚了,我累了,我没有把它通过编译器,所以如果我遗漏了逗号或分号或拼写错误,请原谅我。希望你得到漂移。祝你好运!

【讨论】:

    猜你喜欢
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-06
    • 1970-01-01
    • 2013-04-15
    • 2015-04-14
    • 1970-01-01
    相关资源
    最近更新 更多