一、题目
Android SharedPreferences存储电话号码
二、环境
Win10 AndroidStudio
三、代码实现
package com.example.children;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class StoryPhoneActivity extends AppCompatActivity implements View.OnClickListener {
private TextView text1;
private TextView text2;
private EditText PhoneNumber1;
private EditText PhoneNumber2;
private Button mBtnOk;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_storyphone);
initViews();
}
@Override
public void onClick(View v) {
String phone1 = PhoneNumber1.getText().toString().trim();
String phone2 = PhoneNumber2.getText().toString().trim();
if ("".equalsIgnoreCase(phone1) || "".equalsIgnoreCase(phone2)) {
Toast.makeText(this, "爸爸妈妈的电话都不能为空!", Toast.LENGTH_LONG).show();
}
else {
SharedPreferences phone_info = getSharedPreferences("phone_info", MODE_PRIVATE);
SharedPreferences.Editor editor = phone_info.edit();
editor.putString("PhoneNumber1",phone1);
editor.putString("PhoneNumber2",phone2);
editor.apply();//---应用操作
editor.commit();
Toast.makeText(this, "电话信息保存成功!", Toast.LENGTH_LONG).show();
}
}
private void initViews() {
text1 = (TextView) findViewById(R.id.text1);
text2 = (TextView) findViewById(R.id.text2);
PhoneNumber1 = (EditText)findViewById(R.id.PhoneNumber1);
PhoneNumber2 = (EditText)findViewById(R.id.PhoneNumber2);
mBtnOk = (Button)findViewById(R.id.btnOk);
mBtnOk.setOnClickListener(this);
}
}
四、实验结果
后一篇博客为一键拨号的demo
有问题,欢迎留言交流!