簡體   English   中英

使用Bundle將活動中的字符串值發送到片段返回null

[英]Send string values from activity to fragment using Bundle returns null

我有一個底部導航欄,其中有4個菜單項可供用戶選擇。 根據他們選擇的內容,確定在我的框架中顯示哪個片段。 我可以加載片段並與之交互。 但是我還需要向每個片段發送一些字符串值,但無法弄清楚哪里出了問題。 當我啟動片段並嘗試使用getArguments()訪問值時,它總是返回null。 下面是我的代碼:

在unitactivity.java中,我遍歷代碼來選擇片段

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

public class UnitActivity extends AppCompatActivity {

    private BottomNavigationView bottomNavigation;
    private Fragment fragment;
    private FragmentManager fragmentManager;

    Boolean CheckEditText;
    ProgressDialog progressDialog;

    String ReadOnly;
    String LexaUser;
    String Password;
    String QA;
    String SearchValue;
    String UnitId;
    String UnitSize;
    String UnitStatus;

    Button UnitDetailsHeader;
    TextView UnitSizeText;
    TextView UnitStatusText;

    String finalResultUnitDetails;
    String HttpURLUnitDetails = "https://[path/to/server]/getUnitDetails.php";
    HashMap<String, String> hashMapUnitDetails = new HashMap<>();
    HttpParse httpParse = new HttpParse();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_units);

        Intent intent = getIntent();

        LexaUser = intent.getStringExtra("UserName");
        ReadOnly = intent.getStringExtra("ReadOnly");
        Password = intent.getStringExtra("Password");
        QA = intent.getStringExtra("QA");
        SearchValue = intent.getStringExtra("SearchInput");

        bottomNavigation = (BottomNavigationView)findViewById(R.id.bottom_navigation);
        bottomNavigation.inflateMenu(R.menu.bottom_menu);
        fragmentManager = getSupportFragmentManager();

        bottomNavigation.getMenu().getItem(0).setChecked(true);

        UnitDetailsHeader = findViewById(R.id.UnitDetailsViewTitle);
        UnitDetailsHeader.setText(SearchValue);

        UnitSizeText = findViewById(R.id.UnitSize);
        UnitStatusText = findViewById(R.id.UnitStatus);

        if (SearchValue.contains("-")) {
            getUnitDetails(SearchValue, LexaUser);
        } else {
            getSiblings();
        }

        bottomNavigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                int id = item.getItemId();

                switch (id){
                    case R.id.action_search:
                        fragment = new NewUnitStatusFragment();
                        break;
                    case R.id.action_cart:
                        fragment = new PendingUnitStatusFragment();
                        break;
                    case R.id.action_hot_deals:
                        fragment = new FinalUnitStatusFragment();
                        break;
                    case R.id.action_siblings:
                        fragment = new SiblingUnitFragment();
                        break;
                }

                Bundle connBundle = new Bundle();
                connBundle.putString("SearchValue", SearchValue);
                connBundle.putString("LexaUser", LexaUser);
                connBundle.putString("Password", Password);
                connBundle.putString("QA", QA);

                fragment.setArguments(connBundle);

                final FragmentTransaction transaction = fragmentManager.beginTransaction();
                transaction.replace(R.id.main_container, fragment).commit();

                return true;
            }
        });
    }
}

當我嘗試訪問片段中的值時:(onCreateView)

 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    Bundle bundle = getArguments();

    if (bundle != null) {
        SearchValue = bundle.getString("SearchValue");
        LexaUser = bundle.getString("LexaUser");
        Password = bundle.getString("Password");
    }

    View view = inflater.inflate(R.layout.fragment_newunitstatus, container, false);

    newUnitStatusContext = getContext();
    newUnitStatusActivity = getActivity();

    statusSpinner = view.findViewById(R.id.Status);
    generalCauseSpinner = view.findViewById(R.id.GeneralCause);
    newUSComment = view.findViewById(R.id.NewComment);
    newUnitStatusImage = view.findViewById(R.id.AddPhoto);
    addPhotoBtn = view.findViewById(R.id.AddPhotosLabel);
    addNewUnitStatus = view.findViewById(R.id.addBtnNewUnitStatus);

    ArrayAdapter<CharSequence> statusSpinnerAdapter = ArrayAdapter.createFromResource(newUnitStatusContext,
            R.array.new_unit_status_array, android.R.layout.simple_spinner_item);

    statusSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    statusSpinner.setAdapter(statusSpinnerAdapter);

    newUnitStatus = statusSpinner.getSelectedItem().toString();

    ArrayAdapter<CharSequence> generalCauseSpinnerAdapter = ArrayAdapter.createFromResource(newUnitStatusContext,
            R.array.status_general_cause_array, android.R.layout.simple_spinner_item);

    generalCauseSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    generalCauseSpinner.setAdapter(generalCauseSpinnerAdapter);

    generalCause = generalCauseSpinner.getSelectedItem().toString();

    addPhotoBtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
                startGallery();
        }
    });

    // Set a click listener for the text view
    addNewUnitStatus.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {

            newUnitStatus = statusSpinner.getSelectedItem().toString();
            generalCause = generalCauseSpinner.getSelectedItem().toString();
            newUnitStatusComment = newUSComment.getText().toString();

            Toast.makeText(newUnitStatusContext, "SV: " +SearchValue + " US: " + newUnitStatus + " GC: " + generalCause + " USC: " + newUnitStatusComment + " User: " + LexaUser + " PW: " + Password, Toast.LENGTH_LONG).show();

            //addNewUnitStatus(SearchValue, newUnitStatus, generalCause, newUnitStatusComment, newUnitStatusPhoto, LexaUser, Password);

        }
    });

    return view;
}

感謝所有幫助! 謝謝!

對於替代答案,您可以嘗試以下操作:

bottomNavigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                int id = item.getItemId();

                Bundle connBundle = new Bundle();
                connBundle.putString("SearchValue", SearchValue);
                connBundle.putString("LexaUser", LexaUser);
                connBundle.putString("Password", Password);
                connBundle.putString("QA", QA);

                switch (id){
                    case R.id.action_search:
                        fragment = new NewUnitStatusFragment(connBundle);
                        break;
                    case R.id.action_cart:
                        fragment = new PendingUnitStatusFragment(connBundle);
                        break;
                    case R.id.action_hot_deals:
                        fragment = new FinalUnitStatusFragment(connBundle);
                        break;
                    case R.id.action_siblings:
                        fragment = new SiblingUnitFragment(connBundle);
                        break;
                }

                final FragmentTransaction transaction = fragmentManager.beginTransaction();
                transaction.replace(R.id.main_container, fragment).commit();

                return true;
            }
        });

在Fragment中,您可以從傳遞的bundle參數中獲取參數,例如:

private Bundle bundle;

    public static FragmentA(Bundle bundle) {
        this.bundle = bundle;
    }

 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    if (bundle != null) {
        SearchValue = bundle.getString("SearchValue");
        LexaUser = bundle.getString("LexaUser");
        Password = bundle.getString("Password");
    }

    //etc...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM