无法从SharedPreferences检索数据?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了无法从SharedPreferences检索数据?相关的知识,希望对你有一定的参考价值。
我有这个活动::
public class MainActivity extends AppCompatActivity
boolean networkState;
public View layout;
TextView Data1Text, Data2Text;
String Data1, Data2;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LayoutInflater inflater = getLayoutInflater();
layout = inflater.inflate(R.layout.toast,
(ViewGroup) findViewById(R.id.toast_layout_root));
Data1Text = (TextView) findViewById(R.id.data1);
Data2Text = (TextView) findViewById(R.id.data2);
ConnectivityManager cm =
(ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
if(isConnected)
new doIt().execute();
networkState = true;
else
Toast.makeText(this, "NO CONNECTION", Toast.LENGTH_SHORT).show();
networkState = false;
public class doIt extends AsyncTask<Void, Void, Void>
ProgressDialog mProgressDialog;
@Override
protected Void doInBackground(Void... params)
try
//Here I retreive data from my website and it works like magic
// I get Data1 and Data2 values from it.
catch (IOException e)
e.printStackTrace();
return null;
@Override
protected void onPostExecute(Void aVoid)
super.onPostExecute(aVoid);
Data1Text.setText(Data1);
Data2Text.setText(Data2);
mProgressDialog.dismiss();
@Override
protected void onPreExecute()
super.onPreExecute();
mProgressDialog = new ProgressDialog(MainActivity.this);
//mProgressDialog.setTitle("");
mProgressDialog.setMessage("Update in Progress..");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
@Override
public void onPause()
super.onPause();
SharedPreferences settings;
SharedPreferences.Editor editor;
settings = this.getSharedPreferences("MYTAGI", Context.MODE_PRIVATE); //1
editor = settings.edit();
editor.putString("data1", Data1);
editor.putString("data2", Data2);
editor.commit();
如何从我的共享首选项中再次检索数据?我是在onCreate的最后一行做的,但它不起作用......
保存数据似乎有效,但检索数据不正确..请帮助
答案
这是我如何做到的。尝试使用以下方法保存数据
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
editor.putString("data1", Data1);
editor.putString("data2", Data2);
editor.commit();
得到它:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String Data1 = preferences.getString("data1", "Default value for data1");
String Data2 = preferences.getString("data2", "Default value for data2");
以上是关于无法从SharedPreferences检索数据?的主要内容,如果未能解决你的问题,请参考以下文章
尝试使用 SharedPreferences 存储和检索应用程序数据,但它没有返回所需的数据
尝试从 sharedPreferences 检索地图时出现颤振错误
我可以使用一个按钮将数据保存在 sharedPreferences 中,然后使用另一个按钮来检索它吗?