confbutton.setOnClickListener(
new View.OnClickListener() {
@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();
// save the IP address and port for the next time the app is used
editor.putString(PREF_IP, ipAddress); // set the ip address value to save
editor.putString(PREF_PORT, portNumber); // set the port number to save
editor.commit(); // save the IP and PORT
// 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, ""));
onBackPressed();}
});
我在设置活动中写了这个来获取IP地址和端口号。然后我使用以下方法调用主活动中的SharedPreferences:
sharedPreferences = getSharedPreferences("HTTP_HELPER_PREFS", Context.MODE_PRIVATE);
ipAddress = sharedPreferences.getString(PREF_IP, ipAddress);
portNumber = sharedPreferences.getString(PREF_PORT, portNumber);
displayText.setText(ipAddress);
我用displayText.setText(ipAddress)
看看我是否得到它。它工作但它只给我最后一个SharedPreferences
如果我在设置活动中更改它并降低到主要活动它不会改变,直到我杀死应用程序并再次重新打开它。
我试着这样做:
SettingsButton.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent2 = new Intent("com.example.ela_hidri.myremote.SettingsActivity");
startActivity(intent2);
sharedPreferences = getSharedPreferences("HTTP_HELPER_PREFS", Context.MODE_PRIVATE);
ipAddress = sharedPreferences.getString(PREF_IP, ipAddress);
portNumber = sharedPreferences.getString(PREF_PORT, portNumber);
displayText.setText(ipAddress);
}});
它确实会更改文字,但仅当我点击按钮Settings
时。
我希望每次在“设置活动”中更改它时都要更改它。
答案 0 :(得分:1)
您需要使用主要活动的onResume
功能。当您从“设置活动”更改“IP地址”和“端口”时 - 您将其保存在SharedPreferences中 - 对吗?
现在,当您返回MainActivity
时,您需要将以下代码放在onResume
的{{1}}函数中。
MainActivity
希望这会为你做到这一点。