如何保存输入以便以后使用它(我一直尝试使用共享偏好设置)?

时间:2017-05-09 01:40:23

标签: java android input save android-phone-call

该应用正在获取一个输入号码,并有一个拨打电话的按钮。我想保存输入供以后使用,并尝试使用共享首选项。

public class MainActivity extends AppCompatActivity {

    Button myButton = null;
    EditText numberCall = null;
    int PERMISSION_ALL = 1;
    String[] PERMISSIONS = {Manifest.permission.READ_CONTACTS, Manifest.permission.CALL_PHONE};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

拨打电话的按钮:

    myButton = (Button) findViewById(R.id.button);

我想保存numberCall!

    numberCall = (EditText) findViewById(R.id.editText);

要求许可

    if(!hasPermissions(this, PERMISSIONS)){
        ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
    }

    myButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {


            OnCallBtnClicked();
        }
    });
}

拨打电话

private void OnCallBtnClicked() {

    Integer num = Integer.valueOf(numberCall.getText().toString());
    Intent call = new Intent(Intent.ACTION_CALL);
    call.setData(Uri.parse("tel:" +"0"+num));
    startActivity(call);

    }

public static boolean hasPermissions(Context context, String... permissions) {
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
        for (String permission : permissions) {
            if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
    }
    return true;
}

2 个答案:

答案 0 :(得分:0)

共享偏好是最简单的解决方案。将您的OnCallBtnClicked方法更改为:

 private void OnCallBtnClicked() {
        Integer num = Integer.valueOf(numberCall.getText().toString());
        Intent call = new Intent(Intent.ACTION_CALL);
        call.setData(Uri.parse("tel:" +"0"+num));
        SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME,MODE_PRIVATE).edit();
     editor.putString("Phone", "0"+num);

     editor.commit();

      startActivity(call);

        }

获取您保存的值,请尝试以下操作:

SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); 
String restoredText = prefs.getString("Phone", null);
if (restoredText != null) {
  String phone= prefs.getString("Phone", "No value defined");//"No valuedefined" is the default value.

}

Source

答案 1 :(得分:0)

@TsurYohananov 如果要添加数据库,则很容易获得用户存储的值

Firebase数据库具有提供此功能的功能。 youtube上还有更多视频可供参考。