общие предпочтения между действиями
Этот вопрос похож на другие вопросы, касающиеся общих предпочтений, но я не знаю, как именно его использовать между различными видами деятельности? Пожалуйста, предоставьте полный файл активности, если это возможно, а не несколько строк кода, так как я нуб в этой области!
У меня есть два занятия. один - userprofile, а другой - edituserprofile. Что бы пользователь ни редактировал в edituserprofile, оно должно отображаться в активности userprofile, как только пользователь нажмет кнопку «Сохранить изображение» на панели приложения edituserprofile. sharedpreferences отлично работает в edituserprofile, где пользователь может видеть введенные данные, а также может изменять их, как они редактируют текстовое представление. Тем не менее, я не могу применить ту же логику к профилю пользователя. Когда я нажимаю кнопку «Сохранить» в edituserprofile, я перехожу в userprofile, и я вижу изменения, внесенные в edituserprofile, но как только я выхожу из userprofile и перезапускаю его, данные очищаются в userprofile, но не из edituserprofile! я хочу, чтобы userprofile сохранял, отображал данные из edituserprofile, даже выход пользователя и перезапускал приложение!
Ниже приведена активность пользователя.
package com.example.android.coffeeshop6menus;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class UserProfile extends AppCompatActivity {
public static final int Edit_Profile = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile);
Toolbar userProfileToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(userProfileToolbar);
SharedPreferences sharedpreferences = getPreferences(MODE_PRIVATE);
displayMessage(sharedpreferences.getString("nameKey", ""));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.userprofile_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_editProfile:
Intent userProfileIntent = new Intent(UserProfile.this, EditUserProfile.class);
startActivityForResult(userProfileIntent, Edit_Profile);
}
return true;
}
// Call Back method to get the Message form other Activity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case Edit_Profile:
if (resultCode == RESULT_OK) {
String name = data.getStringExtra("");
displayMessage(name);
}
break;
}
}
public void displayMessage(String message) {
TextView usernameTextView = (TextView) findViewById(R.id.importProfile);
usernameTextView.setText(message);
}
}
Ниже приведено описание деятельности edituserprofile!
package com.example.android.coffeeshop6menus;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class EditUserProfile extends AppCompatActivity {
private CoordinatorLayout coordinatorLayout;
public static final String Name = "nameKey";
SharedPreferences sharedpreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_user_profile);
Toolbar userProfileToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(userProfileToolbar);
TextView usernameTextView = (TextView) findViewById(R.id.username);
sharedpreferences = getSharedPreferences(Name, Context.MODE_PRIVATE);
if (sharedpreferences.contains(Name)) {
usernameTextView.setText(sharedpreferences.getString(Name, ""));
}
coordinatorLayout = (CoordinatorLayout) findViewById(R.id
.coordinatorLayout);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.editprofile_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_save:
TextView usernameTextView = (TextView) findViewById(R.id.username);
String usernameString = usernameTextView.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, usernameString);
editor.apply();
Snackbar snackbar = Snackbar
.make(coordinatorLayout, "Saved!", Snackbar.LENGTH_LONG);
snackbar.show();
Intent userProfileIntent = new Intent(EditUserProfile.this, UserProfile.class);
userProfileIntent.putExtra("", usernameString);
setResult(RESULT_OK, userProfileIntent);
finish();
}
return true;
}
}
Ниже приведен файл userprofile.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.android.coffeeshop6menus.UserProfile">
<include
layout="@layout/toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:text="Name"
android:textSize="20dp" />
<TextView
android:id="@+id/importProfile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:text="@string/userNameImport"
android:textSize="20dp" />
</LinearLayout>
</ScrollView>
Ниже приведен XML-файл edituserprofile:
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.android.coffeeshop6menus.UserProfile">
<include
layout="@layout/toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:text="User Profile"
android:textSize="20dp" />
</LinearLayout>
<EditText
android:id="@+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:cursorVisible="true"
android:hint="@string/EditTextHint"
android:inputType="textNoSuggestions" />
<EditText
android:id="@+id/usercontact"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:cursorVisible="true"
android:hint="@string/usercontactHint"
android:inputType="textNoSuggestions" />
<EditText
android:id="@+id/useremail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:cursorVisible="true"
android:hint="@string/useremailHint"
android:inputType="textEmailAddress" />
</LinearLayout>
</ScrollView>
Пожалуйста, помогите!