I had this problem with every TextView. I tried a lot of things but i just can't manage to make it work. If you have any suggestion, please help.
I'm begginer in android but I think this is simple problem, but i just can't fix it.
Thanks in advance.
Code for fragment Home
package com.example.mmreviews;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class HomeFragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
LayoutInflater lf = getActivity().getLayoutInflater();
View view = lf.inflate(R.layout.fragment_home, container, false);
view.findViewById(R.id.btn_edit).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getFragmentManager().beginTransaction().replace(R.id.fragment_container, new EditFragment()).commit();
}
});
view.findViewById(R.id.btn_logout).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), LogIn.class);
startActivity(intent);
}
});
TextView textViewUsernameInfo = view.findViewById(R.id.username);
textViewUsernameInfo.setText("Some text");
return view;
}
}
Xml for text i want to set. Maybe i should try some other text view?
<TextView
android:id="#+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="#id/text1"
android:layout_toRightOf="#id/text1"
android:textColor="#4B83E5"
android:textSize="16sp">
</TextView>
exception that I get
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mmreviews, PID: 6184
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mmreviews/com.example.mmreviews.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2957)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6944)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.example.mmreviews.HomeFragment.onCreateView(HomeFragment.java:38)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2600)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:881)
at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303)
at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:439)
at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManagerImpl.java:2079)
at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1869)
at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1824)
at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1727)
at androidx.fragment.app.FragmentManagerImpl.dispatchStateChange(FragmentManagerImpl.java:2663)
at androidx.fragment.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManagerImpl.java:2613)
at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:246)
at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:542)
at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:210)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1340)
at android.app.Activity.performStart(Activity.java:7200)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2920)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6944)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
Try this:
TextView textViewUsernameInfo = (TextView)view.findViewById(R.id.username);
textViewUsernameInfo.setText("Some text");
For some reason, you have two inflaters
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
//LayoutInflater inflater also inflater, but you decalre another inflater
LayoutInflater lf = getActivity().getLayoutInflater();
//and i assume you try to get lf LayoutInflater from Activity not from Fragment
View view = lf.inflate(R.layout.fragment_home, container, false);
...
}
Try to remove
LayoutInflater lf = getActivity().getLayoutInflater();
and change your view to
assert inflater != null;//not required but try to add
View view = inflater.inflate(R.layout.fragment_home, container, false);
According to docs: onCreateView(LayoutInflater, ViewGroup, Bundle) creates and returns the view hierarchy associated with the fragment and LayoutInflater object can be used to inflate any views in the fragment.
Docs about fragment
UPD: I won't able to recreate your error.
I created simple XML for the main activity and for fragment separately
main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.fragment.app.FragmentContainerView
android:id="#+id/fragmentContainerView"
android:name="com.example.test.MainFragment"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
main_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainFragment">
<TextView
android:id="#+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#4B83E5"
android:textSize="16sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
</TextView>
<Button
android:id="#+id/btn_edit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<Button
android:id="#+id/btn_logout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Created Fragment class and left MainActivity with default
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.main_activity);
}
}
Fragment class
public class MainFragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main_fragment, container, false);
Button button1 = view.findViewById(R.id.btn_edit);
button1.setOnClickListener(v -> Toast.makeText (requireContext (),"short1",Toast.LENGTH_SHORT).show ());
Button button2 = view.findViewById(R.id.btn_logout);
button2.setOnClickListener(v -> Toast.makeText (requireContext (),"short2",Toast.LENGTH_SHORT).show ());
TextView textViewUsernameInfo = view.findViewById(R.id.username);
textViewUsernameInfo.setText("Some text");
return view;
}}
It is working fine without throwing NullPointerException for me.
You can try ViewBinding from Android Devs or ButterKnife third-party library from JakeWharton (it is deprecated as for 2021 and wouldn't have further updates, because ViewBinding does the same - still you can use it.)
Related
I'm doing a recycler method in my android studio project but i have a problem.
Everytime i'm trying to findViewById my application is crashing.
Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
And i don't understand why because i'm creating my view in the good way.
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_carrito, container, false);
return view;
}
And i'm trying to continue with that
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
...
Log.e("test : ",Integer.toString(R.id.recyclerBuy));
recyView = view.findViewById(R.id.recyclerBuy);
/* recyView.setLayoutManager(new GridLayoutManager(getContext(),RecyclerView.VERTICAL));
recyView.setAdapter(buyAdapter);
*/
}
But i'm crashing at the line recyView = view.findViewById(R.id.recyclerBuy);. My R.id.recyclerBuy is not empty.
And here is my RecyclerView
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".ui.carrito.CarritoFragment">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerBuy"
android:layout_width="match_parent"
android:layout_height="550dp"
android:layout_marginBottom="88dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent" />
...
</androidx.constraintlayout.widget.ConstraintLayout>
Anyone have a clue why i'm crashing everytime ?
This happens because onAttach() callback is called before onCreateView().
The easiest way to fix the issue is placing the code where you finding your RecyclerView in onCreateView(). Something like:
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_carrito, container, false);
recyView = view.findViewById(R.id.recyclerBuy);
// here you recyView won't be null
return view;
}
A good article about fragments lifecycle: https://medium.com/androiddevelopers/the-android-lifecycle-cheat-sheet-part-iii-fragments-afc87d4f37fd
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 1 year ago.
**I am new to android studio and java
I'm trying to bind a button to an activity that contains a recycler view and the adapter that comes with it. The problem is when I click on the button the activity crashes. I know the button is not the problem because I have a different activity that uses a button and goes to the activity.
The problem is in either the activity for the recycler view which is named EdwardActivity or the adapter and I can't seem to figure it out.
Error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.edu.pfrfitness, PID: 10520
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.edu.pfrfitness/com.edu.pfrfitness.EdwardActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setLayoutManager(androidx.recyclerview.widget.RecyclerView$LayoutManager)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setLayoutManager(androidx.recyclerview.widget.RecyclerView$LayoutManager)' on a null object reference
at com.edu.pfrfitness.EdwardActivity.onCreate(EdwardActivity.java:31)
at android.app.Activity.performCreate(Activity.java:8000)
at android.app.Activity.performCreate(Activity.java:7984)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
I/Process: Sending signal. PID: 10520 SIG: 9
Activity for recycler(named Edward Activity):
package com.edu.pfrfitness;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
public class EdwardActivity extends AppCompatActivity {
RecyclerView recyclerView;
String s1[], s2[];
int images [] = {R.drawable.black, R.drawable.black, R.drawable.black, R.drawable.black, R.drawable.black, R.drawable.black};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_row);
recyclerView = findViewById(R.id.recyclerView);
s1 = getResources() .getStringArray(R.array.Navigation_List);
s2 = getResources() .getStringArray(R.array.description);
MyAdapter myAdapter = new MyAdapter(this, s1, s2, images);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(myAdapter);
//call recycler
}
public void Recycler(){
}
}
Adapter:
package com.edu.pfrfitness;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
String data1[], data2[];
int images[];
Context context;
public MyAdapter(Context ct, String s1[], String s2[], int img[]) {
context = ct;
data1 = s1;
data2 = s2;
images = img;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.my_row, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.edwardText1.setText(data1[position]);
holder.edwardText2.setText(data2[position]);
holder.edwardImageView.setImageResource(images[position]);
}
#Override
public int getItemCount() {
return images.length;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView edwardText1, edwardText2;
ImageView edwardImageView;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
edwardText1 = itemView.findViewById(R.id.edwardText1);
edwardText2 = itemView.findViewById(R.id.edwardText2);
edwardImageView = itemView.findViewById(R.id.edwardImageView);
}
}
}
My row so like how each row will look:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:ignore="MissingConstraints">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/edwardImageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:srcCompat="#tools:sample/avatars" />
<TextView
android:id="#+id/edwardText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginTop="10dp"
android:text="Navigation_List"
android:textSize="24sp"
android:textStyle="bold"
app:layout_constraintStart_toEndOf="#+id/edwardImageView"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/edwardText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="description"
android:textSize="16sp"
app:layout_constraintStart_toStartOf="#+id/edwardText1"
app:layout_constraintTop_toBottomOf="#+id/edwardText1" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
</androidx.constraintlayout.widget.ConstraintLayout>
Error explanation:
According to the error you are trying to call setLayoutManager function on a null object. So, your variable "recyclerView" is obviously null.
Reason:
The reason is that in your activity you do this:
setContentView(R.layout.my_row);
and you use the file "my_row.xml" to create your Activity layout. But, in this layout there is no view with id recyclerView. So, when you do this:
recyclerView = findViewById(R.id.recyclerView);
then variable recyclerView is set to null.
Solution:
I guess that by mistake you used file "my_row.xml" as the Activity's layout, since this layout was obviously created fot the adapter's items. You should instead use another layout for the Activity's layout by passing it in your setContent in Activity's onCreate.
So I'm making an app where the bottom navigation lets you click through different web pages and I've come across a problem. I can't seem to get it where the webview will function correctly inside the fragment class.
activity_main
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fragment_container"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginBottom="56dp">
</FrameLayout>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/nav_view"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="0dp"
android:layout_marginEnd="0dp"
android:background="?android:attr/windowBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="#menu/bottom_nav_menu" />
</androidx.constraintlayout.widget.ConstraintLayout>
fragment_clever.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/clever_web"></WebView>
</RelativeLayout>
cleverfragment.java (the one im currently working with)
package com.port.schoool;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class CleverFragment extends Fragment {
WebView webview;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
webview.findViewById(R.id.clever_web);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("google.com");
return inflater.inflate(R.layout.fragment_clever, null);
}
}
mainactivity.java
package com.port.schoool;
import android.os.Bundle;
import android.view.MenuItem;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;
public class MainActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navView = findViewById(R.id.nav_view);
navView.setOnNavigationItemSelectedListener(this);
loadFragment(new ReadWorksFragment());
}
private boolean loadFragment(Fragment fragment) {
if (fragment != null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit();
return true;
}
return false;
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment fragment = null;
switch (menuItem.getItemId()) {
case R.id.navigation_home:
fragment = new ReadWorksFragment();
break;
case R.id.navigation_dashboard:
fragment = new CleverFragment();
break;
case R.id.navigation_notifications:
fragment = new PortalFragment();
break;
}
return loadFragment(fragment);
}
}
Here is my logcat logs for the crashes:
2019-08-04 18:05:25.164 7425-7425/com.port.schoool E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.port.schoool, PID: 7425
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.webkit.WebView.findViewById(int)' on a null object reference
at com.port.schoool.CleverFragment.onCreateView(CleverFragment.java:20)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2439)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManager.java:1460)
at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1784)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManager.java:1852)
at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:802)
at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManager.java:2625)
at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2411)
at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2366)
at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2273)
at androidx.fragment.app.FragmentManagerImpl$1.run(FragmentManager.java:733)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6960)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:441)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
Replace your fragment with:
public class CleverFragment extends Fragment {
WebView webview;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_clever, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
webview = view.findViewById(R.id.clever_web);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("https://google.com");
}
}
Of note:
Your original code would not compile, as there is no findViewById() on Fragment
The right version of inflate() to use in onCreateView() is the one that takes the container and false as the second and third parameters
You configure your fragment's views in onViewCreated()
You need to call findViewById() on the inflated layout (view in onViewCreated()) and assign that to webview
You need to use a valid URL with loadUrl()
This sort of stuff should be covered in your book on Android app development.
I want to change the top toolbar according to clicked fragment but it seems not working for me.
What I want is when I click the fragment, the top toolbar should change. For example, add a Add button and change the title of the toolbar for Create Fragment.
Fragment.java
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
setHasOptionsMenu(true);
View v = inflater.inflate(R.layout.fragment_event_created, container, false);
Toolbar toolbar123 = (Toolbar) v.findViewById(R.id.toolbar123);
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar123);
//((MainActivity) getActivity()).getSupportActionBar().hide();
return v;
}
Fragment XML
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.rick.check_in.ui.EventCreatedFragment">
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/toolbar123"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#131313"
android:minHeight="?attr/actionBarSize">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="right"
android:background="#00aaaaaa">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#000"
android:text="Delete"
android:textColor="#fff"
android:textSize="16dp" />
</LinearLayout>
</android.support.v7.widget.Toolbar>
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/hello_blank_fragment" />
</FrameLayout>
You can do it like this way. onAttach(Activity) called once the fragment is associated with its activity.
public class YourFragment extends Fragment {
private MainActivity mainActivity;
private Toolbar toolbar123;
public YourFragment() {
// Required empty public constructor
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mainActivity = (MainActivity)activity;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_event_created, container, false);
toolbar123 = (Toolbar)v.findViewById(R.id.toolbar123);
setupToolbar();
return v;
}
private void setupToolbar(){
toolbar123.setTitle(getString("Your Fragment Title"));
mainActivity.setSupportActionBar(toolbar123);
}
}
I have created 2 fragment and their layout,
when i click button on profile fragment it should open flat layout, but
it force stop application and its not opening the second fragment,
i have included fragment code and its layout code..
profilefragment.java
public class ProfileFragment extends Fragment {
View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.profile, container, false);
Button button = (Button) rootView.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
onButtonClicked(v);
}
});
return rootView;
}
public void onButtonClicked(View view)
{
//do your stuff here..
final FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.button, new flatview(), "NewFragmentTag");
ft.commit();
}
profile.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${packageName}.${activityClass}"
android:id="#+id/semester">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
flatview.java
public class flatview extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.flat, container, false);
}
flat.xml
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="second fragement"
android:id="#+id/textView3"
android:layout_gravity="center_horizontal" />
logcat
06-19 07:57:56.945 26457-26457/com.idealdeveloper.saltechnical E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.idealdeveloper.saltechnical, PID: 26457
java.lang.ClassCastException: android.widget.Button cannot be cast to android.view.ViewGroup
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:917)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1460)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:440)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Try this I guess it will work for you
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${packageName}.${activityClass}"
android:id="#+id/semester">
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/fragmentLayout"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
Class
public class ProfileFragment extends Fragment {
View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.profile, container, false);
Button button = (Button) rootView.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
onButtonClicked(v);
}
});
return rootView;
}
public void onButtonClicked(View view)
{
//do your stuff here..
final FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(R.id.fragmentLayout, new flatview(), "NewFragmentTag");
ft.commit();
}
I hope this one will helps you
The fragment transaction inserts a View into a ViewGroup, so you can't just replace a Button. You could just replace the parent semester, since it is a ViewGroup.
public void onButtonClicked(View view) {
final FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.semester, new flatview(), "NewFragmentTag");
ft.commit();
}
If your intention is also to remove the button, you will need to do it manually since the FragmentManager can only modify runtime transactions:
ViewGroup parent = (ViewGroup) getActivity().findViewById(R.id.semester);
parent.removeView(view);
You have to provide a ViewGroup root for the flat.xml layout , for example you can surround the TextView with a LinearLayout
flat.xml :
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="second fragement"
android:id="#+id/textView3"
android:layout_gravity="center_horizontal" />
</LinearLayout>