1
我是新開發的Android應用程序,目前我正在開發一個android軟件,需要用戶輸入相當數量的數據並將其作爲數據庫保存在sharedPreferences
上。這裏是例如我的編碼:根據輸入呼叫句子
public static final String DEFAULT= "no data found";
然後:
protected void storeData(SharedPreferences.Editor editor, String key, EditText et) {
String content = et.getText().toString();
if ("".equals(content)) {
editor.remove(key);
} else {
editor.putString(key, content);
}
}
用戶輸入的節約:
public void OnClickSave(){
button17=(Button)findViewById(R.id.button17);
button17.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
name = (EditText) findViewById(R.id.name);
gender = (EditText) findViewById(R.id.gender);
age = (EditText) findViewById(R.id.age);
fruit = (EditText) findViewById(R.id.fab_fruit);
music = (EditText) findViewById(R.id.fab_music);
SharedPreferences sharedPreferences = getSharedPreferences("Database", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
storeData(editor,"name", name);
storeData(editor,"gender", gender);
storeData(editor,"age", age);
storeData(editor,"fruit", fruit);
storeData(editor,"music", music);
editor.commit();
Toast.makeText(MainActivity7.this, "Data was saved!!!", Toast.LENGTH_SHORT).show();
}
}
);
}
對於加載數據,我做了這樣的事情:
public void OnClickLoad(){
button38=(Button)findViewById(R.id.button38);
button38.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences sharedPreferences = getSharedPreferences("Database", Context.MODE_PRIVATE);
String name = sharedPreferences.getString("name", DEFAULT);
String gender = sharedPreferences.getString("gender", DEFAULT);
String age = sharedPreferences.getString("age", DEFAULT);
String fruit = sharedPreferences.getString("fruit", DEFAULT);
String music = sharedPreferences.getString("music", DEFAULT);
}
}
);
AlertDialog.Builder a_builder = new AlertDialog.Builder(MainActivity12.this);
a_builder.setMessage(
"Data 1 name is :"+ name + "\n"+
"Data 1 gender is :"+ gender + "\n"+
"Data 1 age is :"+ age + "\n"+
"Data 1 favorite fruit is :"+ fruit + "\n"+
"Data 1 favorite music is :"+ music + "\n"+
)
.setCancelable(false)
.setPositiveButton("Proceed", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.setNegativeButton("Return", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
;
AlertDialog alert= a_builder.create();
alert.setTitle("Checking");
alert.show();
}
由於我已經設置了Sente NCE在構建器,所以當用戶沒有回答的問題之一,輸出將變得像
Data 1 name is : Sample1
Data 1 gender is : male
Data 1 age is : no data found
Data 1 favorite fruit is : apple
Data 1 favorite music is : no data found
我想知道是否有任何其他的方式,因此,如果用戶沒有輸入任何東西,相關句子不會出現,如下所示:
Data 1 name is : Sample1
Data 1 gender is : Male
Data 1 favorite fruit is : apple
這是編碼的例子,在我的應用程序中,我需要用戶輸入20-30數據。感謝所有願意幫助的人。 *如果標題引起混淆,我很抱歉,因爲我不確定它應該引用什麼。