非活动类中的getSharedPreferences错误

时间:2014-11-12 20:18:57

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

我意识到这个问题已被无数次触及,但我尝试的任何事情都不适合我。尝试访问SharedPreferences时仍然出错。

从主Activity(McsHome)我发布了各种Dialogs来帮助用户添加位置。

第一个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收到错误,我认为与Context相关。我已经玩了几个小时的背景,没有运气(或理解)。我知道我连续弹出几个对话框。如果我添加"扩展活动"错误消失但是在尝试getSharedPreferences时应用程序崩溃了。

通过其他帖子,我确定要从我的McsHome.java活动中传递上下文,但我尝试过的所有内容都失败了。

1 个答案:

答案 0 :(得分: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的{​​{1}}中声明成员变量,并在Context的构造函数中初始化它。像这样:

ProcessLocation

2)您需要创建public class ProcessLocation { Context context; SharedPreferences domainToName; SharedPreferences nameToDomain; // Constructor ProcessLocation(Context context) { this.context = context; } 的实例。在ProcessLocation中,在使用变量AddLocation之前,您需要对其进行初始化。像这样:

addLoc

3)使用 // Create instance of ProcessLocation and pass it the activity (Activity is a Context) addLoc = new ProcessLocation(getActivity); 中的Context,如下所示:

ProcessLocation.processLocation()

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