Click here to Skip to main content
15,880,392 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a fragment hosted by an activity. The fragment makes use of my Activity's EditText(uses view from Activity).
and also uses the fragment's textview to get some data searched on the EditText.

My Problem is how do i call the EditText and textviews well? I tried calling both on the same onCreateView at first
but i got this error at runtime:
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.tex.lightweatherforecast, PID: 4762
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.tex.lightweatherforecast/com.tex.lightweatherforecast.Activity.HomeActivity}: android.view.InflateException: Binary XML file line #21: Binary XML file line #21: Error inflating class fragment
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3013)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3148)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1861)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6819)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:497)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:912)
     Caused by: android.view.InflateException: Binary XML file line #21: Binary XML file line #21: Error inflating class fragment
     Caused by: android.view.InflateException: Binary XML file line #21: Error inflating class fragment
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
        at com.tex.lightweatherforecast.FirstFragment.onCreateView(FirstFragment.java:97)
        at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2952)
        at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:518)
        at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:282)
        at androidx.fragment.app.FragmentStore.moveToExpectedState(FragmentStore.java:112)
        at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1647)
        at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:3124)
        at androidx.fragment.app.FragmentManager.dispatchViewCreated(FragmentManager.java:3061)
        at androidx.fragment.app.Fragment.performViewCreated(Fragment.java:2977)
        at androidx.fragment.app.FragmentStateManager.ensureInflatedView(FragmentStateManager.java:392)
        at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:281)
        at androidx.fragment.app.FragmentLayoutInflaterFactory.onCreateView(FragmentLayoutInflaterFactory.java:140)
        at androidx.fragment.app.FragmentController.onCreateView(FragmentController.java:135)
        at androidx.fragment.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:319)
        at androidx.fragment.app.FragmentActivity.onCreateView(FragmentActivity.java:298)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:791)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:880)
        at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:841)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
        at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:696)
        at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:170)
        at com.tex.lightweatherforecast.Activity.HomeActivity.onCreate(HomeActivity.java:43)
        at android.app.Activity.performCreate(Activity.java:7136)
        at android.app.Activity.performCreate(Activity.java:7127)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2990)
E/AndroidRuntime:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3148)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1861)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6819)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:497)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:912)


