I am getting an error when trying to set text in textview. I have tried updating gradle(which is suggested by one of stack overflow developer's solution), also tried many solution from this same question. Nothing helped me.
ProfileFragment.java
public class ProfileFragment extends Fragment {
private TextView txtUsername, txtExperience;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_profile, container, false);
txtUsername = view.findViewById(R.id.txt_username1);
getUserInfo(view.getContext(),view,null);
return view;
}
protected User getUserInfo(Context context, View view, String user) {
Map<String, String> userDetails = new HashMap<>();
userDetails.put("userid",user);
final User[] userinfo = new User[1];
Call<User> call = RetrofitFactoryWithJwt.getRetrofitInstance(context).getUserProfile(userDetails);
call.enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
if(response.isSuccessful() && response.body() != null){
txtUsername.setText(response.body().getName());
userinfo[0] = response.body();
}
}
@Override
public void onFailure(Call<User> call, Throwable t) {
Log.d("onFailure",Log.getStackTraceString(t));
}
});
return userinfo[0];
}
}
fragment_profile.xml
<androidx.coordinatorlayout.widget.CoordinatorLayout
tools:context="com.work.workapp.profile.ProfileFragment"
android:id="@+id/profile_main">
<LinearLayout>
<TextView
android:id="@+id/txt_username1"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/txt_experience1"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
logcat error I am getting is the following:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.work.myapp, PID: 7568
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.work.workapp.profile.ProfileFragment$6.onResponse(ProfileFragment.java:236)
at retrofit2.DefaultCallAdapterFactory$ExecutorCallbackCall$1$1.run(DefaultCallAdapterFactory.java:83)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7325)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)