java - Android:从随机 fragment/Activity 访问用户登录数据

标签 java android android-fragments

我正在开发一个应用程序,我正在尝试(但失败了)在一系列 Activity 和 fragment 之间传递数据。就目前而言,我的登录/注册 Activity 可以完美运行,并将用户的凭据保存在在线 MySqli 数据库中,当用户登录时,一些凭据将传递给主要 Activity ,其中包含一个显示 fragment 的容器。

我使用 bundle 将数据从这个主要 Activity 传递到它的一个 fragment 没有遇到任何问题,但是,我现在有几个子页面从按以下顺序访问的配置文件 fragment 链接:MainScreen - ProfileFragment - EditProfileFragment - ChangeUserName(弹出 Activity )。 EditProfile frag 也有一个 changeUserPicture 按钮,但它将使用与名称更改相同的方法。

我需要将用户的凭据从 MainScreen 传递到 ChangeUserName Activity 。我试过使用一系列 bundle ,这些 bundle 在创建 Activity/fragment 时传递字符串,但无法正常工作。

我正在尝试使用一个接口(interface)来传递这些数据,但我无法弄清楚如何正确地做到这一点,我们将不胜感激任何对此的帮助!

相关 Activity 和 fragment 的代码如下:

主屏幕:

public class MainScreen extends FragmentActivity implements View.OnClickListener {

ImageButton homeButton, searchButton, messageButton, contactsButton;
ImageView Luna;
ConstraintLayout homeView, searchView, lunaView, inboxView, contactsView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);

    final ImageButton homeButton = (ImageButton) findViewById(R.id.bottom_home);
    final ImageButton searchButton = (ImageButton) findViewById(R.id.bottom_search);
    final ImageView Luna = (ImageView) findViewById(R.id.bottom_luna);
    final ImageButton messageButton = (ImageButton) findViewById(R.id.bottom_messages);
    final ImageButton contactsButton = (ImageButton) findViewById(R.id.bottom_contacts);

    final ConstraintLayout homeView = (ConstraintLayout) findViewById(R.id.home_section);
    final ConstraintLayout searchView = (ConstraintLayout) findViewById(R.id.search_section);
    final ConstraintLayout lunaView = (ConstraintLayout) findViewById(R.id.luna_section);
    final ConstraintLayout inboxView = (ConstraintLayout) findViewById(R.id.inbox_section);
    final ConstraintLayout contactsView = (ConstraintLayout) findViewById(R.id.contacts_section);

    final ImageButton profileButton = (ImageButton) findViewById(R.id.profile_button);

    final TextView titleBarText = (TextView) findViewById(R.id.titleText);

    homeView.setOnClickListener(this);
    searchView.setOnClickListener(this);
    lunaView.setOnClickListener(this);
    inboxView.setOnClickListener(this);
    contactsView.setOnClickListener(this);

    if (findViewById(R.id.container) != null) {

        if (savedInstanceState != null) {
            return;
        }

        HomeFragment firstFragment = new HomeFragment();
        firstFragment.setArguments(getIntent().getExtras());
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, firstFragment)
                .commit();
        titleBarText.setText("Home");

    }


    /*  This is the old toolbar button code. Keep just in case

    homeView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            FragmentManager fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.replace(R.id.container, new HomeFragment());
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
        }
    });

    */
    Intent intent = getIntent();
    final Integer user_id = intent.getIntExtra("user_id", 0);
    final String name = intent.getStringExtra("name");
    final String email = intent.getStringExtra("email");

    profileButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Fragment profileFragment = new ProfileFragment();

            Bundle profileBundle = new Bundle();
            profileBundle.putInt("idKey", user_id);
            profileBundle.putString("nameKey", name);
            profileBundle.putString("emailKey", email);

            profileFragment.setArguments(profileBundle);

            FragmentManager fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.replace(R.id.container, profileFragment);
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
        }
    });

}

@Override
public void onClick(View view) {
    Fragment fragment = new Fragment();
    switch (view.getId()){
        case R.id.home_section:
            fragment = new HomeFragment();

            break;
        case R.id.search_section:
            fragment = new SearchFragment();

            break;
        case R.id.luna_section:
            fragment = new LunaFragment();

            break;
        case R.id.inbox_section:
            fragment = new MessageFragment();

             break;
        case R.id.contacts_section:
            fragment = new ContactsFragment();

            break;
    }
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.container, fragment);
    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.commit();
}

@Override
public void onBackPressed()
{
    if(getFragmentManager().getBackStackEntryCount() > 0)
        getFragmentManager().popBackStack();
    else
        super.onBackPressed();
}

个人资料 fragment :