I need help on how to call the Activity and the fragment's view well in my project.
Here is my code:
FirstFragment.java:
Java
  1  public class FirstFragment extends Fragment {
  2      // User current time, current temperature, current condition, sunrise, sunset, temperature, pressure, humidity, wind_speed, visibility, clouds
  3      TextView current_temp, current_output, rise_time, set_time, temp_out, Press_out, Humid_out, Ws_out, Visi_out, Cloud_out;
  4      // TODO: Rename parameter arguments, choose names that match
  5  // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
  6      private static final String ARG_PARAM1 = "param1";
  7      private static final String ARG_PARAM2 = "param2";
  8  
  9      // TODO: Rename and change types of parameters
 10      private String mParam1;
 11      private String mParam2;
 12  
 13      public FirstFragment() {
 14          // Required empty public constructor
 15      }
 16  
 17      /**
 18       * Use this factory method to create a new instance of
 19       * this fragment using the provided parameters.
 20       *
 21       * @param param1 Parameter 1.
 22       * @param param2 Parameter 2.
 23       * @return A new instance of fragment SecondFragment.
 24       */
 25  // TODO: Rename and change types and number of parameters
 26      public static FirstFragment newInstance(String param1, String param2) {
 27          FirstFragment fragment = new FirstFragment();
 28          Bundle args = new Bundle();
 29          args.putString(ARG_PARAM1, param1);
 30          args.putString(ARG_PARAM2, param2);
 31          fragment.setArguments(args);
 32          return fragment;
 33      }
 34  
 35      @Override
 36      public void onCreate(Bundle savedInstanceState) {
 37          super.onCreate(savedInstanceState);
 38          if (getArguments() != null) {
 39              mParam1 = getArguments().getString(ARG_PARAM1);
 40              mParam2 = getArguments().getString(ARG_PARAM2);
 41  
 42          }
 43      }
 44  
 45      @Override
 46      public View onCreateView(LayoutInflater inflater, ViewGroup container,
 47                               Bundle savedInstanceState) {
 48          // Inflate the layout for this fragment
 49          View rootView = inflater.inflate(R.layout.fragment_first, container, false);
 50          current_temp = rootView.findViewById(R.id.textView10);
 51          current_output = rootView.findViewById(R.id.textView11);
 52          rise_time = rootView.findViewById(R.id.textView25);
 53          set_time = rootView.findViewById(R.id.textView26);
 54          temp_out = rootView.findViewById(R.id.textView28);
 55          Press_out = rootView.findViewById(R.id.textView29);
 56          Humid_out = rootView.findViewById(R.id.textView30);
 57          Ws_out = rootView.findViewById(R.id.textView33);
 58          Visi_out = rootView.findViewById(R.id.textView34);
 59          Cloud_out = rootView.findViewById(R.id.textView35);
 60          EditText textfield = getActivity().findViewById(R.id.textfield);
 61          getWeatherData(textfield.getText().toString().trim());
 62          return rootView;
 63      }
 64  
 65      private void getWeatherData(String name) {
 66  
 67          ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);
 68  
 69          Call<Example> call = apiInterface.getWeatherData(name);
 70  
 71          call.enqueue(new Callback<Example>() {
 72              @Override
 73              public void onResponse(@NotNull Call<Example> call, @NotNull Response<Example> response) {
 74  
 75                  assert response.body() !=null;
 76                  current_temp.setText(response.body().getMain().getTemp() + " ℃");
 77                  current_output.setText(response.body().getWeatherList().get(0).getDescription());
 78                  rise_time.setText(response.body().getSys().getSunrise() + " ");
 79                  set_time.setText(response.body().getSys().getSunset() + " ");
 80                  temp_out.setText(response.body().getMain().getTemp() + " ℃");
 81                  Press_out.setText(response.body().getMain().getPressure() + " hpa");
 82                  Humid_out.setText(response.body().getMain().getHumidity() + " %");
 83                  Ws_out.setText(response.body().getWind().getSpeed() + " Km/h");
 84                  Visi_out.setText(response.body().getVisibility() + " m");
 85                  Cloud_out.setText(response.body().getClouds().getAll()+ " %");
 86              }
 87  
 88              @Override
 89              public void onFailure(@NotNull Call<Example> call, @NotNull Throwable t) {
 90                  t.printStackTrace();
 91              }
 92          });
 93      }
 94  }



