I know this types of error already has been answered. But i am not able figure out the cause of error. what i am trying to accomplish is to add button dynamically into fragment from a button click which is in main activity. please help me. i am new to android development,
public class MainActivity extends AppCompatActivity {
Button add;
Fragment f;
LinearLayout ll;
View v;
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
add = (Button) findViewById(R.id.addButton);
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
f = (ButtonFragment) getFragmentManager().findFragmentById(R.id.buttonLayout);
//if (f != null) {
v = f.getView();
ll = (LinearLayout) v.findViewById(R.id.buttonLayout);
Button dummy = new Button(v.getContext());
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(70, 70);
dummy.setLayoutParams(layoutParams);
ll.addView(dummy);
//} else {
// System.out.println("View is null");
//}
}
});
}
}
This is the fragment class
public class ButtonFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_button, container, false);
return rootView;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
System.out.println("View created");
}
}
this are the error code
11-25 23:15:15.442 987-987/com.example.nekib.dynamiclayoutdemo E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.nekib.dynamiclayoutdemo, PID: 987 java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.app.Fragment.getView()' on a null object reference at com.example.nekib.dynamiclayoutdemo.MainActivity$1.onClick(MainActivity.java:33) at android.view.View.performClick(View.java:4780) at android.view.View$PerformClick.run(View.java:19866) 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:5254) 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:903) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)