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

时间:2019-03-04 10:38:18

标签: android android-activity arguments fragment

我正在尝试将字符串从片段传递到活动,而不是该片段的父对象。活动从片段开始。问题是,当我尝试获取字符串时,它返回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。 我希望有人能弄清楚我为什么这样做。谢谢。

2 个答案:

答案 0 :(得分:0)

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

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

在HomePageActivity中:

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

答案 1 :(得分:0)

因此,事实证明,welcomeMsg是在onPostExecute()方法中设置的,但在其外部显示为null(因为有2个独立的线程)。我创建了一个私有方法来创建HomePageActivity的意图,并将welcomeMsg作为Extra发送。这样工作。有关在onPostExecute方法Instance variable of Activity not being set in onPostExecute of AsyncTask or how to return data from AsyncTask to main UI thread之外字符串值为何为null的详细信息,请参考此问题。这是修改后的片段:

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);
        }
    }

}

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