HomeActivity.java:
Java
  1  public class HomeActivity extends AppCompatActivity {
  2      // User current time
  3      TextView time_field;
  4      ImageView Search;
  5      EditText textfield;
  6      ConstraintLayout constraintLayout;
  7      public static int count=0;
  8      int[] drawable =new int[]{R.drawable.dubai,R.drawable.central_bank_of_nigeria,R.drawable.eiffel_tower,R.drawable.hong_kong,R.drawable.statue_of_liberty};
  9      Timer _t;
 10  
 11      @Override
 12      protected void onCreate(Bundle savedInstanceState) {
 13          super.onCreate(savedInstanceState);
 14          setContentView(R.layout.activity_home);
 15  
 16          time_field = findViewById(R.id.textView9);
 17          Search = findViewById(R.id.imageView4);
 18          textfield = findViewById(R.id.textfield);
 19  
 20          BottomNavigationView bottomNavigationView = findViewById(R.id.bottomNavigationView);
 21          NavController navController = Navigation.findNavController(this, R.id.fragment);
 22          NavigationUI.setupWithNavController(bottomNavigationView, navController);
 23  
 24          Search.setOnClickListener(new View.OnClickListener() {
 25              @Override
 26              public void onClick(View v) {
 27  
 28  
 29                  getWeatherData(textfield.getText().toString().trim());
 30  
 31  
 32                              constraintLayout = findViewById(R.id.layout);
 33                              constraintLayout.setBackgroundResource(R.drawable.dubai);
 34                              _t = new Timer();
 35                              _t.scheduleAtFixedRate(new TimerTask() {
 36                                  @Override
 37                                  public void run() {
 38                                      // run on ui thread
 39                                      runOnUiThread(() -> {
 40                                          if (count < drawable.length) {
 41  
 42                                              constraintLayout.setBackgroundResource(drawable[count]);
 43                                              count = (count + 1) % drawable.length;
 44                                          }
 45                                      });
 46                                  }
 47                              }, 5000, 5000);
 48                          }
 49  
 50              private void getWeatherData(String name) {
 51  
 52                  ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);
 53  
 54                  Call<Example> call = apiInterface.getWeatherData(name);
 55  
 56                  call.enqueue(new Callback<Example>() {
 57                      @Override
 58                      public void onResponse(@NotNull Call<Example> call, @NotNull Response<Example> response) {
 59  
 60                          assert response.body() != null;
 61                          time_field.setText(String.valueOf(response.body().getDt()));
 62  
 63  
 64  
 65                      }
 66  
 67                      @Override
 68                      public void onFailure(@NotNull Call<Example> call, @NotNull Throwable t) {
 69                          t.printStackTrace();
 70                      }
 71  
 72  
 73                  });
 74              }
 75  
 76  
 77  
 78  
 79          });
 80      }
 81  }


It's a Weather App by the way.

What I have tried:

So i saw a suggestion on this site https://stackoverflow.com/a/15137231/13899010 suggesting to use
onActivityCreated for caling the activity's view and onCreateView for fragment.
But when i added:
@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

above the onCreateView, the onCreateView wasn't recognized as valid again.
Posted
Updated 17-Mar-21 1:01am
v2
Comments
David Crow 21-Mar-21 22:42pm    
It looks as though the onCreateView() method in FirstFragment is trying to access a UI element that belongs to the activity. Not a good design.
Chinedum Ezeozue 22-Mar-21 4:10am    
Yeah that's exactly it. I know it's not a good design and I'd have loved to use only the fragment's element, but there's only a search button that searches for weather city in the activity, it needs to be linked to the fragment otherwise, I won't be able to access the fragment data.

Can't there be a way to do it even if it's not a good design? Can't it work?
David Crow 22-Mar-21 13:53pm    
One way would be for the fragment to save the data to a preference. The activity could then monitor for changes to that particular preference and update its UI accordingly.

Another way would be to use an interface between the activity and the fragment.
Chinedum Ezeozue 22-Mar-21 14:35pm    
Okay thanks a lot! This was helpful

1 solution

The key messages there are:
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference

...

        at com.tex.lightweatherforecast.Activity.HomeActivity.onCreate(HomeActivity.java:43)

But there is no call to getText around that line. You need to run the app in the debugger to see which reference is not being initialised.
 
Share this answer
 
Comments
Chinedum Ezeozue 17-Mar-21 7:07am    
I did call the getText in my fragment(line 60)
EditText textfield = getActivity().findViewById(R.id.textfield);
Richard MacCutchan 17-Mar-21 7:09am    
Yes, I noticed that but it is not clear if that is the problem. Have you checked the XML to see that the id name is correct? What do you see when you run the code in the debugger?
Chinedum Ezeozue 17-Mar-21 8:47am    
Sure i did, the id name is correct
Runtime error still shows the exact same error
Richard MacCutchan 17-Mar-21 8:49am    
Well, as I keep saying, you have to use the debugger to find the problem. We cannot run the code for you.
Chinedum Ezeozue 18-Mar-21 7:15am    
Please I'm not saying run the code for me, I've spent several hours trying to figure out a solution, yet I'm able to achieve nothing. My only plea is is how to call the getActivity in such a way it will not return null because it returns npe whenever I use the oncreateview, it may work on the onActivityCreated but I've not found a way to do that, please help

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900