簡體   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