how can i read a SharedPreferences from another ac

2019-09-04 01:51发布

问题:

    sharedPreferences = getSharedPreferences("HTTP_HELPER_PREFS", Context.MODE_PRIVATE);
    editor = sharedPreferences.edit();

    // get the IP address and port number from the last time the user used the app,
    // put an empty string "" is this is the first time.
    editTextIPAddress.setText(sharedPreferences.getString(PREF_IP, ""));
    editTextPortNumber.setText(sharedPreferences.getString(PREF_PORT, ""));
    confbutton.setOnClickListener(this);

}


@Override
public void onClick(View v) {
    // get the ip address
    String ipAddress = editTextIPAddress.getText().toString().trim();
    // get the port number
    String portNumber = editTextPortNumber.getText().toString().trim();

    editor.putString(PREF_IP, ipAddress); // 
    editor.putString(PREF_PORT, portNumber); 
    editor.commit(); 
    onBackPressed();

that's my code i created a second Activity to get the ip adresse and the port number now i need to read that SharedPreferencesin the main activity

回答1:

Something like this

SharedPreferences prefs = getSharedPreferences("HTTP_HELPER_PREFS", Context.MODE_PRIVATE);
String ipAddress = prefs.getString(PREF_IP, ipAddress); 
String portNumber = prefs.getString(PREF_PORT, portNumber);