1

이 문제가 여러 번 언급되었지만 시도하지 않은 것은 저를 위해 노력하고 있습니다. SharedPreferences에 액세스하려고 할 때 여전히 오류가 발생합니다.비 활동 클래스에서 getSharedPreferences 오류

주요 활동 (McsHome)에서 사용자가 위치를 추가 할 수 있도록 다양한 대화 상자를 시작했습니다. 때 버튼을

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(); 
    } 
} 

이이 위치를 추가하는 옵션을 사용자에게 제공합니다

첫 번째 대화는이 단순히 위치 (PopupMessage.java)를 추가해야합니다라는 메시지를 팝업, 다음과 같습니다 또 다른 대화 상자를 클릭하면 (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() 메소드를 포함하는 세 번째 Class, ProcessLocation.java로 전달됩니다.

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 활동에서 컨텍스트를 전달하는 것과 관련이 있다고 확신하지만 시도한 모든 것이 실패했습니다.

+0

무엇이 오류입니까? – ToYonos

+0

시도해 보셨습니까? MODE_PRIVATE 또는 getActivity(). MODE_PRIVATE? – Lukos

+0

Context.MODE_PRIVATE, 대문자 C를 사용하고 android.content.Context를 가져 오십시오. – zgc7009

답변

1

우선 AddLocation에서 멤버 변수 addLoc을 선언하지만 절대 할당하지 마십시오. 컴파일이를 얻었다 경우는 NullPointerException 여기 던질 것이다 :

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

getSharedPreferences()Context 클래스의 방법이다. ProcessLocation.processLocation()에 전화하려고합니다. 이 메서드는 ProcessLocation 클래스에는 없습니다.

당신은 다음을 수행해야합니다 : 그것은 getSharedPreferences()를 호출 할 수 있도록하는 Context 참조가 필요 ProcessLocation

1). 이를 수행하는 가장 쉬운 방법은 에 Context 유형의 멤버 변수를 선언하고 ProcessLocation의 생성자에서 초기화하도록하는 것입니다. 이와 같이 :

2) ProcessLocation의 인스턴스를 만들어야합니다. 에서 변수 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); 
     ... 
    } 

늦었 내가 피곤 해요 내가 컴파일러를 통해이를 두지 않았기 때문에 용서해주십시오 나는 쉼표 나 세미콜론을 사용하지 않았거나 철자가 틀린 경우 나에게 알려줍니다. 잘하면 당신은 표류를 얻는다. 행운을 빕니다!

관련 문제