2012-03-09 34 views
1

我想通過使用developer.android.com SharedPreferences中的代碼來測試SharedPreferences。自從他們說onStop "may never be called"後,我試圖稍微改變它。問題是,即使覆蓋的第一行是super.onPause(),onPause也會給我這個奇怪的錯誤。onPause():SuperNotCalledException即使super.onPause()存在

03-09 14:41:00.883: E/AndroidRuntime(394): android.app.SuperNotCalledException: Activity {com.mobinoob.saveinfo/com.mobinoob.saveinfo.SaveInfoActivity} did not call through to super.onPause() 

下面是代碼示例:

public class SaveInfoActivity extends Activity { 
/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    addListener(); 
    loadText(); 
    textSaved = ""; 
    created = true; 
} 

private boolean created = false; 

private void addListener() { 
    EditText et = (EditText) findViewById(R.id.editText1); 
    et.addTextChangedListener(new TextWatcher() { 

     public void afterTextChanged(Editable s) { 
      textSaved = s.toString(); 
      System.out.println("text:" + textSaved); 
     } 

     public void beforeTextChanged(CharSequence s, int start, int count, 
       int after) { 
     } 

     public void onTextChanged(CharSequence s, int start, int before, 
       int count) { 
     } 
    }); 

} 

private static String fileName = "savedInfo.txt"; 
private static String propertyName = "text"; 
private String textSaved; 

@Override 
protected void onPause() {}{ 
    super.onPause(); 
    if (created) { 
     saveText(); 
    } 
} 
private void loadText() { 
    SharedPreferences settings = getSharedPreferences(fileName, MODE_PRIVATE); 
    if (settings == null) 
     return; 
    String result = settings.getString(propertyName, ""); 
    setText(result); 
} 

private void saveText() { 
    System.out.println("saving"); 
    SharedPreferences settings = getSharedPreferences(fileName, 0); 
    SharedPreferences.Editor editor = settings.edit(); 
    editor.putString(propertyName, textSaved); 
    editor.commit(); 

} 
private void setText(String result) { 
    TextView tv = (TextView) findViewById(R.id.textView1); 
    tv.setText(result); 
    System.out.println("restore" + result); 
} 

任何想法,我失去了一些東西?還要注意,因爲onPause()也是我第一次啓動應用程序,所以需要if(創建)。

回答

5
protected void onPause() {}{ 

你在這裏有一對額外的花括號,使它看起來像一個空的函數。

+1

10分鐘註冊併發布問題和什麼? 10秒,發現一個愚蠢的錯字。:)我讀了幾次,沒有看到。謝謝! – maugch 2012-03-09 14:16:03

1

看起來像一個簡單的錯字給我...注意在onPause()後面的空括號。這可能會被檢測爲您的方法。

@Override 
protected void onPause() {}{ 
    super.onPause(); 
    if (created) { 
     saveText(); 
    } 
} 
+0

謝謝! (我想這是檢查代碼的更多目光的力量。)Eclipse也不警告我,這也很奇怪。 – maugch 2012-03-09 14:17:46

+1

它當然不能警告你有一個空的函數,當然......但我很驚訝它並沒有抱怨在某個地方的匿名函數! – JTeagle 2012-03-09 14:22:08

+0

我再次檢查。根本沒有警告。 – maugch 2012-03-09 14:24:43

相關問題