简体   繁体   中英

Passing values from fragment to activity using extras puts only null values

I am trying to pass a String from a fragment to an activity, not the parent of this fragment. The activity is started from the fragment. The problem is that when I try to get the string it returns null. I couldn't figure out why. Here is the code: Inside the fragment:

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

And in the HomePageActivity I am trying to read the String:

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

From both sout calls (from fragment and from activity) I get null. I hope someone can figure why I this. Thank you.

I assume you set welcomeMsg as a string. You can try this:

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

in HomePageActivity:

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

So it turns out that welcomeMsg was set inside the onPostExecute() method but appeared as null outside of it (as there are 2 separate threads). I created a private method for creating the intent for the HomePageActivity and sending the welcomeMsg as an Extra. This way it works. Please refer to this question for details about why the value for the string was null outside of the onPostExecute method: Instance variable of Activity not being set in onPostExecute of AsyncTask or how to return data from AsyncTask to main UI thread . This is the modified Fragment:

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

}

The functionality is not complete so please take into consideration only the code relevant for this question. The code inside the activity started remains the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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