Android 在MainActivity中加载SharedReferences,并在辅助activity中更新
各位早上好, 我在创建第一个应用程序的过程中再次遇到问题。这次使用的是SharedReferences文件 我有两个活动必须使用相同的SharedReferences文件。第一个是主活动,第二个是数据的编辑布局 在MainActivity中,我使用以下方法将数据连接到PLC:Android 在MainActivity中加载SharedReferences,并在辅助activity中更新,android,android-activity,sharedpreferences,Android,Android Activity,Sharedpreferences,各位早上好, 我在创建第一个应用程序的过程中再次遇到问题。这次使用的是SharedReferences文件 我有两个活动必须使用相同的SharedReferences文件。第一个是主活动,第二个是数据的编辑布局 在MainActivity中,我使用以下方法将数据连接到PLC: //initialize the SharedPreferences variables for the PLC Data and Connection m_DataPLC = getSharedP
//initialize the SharedPreferences variables for the PLC Data and Connection
m_DataPLC = getSharedPreferences("CFTPreferences",CONTEXT_IGNORE_SECURITY);
m_DataEditorPLC = m_DataPLC.edit();
//Gets the number from the IP Address for the connection with the PLC
//As default, the system takes the value of a static string value
//This is when the SharedPreferences file is empty
m_IpAddress = getResources().getString(R.string.ip_Address);
m_NewIpAddress = m_DataPLC.getString("newIpAddress", m_NewIpAddress);
if(m_NewIpAddress == null)
{
m_DataEditorPLC.putString("newIpAddress", m_IpAddress.toString());
m_DataEditorPLC.commit();
m_OldIpAddress = m_NewIpAddress = m_IpAddress;
}
else
{
m_OldIpAddress = m_IpAddress = m_NewIpAddress;
}
//Start the connection with the PLC
m_Connection = new ModbusConnection(this,m_IpAddress);
inet = m_Connection.loginPLC();
在我的第二个活动中,我必须加载相同的数据并能够修改它。我首先要做的是登录到SharedReferences文件:
dataPLC = getSharedPreferences("CFTPreferences",CONTEXT_IGNORE_SECURITY);
dataEditorPLC = dataPLC.edit();
然后,我用按钮的点击动作进行书写:
public void setIPAddress()
{
if (!newIpAddress.equals(etIPAddress.getText().toString()))
{
dataEditorPLC.putString("oldIpAdd",ipAddress.toString());
dataEditorPLC.putString("newIpAdd",etIPAddress.getText().toString());
dataEditorPLC.commit();
}
}
我不知道我是否在错误地调用同一个文件两次,或者如果我必须做一些额外的事情来修复这个文件。它看起来好像进行了更新,但没有刷新MainActivity。如果有人有类似的问题,我会非常感谢你的帮助
非常感谢 我认为您正在访问第一个活动的
onCreate()
中共享首选项的值。那将是你的问题。因为当您从第二个活动返回到第一个活动时,不会调用您的onCreate()
,而是调用onResume()
。因此,更好的做法是将访问SharedReferences
值的代码移动到单独的函数中,并在onCreate()
和onResume()中调用此函数
例如
public void getSharedPrefernces() {
m_DataPLC = getSharedPreferences("CFTPreferences",CONTEXT_IGNORE_SECURITY);
m_NewIpAddress = m_DataPLC.getString("newIpAddress", m_NewIpAddress);
}
希望这有帮助。。!!干杯…都德没问题,不适合小妞;)。是的,你是对的,我改变了它,并做了一个新的方法,它在所有事件(启动、创建、恢复、暂停和重新启动)中都被调用。我还在次要活动中发现了一个错误,该错误与代码内部的编辑文本有关。我用这个解决了我的问题。谢谢!!!哈..哈。。在回答之前,我没有看你的名字或任何东西。随便放吧。。对不起,女士……:)