2013-03-28 96 views
0

我想要在SharedPreference中存儲EditTextAlertDialog)字段中的值。它顯示在此行SharedPreferences.Editor editor = sp.edit(); **注意NullPointerException:代碼工作不SharedPreferences **自定義警報對話框中的共享首選項

private void myDialog() { 
    // TODO Auto-generated method stub 
    LayoutInflater inflater = LayoutInflater.from(getApplicationContext()); 
    View view = inflater.inflate(R.layout.cus_dialog, null); 
    AlertDialog.Builder ab = new AlertDialog.Builder(this); 
    ab.setView(view); 
    final EditText input = (EditText) view.findViewById(R.id.etValue); 

    ab.setCancelable(false); 
    ab.setPositiveButton("Send", new DialogInterface.OnClickListener() { 

     @Override 
     public void onClick(DialogInterface dialog, int which) { 
      String s = input.getText().toString(); 
      SharedPreferences.Editor editor = sp.edit(); 
      editor.putString("A", s); 
      editor.commit(); 
      Toast.makeText(getApplicationContext(), "" + s, 
        Toast.LENGTH_SHORT).show(); 
     } 
    }); 
    ab.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 

     @Override 
     public void onClick(DialogInterface dialog, int which) { 
      // TODO Auto-generated method stub 
      dialog.cancel(); 
     } 
    }); 
    AlertDialog ad = ab.create(); 

    ad.show(); 
} 

enter image description here

+0

哪裏是你的SP變量聲明? – 2013-03-28 08:05:44

回答

3
SharedPreferences preferences = PreferenceManager 
         .getDefaultSharedPreferences(acivity.this); 
       SharedPreferences.Editor editor = preferences.edit(); 
       editor.putString("a", "a"); 
       editor.commit();