繁体   English   中英

使用Extras将值从片段传递到活动只会放置空值

[英]Passing values from fragment to activity using extras puts only null values

我正在尝试将字符串从片段传递到活动,而不是该片段的父对象。 活动从片段开始。 问题是,当我尝试获取字符串时,它返回null。 我不知道为什么。 代码如下:在片段内部:

    loginButton.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("ResourceType")
            @Override
            public void onClick(View v) {
                String email = emailText.getText().toString();
                String password = passwordText.getText().toString();
                String organizationName = orgSpinner.getSelectedItem().toString();
                System.out.println("username loges in for organization " + organizationName + " with email " + email + " and pass : " + password);
                Intent intent = new Intent(getActivity(), HomePageActivity.class);
                GetUserTask task = new GetUserTask();
                task.execute(1);
                Bundle extras = new Bundle();
                extras.putString("WELCOME_MSG", welcomeMsg);
                //intent.putExtra("WELCOME_MSG", welcomeMsg);
                System.out.println("!!"+ extras.getString("WELCOME_MSG"));
                intent.putExtras(extras);
                startActivity(intent);
            }
        });
        return view;
    }

在HomePageActivity中,我尝试读取字符串:

Bundle extras = getIntent().getExtras();
        if (extras != null) {
            //String msg = getIntent().getStringExtra("WELCOME_MSG");
            String msg = extras.getString("WELCOME_MSG");
            System.out.println("HEREEE : " + msg);
            welcomeMsg.setText(msg);
        } else {
            System.out.println("No extras");
        }

从两个sout调用(从片段和活动),我得到null。 我希望有人能弄清楚我为什么这样做。 谢谢。

我假设您将welcomeMsg设置为字符串。 您可以尝试以下方法:

Intent intent = new Intent(getActivity(), HomePageActivity.class);
intent.putExtra("WELCOME_MSG", welcomeMsg);

在HomePageActivity中:

String msg = getIntent().getStringExtra("WELCOME_MSG");

因此,事实证明,welcomeMsg是在onPostExecute()方法中设置的,但在其外部显示为null(因为有2个独立的线程)。 我创建了一个私有方法来创建HomePageActivity的意图,并将welcomeMsg作为Extra发送。 这样工作。 请参阅此问题,以获取有关为何在onPostExecute方法之外该字符串的值为null的详细信息: 未在AsyncTask的onPostExecute中设置Activity的实例变量,或如何将数据从AsyncTask返回到主UI线程 这是修改后的片段:

package com.example.iosif.ongmanagement.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;

import com.example.iosif.ongmanagement.R;
import com.example.iosif.ongmanagement.activity.HomePageActivity;
import com.example.iosif.ongmanagement.model.User;
import com.example.iosif.ongmanagement.repository.UserRepository;

public class LoginFragment extends Fragment {

    private static final String TAG = "LoginTabFragment";
    private Button loginButton;
    private EditText emailText;
    private EditText passwordText;
    private Spinner orgSpinner;
    private String welcomeMsg;

    public LoginFragment(){

    }
    @Nullable
    @Override
    public View onCreateView(@NonNull final LayoutInflater inflater, @Nullable final ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.login_fragment, container, false);
        loginButton = (Button) view.findViewById(R.id.loginButton);
        emailText = view.findViewById(R.id.etEmail);
        passwordText = (EditText) view.findViewById(R.id.etPassword);
        orgSpinner = (Spinner) view.findViewById(R.id.organizationsSpinner);

        loginButton.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("ResourceType")
            @Override
            public void onClick(View v) {
                String email = emailText.getText().toString();
                String password = passwordText.getText().toString();
                String organizationName = orgSpinner.getSelectedItem().toString();
                System.out.println("username loges in for organization " + organizationName + " with email " + email + " and pass : " + password);
                GetUserTask task = new GetUserTask();
                task.execute(1);

            }
        });
        return view;
    }

    /*
     * Starts the HomePageActivity and sends as Extra the value for the welcome message
     */
    private void startHomePage(String name){
        Bundle extras = new Bundle();
        extras.putString("WELCOME_MSG", welcomeMsg);
        System.out.println("!!"+ extras.getString("WELCOME_MSG"));
        Intent intent = new Intent(getActivity(), HomePageActivity.class);
        intent.putExtras(extras);
        startActivity(intent);
    }

    private class GetUserTask extends AsyncTask<Integer, Void, User> {

        @Override
        protected User doInBackground(Integer... integers) {
            UserRepository userRepository = new UserRepository();
            User userData = userRepository.getUser(integers[0]);
            return userData;
        }


        @Override
        protected void onPostExecute(User user) {
            welcomeMsg = "Welcome, " + user.getFirstName() + "!";
            System.out.println(welcomeMsg);
            startHomePage(welcomeMsg);
        }
    }

}

该功能不完整,因此请仅考虑与此问题相关的代码。 活动内部启动的代码保持不变。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM