skip to Main Content

Error : Attempt to invoke virtual method ‘java.lang.String android.os.Bundle.getString(java.lang.String)’ on a null object reference

I Am Making a Search Button that will send the search Query to fragment And From there it loads the URL with a search query

for eg if I search pen in the search bar. the query will send using bundle and will load in webview in another fragment.

Activity code
    firstFragmentBtn = findViewById(R.id.fragment1btn);
    secondFragmentBtn = findViewById(R.id.fragment2btn);

     searchView = findViewById(R.id.edit_query);
  

  searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
      @Override
      public boolean onQueryTextSubmit(String query) {

          Bundle bundle = new Bundle();
          bundle.putString("sendData", searchView.getQuery().toString());

          fragment1 fragobj = new fragment1();
          fragobj.setArguments(bundle);
          replaceFragment(new fragment1());
          return true;
      }

      @Override
      public boolean onQueryTextChange(String newText) {
          return false;
      }
  });

    firstFragmentBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            replaceFragment(new fragment1());

        }
    });

    secondFragmentBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            replaceFragment(new fragment2());

        }
    });

fragment code

  WebView webView = view.findViewById(R.id.webView);
    webView.getSettings().setJavaScriptEnabled(true);

    Bundle bundle = getArguments();
  // error in this line
   String  message = bundle.getString("SendData"); ????

    webView.loadUrl("https://google.com/search?q=" + message);




    return view;

2

Answers


  1. In your fragment inside onCreateView()

    if(getArguments().getString("sendData") != null)
    {
        String message = getArguments().getString("sendData");
    
    .
    .
    .
    
    Login or Signup to reply.
  2. in putString("sendData") whereas in getString it is "SendData" put same in both either sendData or SendData.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search