Load SharedPreferences in MainActivity and Update

2019-09-05 02:21发布

问题:

Good morning everyone,

I'm having problems again in my proccess to create my first app. This time with the SharedPreferences file.

I have 2 activities that must use the same SharedPreferences file. The first one is the MainActivity and the second one an edit layout for the data.

In the MainActivity I have the following method where I use the data to connect to a PLC:

        //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();

In my second activity, I have to load the same data and be able to modify it. What I do first is the login to the SharedPreferencesFile:

dataPLC = getSharedPreferences("CFTPreferences",CONTEXT_IGNORE_SECURITY);
dataEditorPLC = dataPLC.edit();

Then I do the writing with a click action of a button:

    public void setIPAddress()
{
    if (!newIpAddress.equals(etIPAddress.getText().toString()))
    {
        dataEditorPLC.putString("oldIpAdd",ipAddress.toString());
        dataEditorPLC.putString("newIpAdd",etIPAddress.getText().toString());
        dataEditorPLC.commit();
    }
}

I dunno if I'm doing wrong calling the same file twice or if I have to do something extra to mend this. It looks like it does the update, but it doesn't refresh the MainActivity. If someone had some sort of the same problem, I would appreciate the help on this one!!!.

Many thanks in advance!!!

回答1:

I think you are accessing the value of Shared Preferences in onCreate() of first Activity. That will be your problem. Beacuse when you come back from second activity to first activity, your onCreate() is not called, instead onResume() is called. So the better thing to do is move the code where you access SharedPreferences value to a seperate function and call this function in both onCreate() and onResume().

for e.g.

public void getSharedPrefernces() {
  m_DataPLC = getSharedPreferences("CFTPreferences",CONTEXT_IGNORE_SECURITY);
  m_NewIpAddress = m_DataPLC.getString("newIpAddress", m_NewIpAddress);
}

Hope this Helps..!! Cheers...