package sn.len.sharedpreferences; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class SharedPreferencesActivity extends Activity { private EditText name=null; private EditText age=null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); name=(EditText)findViewById(R.id.webname); age=(EditText)findViewById(R.id.age); Button saveButton=(Button)findViewById(R.id.saveButton); Button restorationButton=(Button)findViewById(R.id.restorationData); //写入信息 saveButton.setOnClickListener ( new View.OnClickListener() { @Override public void onClick(View v) { String web_name=name.getText().toString(); String true_age=age.getText().toString(); SharedPreferences preferences=getSharedPreferences("softinfo",Context.MODE_WORLD_READABLE); Editor edit=preferences.edit(); edit.putString("name", web_name); edit.putInt("age",new Integer(true_age)); edit.commit(); Toast.makeText(SharedPreferencesActivity.this, R.string.success,Toast.LENGTH_LONG).show(); } } ); //读取信息 restorationButton.setOnClickListener ( new View.OnClickListener() { @Override public void onClick(View v) { SharedPreferences ferences=getSharedPreferences("softinfo",0); String true_name=ferences.getString("name", ""); int true_age=ferences.getInt("age", 20); name.setText(true_name); age.setText(String.valueOf(true_age)); } } ); } }
Android SharedPreferences(信息的保存和读取)
内容版权声明:除非注明,否则皆为本站原创文章。