public class ProfileFragment extends Fragment{

MainScreen activity = (MainScreen) getActivity();

public ProfileFragment() {
}

    @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_profile, container, false);
        final TextView userName = (TextView) view.findViewById(R.id.userFullName);
        final TextView userWorkplace = (TextView) view.findViewById(R.id.workplace);

        final Button workspaceButton = (Button) view.findViewById(R.id.workspaceButton);
        final Button socialButton = (Button) view.findViewById(R.id.socialspaceButton);
        final Button editProfileButton = (Button) view.findViewById(R.id.editProfileButton);
        final Button preferencesButton = (Button) view.findViewById(R.id.preferencesButton);
        final Button appSettingsButton = (Button) view.findViewById(R.id.appSettingsButton);

        Bundle interfaceBundle = this.getArguments();


        if (interfaceBundle != null) {
            String nameBundle = getArguments().getString("nameKey"); //Get pass data with its key value
            userName.setText(nameBundle);
        } else {
            userName.setText("No Username Found");
        }

        editProfileButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                FragmentManager fragmentManager = getFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.replace(R.id.container, new EditProfileFragment());
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.commit();
            }
        });

    return view;
}





    @Override
public void onResume() {
    super.onResume();
    TextView title = (TextView) getActivity().findViewById(R.id.titleText);
    title.setText("Profile");

    ImageButton icon = (ImageButton) getActivity().findViewById(R.id.profile_button);
    icon.setColorFilter(getResources().getColor(R.color.coolWhite));
}

@Override
public void onPause() {
    super.onPause();
    ImageButton icon = (ImageButton) getActivity().findViewById(R.id.profile_button);
    icon.setColorFilter(getResources().getColor(R.color.slightGrey));
}

EditProfileFragment(目前只包含两个按钮):

public class EditProfileFragment extends Fragment {


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_edit_profile, container, false);

    Button editName = (Button) view.findViewById(R.id.changeUsernameButton);
    Button editPicture = (Button) view.findViewById(R.id.changeProfilePictureButton);


    editName.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {


            startActivity(new Intent(getActivity(), PopupNameChange.class));
        }
    });

    return view;
}

@Override
public void onResume() {
    super.onResume();
    TextView title = (TextView) getActivity().findViewById(R.id.titleText);
    title.setText("Edit Profile");


    ImageButton icon = (ImageButton) getActivity().findViewById(R.id.profile_button);
    icon.setColorFilter(getResources().getColor(R.color.coolWhite));

}

@Override
public void onPause() {
    super.onPause();
    ImageButton icon = (ImageButton) getActivity().findViewById(R.id.profile_button);
    icon.setColorFilter(getResources().getColor(R.color.slightGrey));

}

PopupNameChange(打开以更改用户名的 Activity。它会在屏幕中央的 fragment 上方弹出,并且不会覆盖之前的 View ):

public class PopupNameChange extends Activity implements PracticeInterface{

String userName;

public void onFragmentInteraction(String userDataString) {
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.pop_up_change_name);

    TextView userNameCurrent = (TextView) findViewById(R.id.tvCurrentName);

    //I want to pass the user's name to this activity to change the string of userNameCurrent
    userNameCurrent.setText(userName);

    DisplayMetrics dm = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm);


    int width = dm.widthPixels;
    int height = dm.heightPixels;

    getWindow().setLayout(ConstraintLayout.LayoutParams.WRAP_CONTENT, ConstraintLayout.LayoutParams.WRAP_CONTENT);

    getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

}

最佳答案

因此,实现目标的最快方法是使用 SharedPreferences。谷歌链接 site .基本上,当您在主 Activity 中获取数据时,将该数据插入到 SharedPreferences 中,如下所示:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("userName", userName);
editor.commit();

然后在您的 ChangeUserName 中获取当前用户名:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
String userName = sharedPref.getString("userName", defaultValue);

我也应该警告你。不要在 SharedPreferences 中保存敏感数据。拥有 root 权限的手机用户可以轻松地从 SharedPreferences 获取数据。

关于java - Android:从随机 fragment/Activity 访问用户登录数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45639016/

相关文章:

java - 欢迎 Activity 代码放置在哪里

android - 使用按钮在选项卡之间切换

android - 如何使用嵌套 fragment (Android 4.2)在 ViewPager 中添加 fragment

android - Android 4.2.x 上的 "Error Inflating Class Fragment"

Java:如何让线程等待用户的IO然后继续

java - 如何使用 Chrome webdriver 缩小页面

java - 在端口 80 上尝试 https 时 tomcat8 处于 100% cpu

java - Tomcat 中的严格引号转义

java - 在 Java 中检查空值

java - Android - 无法通过 fragment 中的 Intent 启动 Activity