2015-09-27 103 views
0

我试图更新编辑器,当用户想要更改信息。但编辑不更新。它只是存储相同的信息。我已经在其他课程中清除了它,但仍然没有获得新的值。我该怎么办?编辑器不更新

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_test); 
    h1 = (EditText) findViewById(R.id.h12); 
    min1 = (EditText) findViewById(R.id.min12); 
    d1 = (EditText) findViewById(R.id.d12); 
    m1 = (EditText) findViewById(R.id.m12); 
    y1 = (EditText) findViewById(R.id.y12); 
    button8 = (Button) findViewById(R.id.button8); 
    button8.setOnClickListener(this); 
    sp = getSharedPreferences("A", Context.MODE_PRIVATE); 
    abc = sp.getInt("d11",0); 
    if (abc != 0) 
    { 
     startActivity(new Intent("com.example.dc2.TEST3")); 
    } 
} 


public void onClick(View v) { 
    sp = getSharedPreferences("A", Context.MODE_PRIVATE); 
    d11 = Integer.parseInt(d1.getText().toString()); 
    m11 = Integer.parseInt(m1.getText().toString()); 
    y11 = Integer.parseInt(y1.getText().toString()); 
    if(h1.getText().toString().trim().length() == 0) 
    { 
     h12 = 8; 
     min12 = 0; 
    } 
    else 
    { 
     h12 = Integer.parseInt(h1.getText().toString()); 
     min12 = Integer.parseInt(min1.getText().toString()); 
    } 
    final SharedPreferences.Editor editor = sp.edit(); 
    editor.putInt("d11", d11); 
    editor.putInt("m11", m11); 
    editor.putInt("y11", y11); 
    editor.putInt("h12", h12); 
    editor.putInt("min12", min12); 
    editor.apply(); 
    Intent intent = new Intent(this, TEST3.class); 
    startService(new Intent(this, MyService.class)); 
    startActivity(intent); 
} 

回答

0

您正在循环中的编辑器中调用clear(),它实际上会删除所有存储的键值对。因此,最终只有最后一次迭代中存储的数据。

请参见: http://developer.android.com/reference/android/content/SharedPreferences.Editor.html

+0

我()后加清晰。它不工作,没有清除() –

+0

我不完全明白你想要做什么。您是否打算在任何特定时间仅保存单个年龄段数据,覆盖以前的数据,或者您是否期望有多个?你是否使用调试器检查过这种情况,并且每次迭代的数据确实不同? – logcat

+0

是的。我想用新的数据替换以前的数据。但是这不会发生 –