我有一个应用程序,它只有一个布局,并且该布局有一些用于设置的EditText字段。我希望这些EditText字段中的数据可以在应用程序中的不同类中使用。我会使用PreferenceFragmentCompat来做到这一点吗?
我发现了SharedPreferences,但是我在访问set字符串时遇到了问题。
我的主要活动
private void initViews() {
setDefaultAppButton = (Button) findViewById(R.id.set_as_default);
selectApns = (Button) findViewById(R.id.apns);
fromField = (EditText) findViewById(R.id.from);
toField = (EditText) findViewById(R.id.to);
messageField = (EditText) findViewById(R.id.message);
imageToSend = (ImageView) findViewById(R.id.image);
sendButton = (Button) findViewById(R.id.send);
log = (RecyclerView) findViewById(R.id.log);
Pref.setDevicePhoneNumber(fromField.getText().toString());
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.edit().putString("devicePhoneNumber", fromField.getText().toString());
prefs.edit().commit();
}
上面的代码工作正常,但在下面的类中,关键字“this”带有红色下划线,并带有消息“getDefaultSharedPreferences (android.content.Context) 在PreferenceManager中无法应用 至 (com.klinker.android.messaging_sample.SmsReceiver) “
public class SmsReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Object[] smsExtra = (Object[]) intent.getExtras().get("pdus");
String body = "";
String originatingAddress = "";
for (int i = 0; i < smsExtra.length; ++i) {
SmsMessage sms = SmsMessage.createFromPdu((byte[]) smsExtra[i]);
body += sms.getMessageBody();
originatingAddress = sms.getOriginatingAddress();
}
String from = (originatingAddress!=null && originatingAddress.length()>3)?(originatingAddress.replace("+", "")):("") ;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
Log.d("Device Number","Device number: " + prefs.getString("devicePhoneNumber", "DEFAULT"));
}
}