简体   繁体   中英

getSharedPreferences error in non-activity class

I realize this issue has been touched on numerous times but nothing I try is working for me. I still get errors when trying to access SharedPreferences .

From the main Activity (McsHome) I am launch a variety of Dialogs to help the user add a location.

The first Dialog is below, this simply pops up a message stating a location needs to be added (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();
    }
}

This gives the user an option to add a location, when that button is clicked another dialog pops up (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();
    }

The AddLocation.java uses an XML layout which includes 3 EditText fields. The values of these are passed on to a third Class, ProcessLocation.java which includes the method 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");
                }

        }

}

I'm getting an error on the MODE_PRIVATE , I believe related to Context. I've been playing around with context for hours with no luck (or understanding). I know I'm popping up a couple of dialogs in a row. If I add "extends Activity" the error goes away but then the app crashes when trying to getSharedPreferences .

From going through the other posts I'm sure it's to do with passing the context from my McsHome.java activity but everything I've tried has failed.

First of all, in AddLocation you declare the member variable addLoc , but you never assign it to anything. If you did get this to compile, it would throw a NullPointerException here:

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

getSharedPreferences() is a method of the Context class. In ProcessLocation.processLocation() you are trying to call it. This method doesn't exist in the ProcessLocation class.

You need to do the following:

1) ProcessLocation needs to have a Context reference, so that it can call getSharedPreferences() . The easiest way to do this is to declare a member variable in ProcessLocation of type Context and have it initialized in the constructor of ProcessLocation . Like this:

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

2) You need to create an instance of ProcessLocation . In AddLocation , before using the variable addLoc you will need to initialize it. Like this:

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

3) Use the Context in ProcessLocation.processLocation() , like this:

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

It is late and I'm tired and I didn't put this through a compiler, so please forgive me if I left out a comma or a semicolon or spelled something wrong. Hopefully you get the drift. Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM