1

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.

  • it is not clear where you have defined `welcomeMsg` and where you have assigned value to it. Please add those code too. – Akram Mar 04 '19 at 10:46
  • Same thing found here `welcomeMsg` is not found here. Have you tried to debug app and check what values assigned to `welcomeMsg`? – Nilesh Panchal Mar 04 '19 at 10:56
  • Sorry, I deleted a line by mistake. welcomeMsg is declared as a private instance variable and is assigned as: welcomeMsg = findViewById(R.id.welcomeTextView); I have to mention that welcomeMsg is set after the setText call. – Show-me-the-code Mar 04 '19 at 11:57
  • Inside the fragment welcomeMsg is a private String and is set in a private class:`code` private class GetUserTask extends AsyncTask { @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() + "!"; } } – Show-me-the-code Mar 04 '19 at 12:10
  • You are using AsyncTask which is running in background thread, before value assigning to " welcomeMsg = "Welcome, " + user.getFirstName() + "!"; }" null value get put in bundle extras and another activity starts, so it get null value at another activity. – Zumbarlal Saindane Mar 04 '19 at 12:31
  • @zums Thank you. I just figured it out. I posted the answer below. I am new at Android so I'm learning as I go :) – Show-me-the-code Mar 04 '19 at 12:33

2 Answers2

0

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");
twenk11k
  • 557
  • 5
  • 17
  • I deleted a line by mistake. welcomeMsg is a TextView declared as a private instance variable. The problem is with putExtra I believe, as the value return from getExtras().getString() is null. – Show-me-the-code Mar 04 '19 at 12:01
0

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.