2017-04-26 99 views
0

我正在将一些数据从片段保存到SharedPreference,并希望在其他片段中使用这些数据。但是我只想在SharedPreferences成功保存的情况下执行片段事务,否则其他片段将无法检索数据(因为使用这些SharedPreference值来检索数据)。如何知道Android SharedPreferences已成功保存?

我的代码:

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{ 

    ... ... ... ... ... ... ... ... ... 

    public void setSharedPref(String key, String val) { 
     SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE); 
     SharedPreferences.Editor editor = sharedPref.edit(); 
     editor.putString(key, val); 
     editor.commit(); 

    } 

    public String fetchSharedPref(String key) { 
     SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE); 
     String val = sharedPref.getString(key, Constant.SHARED_PREF_DEFAULT_MSN); 
     return val; 
    } 
} 

我如何可以肯定的是SharedPreferences成功保存?
有没有什么办法可以实现只有在SharedPreferences保存成功时才会调用的回调函数?

+1

据我所知,'Editor.commit'返回您需要的东西 –

+1

您可以通过Editor.commit() –

+0

Editor.commit() – Anu

回答

2

来自docs

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE); 
SharedPreferences.Editor editor = sharedPref.edit(); 
editor.putInt(getString(R.string.saved_high_score), newHighScore); 
editor.commit(); 

然后去检查commit()方法here

返回类型:布尔

说明:返回true,如果新的值成功写入到永久存储。

+1

来判断您的链接是俄语。请把它改成英文。 –

+0

完成。我认为这个页面还没有翻译。 –

1

形式Documentation

适用()

这立即将数据保存到内存中,并保存在一个单独的线程中的数据 盘。所以没有机会阻止主线程 (您的应用程序不会挂起)。

这是首选技术,但自从 姜饼(API 9,Android 2.3)以来才可用。

提交()

调用此然而将数据保存到文件中,这个过程是在 调用它,停止一切 ,直到保存完成的线程进行。 成功完成时返回true,失败时返回 。

使用commit()如果需要保存 数据,或者如果你是预姜饼设备开发成功的确认。 commit() 因为API 1

已经可以让你可以在editor.commit();

commit()回报true检查状态,如果保存作品,false否则。

1

找到解决方案之间

public boolean setSharedPref(String key, String val) { 
    SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE); 
    SharedPreferences.Editor editor = sharedPref.edit(); 
    editor.putString(key, val); 
    return editor.commit() 
} 

差异:)

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE); 
SharedPreferences.Editor editor = sharedPref.edit(); 
editor.putInt("Your Key", "Your value"); 
boolean savedOrNot = editor.commit(); 

if(savedOrNot){ 
// Successfully saved 
}else{ 
// Not saved 
} 
1

的editor.commit(将返回boolean值,它会让你知道,如果数据已保存。

如果你想分析保存在共享偏好和SQLite的所有数据,那么我会建议使用facebook stetho

其调试桥是Android,您可以查看所有的共享偏好数据和SQL数据库为调试。