i have a basic navigation with 3 tabs. One of them contains a fragment with google maps in it. However the navigation isn't good, it keeps crashing after i select the tab for the second time.
It says it is because of the XML file of the maps which in my opinion doesn't have anything wrong. Can anyone see my error which i am blinded for right now?
Logcat :
android.view.InflateException: Binary XML file line #7: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:719)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:761)
at android.view.LayoutInflater.inflate(LayoutInflater.java:498)
at android.view.LayoutInflater.inflate(LayoutInflater.java:398)
at com.example.dell.animalz.MapsFragment.onCreateView(MapsFragment.java:22)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1504)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:942)
at android.support.v4.app.FragmentManagerImpl.attachFragment(FragmentManager.java:1297)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:672)
at
android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1484)
at
android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:482)
at
android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1073)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:555)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:514)
at android.support.v4.view.ViewPager.setCurrentItem(ViewPager.java:495)
at com.example.dell.animalz.HomeActivity.onTabSelected(HomeActivity.java:67)
at com.android.internal.app.ActionBarImpl.selectTab(ActionBarImpl.java:674)
at com.android.internal.app.ActionBarImpl$TabImpl.select(ActionBarImpl.java:1217)
at
com.android.internal.widget.ScrollingTabContainerView$TabClickListener.onClick(ScrollingTabContainerView.java:976)
at android.view.View.performClick(View.java:4637)
at android.view.View$PerformClick.run(View.java:19422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5586)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalArgumentException: Binary XML file line #7: Duplicate id 0x7f070067, tag null, or parent id 0x0 with another fragment for com.google.android.gms.maps.SupportMapFragment
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:297)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:691)
HomeActivity.java
public class HomeActivity extends FragmentActivity implements ActionBar.TabListener {
ViewPager mViewPager = null;
private TabsMenuAdapter mAdapter;
private ActionBar actionBar;
private String []tabs = {"News", "Animalz", "Maps"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_layout);
mViewPager = (ViewPager)findViewById(R.id.viewpager1);
actionBar = getActionBar();
mAdapter = new TabsMenuAdapter(getSupportFragmentManager());
mViewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
for(String tab_names : tabs){
actionBar.addTab(actionBar.newTab().setText(tab_names).setTabListener(this));
}
mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener(){
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
mViewPager.setCurrentItem(tab.getPosition());
}
}
Maps.java
public class MapsFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.maps_layout, container, false);
return rootView;
}
}
Maps.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">
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment"/>
</RelativeLayout>
Any help would be appreciated, thanks in advance !
You have to remove the MapFragment in the onDestroyView() method of the Fragment that contains the map, with referring to this answer, you must do the following:
// override the onDestroyView of the fragment
#Override
public void onDestroyView() {
super.onDestroyView();
MapFragment f = (MapFragment) getFragmentManager()
.findFragmentById(R.id.the_map);
if (f != null)
getFragmentManager().beginTransaction().remove(f).commit();
}
Every time check your parent view empty or not. If yes then remove. Change your Maps.java.
private static View view;
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup group,Bundle bundle)
{
if(view!=null)
{
ViewGroup parent =(ViewGroup)view.getParent();
if(parent!=null)
parent.removeView(view);
}
try{
view=inflater.inflate(R.layout.maps, group, false);
........
}
catch(Exception e)
{
Log.e("ERROR", ""+e);
}
return view;
}
Related
I have a working "folder explorer" for the internal storage only. But I want to improve that explorer to use internal and external storage. I want something like this:
Bellow is the basic code of my working folder explorer (internal storage only):
select_folders.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.fragment.app.FragmentContainerView
android:id="#+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
SelectFoldersActiviy.java
public class SelectMusicFolderActivity extends AppCompatActivity {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragmentContainer, FoldersFragment.newInstance(path))
.commit();
}
}
...
}
The following fragment class uses a ListView to list all subfolders for a folder. In the onItemClick() method of the ListView objet I instantiate a new fragment with the current item path as argument. Like so:
FoldersFragment.java
public class FoldersFragment extends Fragment {
...
private static final String RUTA_KEY = "ruta";
private final String PATH = "ruta";
public static FoldersFragment newInstance(String ruta) {
FoldersFragment fragment = new FoldersFragment();
Bundle args = new Bundle();
args.putString(RUTA_KEY, ruta);
fragment.setArguments(args);
return fragment;
}
...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
ruta = getArguments().getString(RUTA_KEY);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
...
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
getActivity().getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragmentContainer,
FoldersFragment.newInstance(currentItemPath))
.addToBackStack(null)
.commit();
}
}
}
With what I can combine the viewpager2 to get the aproach of the image?
I tried with fragmentcontainerview inside viewpager2, but viewpager2 dont support direct childs.
I tried with NavHostFragment too, but that needs a predefined navigation graph, and the number of folders is undetermined.
So,im trying to call some methods of an extended fragment class into mainActivity and somehow i cant get the variable to reference the actual fragment.
It says im referencing a null object when im calling the frag.method() line.
Is it because of wrong id in findFragmentByid() inside of the onCreate() in mainActivity?
Ive tried using the id of the linear and constraint layout ('yes' and 'paint'),still get the error.
Main activity
public class MainActivity extends AppCompatActivity {
public ViewGroup.LayoutParams params;
private Path path=new Path();
private Paint brush = new Paint();
private PaintView paintView;
FirstFragment frag=new FirstFragment();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
frag = (FirstFragment) getSupportFragmentManager().findFragmentById(R.id.paint);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar2);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
toolbar.setMinimumWidth(20);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
switch (id){
case R.id.eraser:
frag.eraser();
return true;
case R.id.brush:
frag.brush();
return true;
}
return super.onOptionsItemSelected(item);
}
}
FirstFragment
public class FirstFragment extends Fragment {
public FirstFragment() {}
private PaintView paintView;
#Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState
) {
View rootView=inflater.inflate(R.layout.fragment_first,container,false);
LinearLayout Rl= (LinearLayout) rootView.findViewById(R.id.paint);
paintView=new PaintView(getActivity());
Rl.addView(paintView);
// Inflate the layout for this fragment
return rootView;
}
public void onViewCreated(#NonNull View view, Bundle savedInstanceState) {
paintView.brush();
super.onViewCreated(view, savedInstanceState);
/*
view.findViewById(R.id.button_first).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
NavHostFragment.findNavController(FirstFragment.this)
.navigate(R.id.action_FirstFragment_to_SecondFragment);
}
});
*/
}
public void eraser()
{
paintView.eraser();
}
public void brush(){
paintView.brush();
}
}
first_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/yes"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".FirstFragment" >
<LinearLayout
android:id="#+id/paint"
android:layout_width="409dp"
android:layout_height="0dp"
android:layout_marginStart="1dp"
android:layout_marginTop="1dp"
android:layout_marginEnd="1dp"
android:orientation="horizontal"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"></LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Error
Process: com.example.myapplication, PID: 29743
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.myapplication.FirstFragment.eraser()' on a null object reference
at com.example.myapplication.MainActivity.onOptionsItemSelected(MainActivity.java:50)
at android.app.Activity.onMenuItemSelected(Activity.java:4137)
at androidx.fragment.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:436)
at androidx.appcompat.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:196)
at androidx.appcompat.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:109)
at androidx.appcompat.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:109)
at androidx.appcompat.app.ToolbarActionBar$2.onMenuItemClick(ToolbarActionBar.java:64)
at androidx.appcompat.widget.Toolbar$1.onMenuItemClick(Toolbar.java:204)
at androidx.appcompat.widget.ActionMenuView$MenuBuilderCallback.onMenuItemSelected(ActionMenuView.java:781)
at androidx.appcompat.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:840)
at androidx.appcompat.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:158)
at androidx.appcompat.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:991)
at androidx.appcompat.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:981)
at androidx.appcompat.widget.ActionMenuView.invokeItem(ActionMenuView.java:625)
at androidx.appcompat.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:151)
at android.view.View.performClick(View.java:7125)
at android.view.View.performClickInternal(View.java:7102)
at android.view.View.access$3500(View.java:801)
at android.view.View$PerformClick.run(View.java:27336)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
29743-29743/com.example.myapplication I/Process: Sending signal. PID: 29743 SIG: 9
Welp,the problem was caused by the fact that there was no fragment in the respective layout since the layout(yes,paint) was INSIDE the fragment i was trying to call,so basically id mismatch.Stupid me.
I'm trying to use a FrameLayout on one of my activities. I want this FrameLayout to be a placeholder in an activity and I want to add/replace/remove fragments inside it.
I have a simple cafe app used for studying android. For simplicity I will post the code for the Cake and Breads category.
Problem: NullPointerException. I don't know the reason WHY my fragment's view is null. I'm guessing maybe the fragment lifecycle didn't run so the view was not inflated thus accessing the view throws a nullpointer? Please help me understand WHY a nullpointer is thrown.
Flow of the App
User selects a specific cake or bread in a ListFragment > CakeAndBreadActivity is called > Display Cake or Bread specific detail
I'm looking for: the explanation and reason behind the NullPointerException in the view and How can I display the Cakes and Bread details into the fragment when using FrameLayout.
NullPointerException
--------- beginning of crash
10-25 01:41:21.550 2374-2374/com.cafe E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.cafe, PID: 2374
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.cafe/com.cafe.CakeAndBreadActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at com.cafe.CakeAndBreadDetailFragment.displayCakeAndBreadDetails(CakeAndBreadDetailFragment.java:97)
at com.cafe.CakeAndBreadActivity.displayCakeAndBreadDetails(CakeAndBreadActivity.java:30)
at com.cafe.CakeAndBreadActivity.onCreate(CakeAndBreadActivity.java:19)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
CakeAndBreadActivity
public class CakeAndBreadActivity extends Activity implements CakeAndBreadDetailFragment.onCakeAndBreadDetailFragmentListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cake_and_bread);
displayCakeAndBreadDetails();
}
public void displayCakeAndBreadDetails(){
Intent cakeAndBreadIntent = getIntent();
int cakeAndBreadId = Integer.valueOf(cakeAndBreadIntent.getIntExtra("cakeAndBreadNumber", 0));
CakeAndBreadDetailFragment cakeAndBreadDetail = new CakeAndBreadDetailFragment();
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
cakeAndBreadDetail.displayCakeAndBreadDetails(cakeAndBreadId);
fragmentTransaction.replace(R.id.cake_and_bread_detail_frame_layout_id, cakeAndBreadDetail);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
#Override
public void onCakeAndBreadDetail(int id) {
}
}
activity_cake_and_bread.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.cafe.CakeAndBreadActivity">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:id="#+id/cake_and_bread_detail_frame_layout_id"/>
</LinearLayout>
CakeAndBreadDetailFragment
public class CakeAndBreadDetailFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
private onCakeAndBreadDetailFragmentListener mListener;
public CakeAndBreadDetailFragment() {
}
public static CakeAndBreadDetailFragment newInstance(String param1, String param2) {
CakeAndBreadDetailFragment fragment = new CakeAndBreadDetailFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_cake_and_bread_detail, container, false);
}
public void onButtonPressed(int id) {
if (mListener != null) {
mListener.onCakeAndBreadDetail(id);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof onCakeAndBreadDetailFragmentListener) {
mListener = (onCakeAndBreadDetailFragmentListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement onCakeAndBreadDetailFragmentListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface onCakeAndBreadDetailFragmentListener {
// TODO: Update argument type and name
void onCakeAndBreadDetail(int id);
}
public void displayCakeAndBreadDetails(int id){
CakeAndBread cakeAndBread = (CakeAndBread)CakeAndBread.getCakeAndBreadList().get(id);
View cakeAndBreadView = getView();
TextView cakeAndBreadTextView = (TextView)cakeAndBreadView.findViewById(R.id.cake_and_bread_detail_fragment_id);
cakeAndBreadTextView.setText(cakeAndBread.getCakeAndBreadName() + " " + cakeAndBread.getCakeAndBreadNutritionFacts());
}
}
fragment_cake_and_bread_detail.xml
<LinearLayout 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.cafe.CakeAndBreadDetailFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:id="#+id/cake_and_bread_detail_fragment_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
EDIT: as suggested, the fragment was not completely loaded when I'm trying to access the view, thus the nullpointerexception is thrown. Now my problem is the framelayout or the fragment doesn't show the textview that I placed in the fragment, how do I solve this? I'm passing cake and bread id and then setting the text in the setText(...) method of the TextView.
cakeAndBreadDetail.displayCakeAndBreadDetails(cakeAndBreadId);
fragmentTransaction.replace(R.id.cake_and_bread_detail_frame_layout_id, cakeAndBreadDetail);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
You are calling displayCakeAndBreadDetails(..) which calls displayCakeAndBreadDetails(..) which calls getView().
At that point you haven't inserted the fragment yet (happens after fragmentTransaction.commit();) so there is no view associated with the fragment. Hence getView() returns null.
#Kiskae is correct. You're calling cakeAndBreadDetail.displayCakeAndBreadDetails(cakeAndBreadId), when the fragment isn't ready which will result in a NullPointerException. Try:
public class CakeAndBreadActivity extends Activity implements CakeAndBreadDetailFragment.onCakeAndBreadDetailFragmentListener {
public void displayCakeAndBreadDetails(){
Intent cakeAndBreadIntent = getIntent();
int cakeAndBreadId = Integer.valueOf(cakeAndBreadIntent.getIntExtra("cakeAndBreadNumber", 0));
CakeAndBreadDetailFragment cakeAndBreadDetail = CakeAndBreadDetailFragment.newInstance(cakeAndBreadId);
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.cake_and_bread_detail_frame_layout_id, cakeAndBreadDetail);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
public class CakeAndBreadDetailFragment extends Fragment {
private static final String ARG_CAKE_AND_BREAD_ID = "ARG_CAKE_AND_BREAD_ID";
public CakeAndBreadDetailFragment() {
}
public static CakeAndBreadDetailFragment newInstance(int cakeAndBreadId) {
CakeAndBreadDetailFragment fragment = new CakeAndBreadDetailFragment();
Bundle args = new Bundle();
args.putInt(ARG_CAKE_AND_BREAD_ID, cakeAndBreadId);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_cake_and_bread_detail, container, false);
if (getArguments != null) {
int cakeAndBreadId = getArguments.getInt(ARG_CAKE_AND_BREAD_ID, -1);
if (cakeAndBreadId != -1) {
displayCakeAndBreadDetails(cakeAndBreadId);
}
}
return view;
}
public void displayCakeAndBreadDetails(int id){
...
}
}
I created an android application using ButterKnife. I wanted to add an activity with Navigation bar . So I used , Navigation Drawer Activityin android studio.
Then I tried to launch it using another activity .Like this ,
Intent intent = new Intent(this, AddInfoActivity.class);
startActivity(intent);
Then I got following error message.
FATAL EXCEPTION: main
Process: xxx.com.au.abcd, PID: 13408
java.lang.RuntimeException: Unable to start activity ComponentInfo{xxx.com.au.abcd/xxx.com.au.abcd.activities.AddInfoActivity}: android.view.InflateException: Binary XML file line #18: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2436)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2498)
at android.app.ActivityThread.access$900(ActivityThread.java:179)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1324)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5641)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1288)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1104)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #18: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:719)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:761)
at android.view.LayoutInflater.inflate(LayoutInflater.java:498)
at android.view.LayoutInflater.inflate(LayoutInflater.java:398)
at android.view.LayoutInflater.inflate(LayoutInflater.java:354)
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:284)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
at xxx.com.au.abcd.activities.AddInfoActivity.onCreate(AddInfoActivity.java:33)
at android.app.Activity.performCreate(Activity.java:5484)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2400)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2498)
at android.app.ActivityThread.access$900(ActivityThread.java:179)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1324)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5641)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1288)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1104)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at xxx.com.au.abcd.activities.NavigationDrawerFragment.onCreateView(NavigationDrawerFragment.java:103)
at android.app.Fragment.performCreateView(Fragment.java:1700)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:866)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1040)
at android.app.FragmentManagerImpl.addFragment(FragmentManager.java:1142)
at android.app.Activity.onCreateView(Activity.java:5020)
at android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:36)
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:75)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:695)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:761)
at android.view.LayoutInflater.inflate(LayoutInflater.java:498)
at android.view.LayoutInflater.inflate(LayoutInflater.java:398)
at android.view.LayoutInflater.inflate(LayoutInflater.java:354)
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:284)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
at xxx.com.au.abcd.activities.AddInfoActivity.onCreate(AddInfoActivity.java:33)
at android.app.Activity.performCreate(Activity.java:5484)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2400)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2498)
at android.app.ActivityThread.access$900(ActivityThread.java:179)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1324)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5641)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
And this is my activity with navigation bar,
AddInfoActivity.java
import android.app.Activity;
import butterknife.ButterKnife;
import tekhinno.com.au.mygulukose.R;
public class AddInfoActivity extends BaseActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_info_activity);
ButterKnife.inject(this);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_add_info, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((AddInfoActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
NavigationDrawerFragment.java
import butterknife.ButterKnife;
import tekhinno.com.au.mygulukose.R;
/**
* Fragment used for managing interactions for and presentation of a navigation drawer.
* See the <a href="https://developer.android.com/design/patterns/navigation-drawer.html#Interaction">
* design guidelines</a> for a complete explanation of the behaviors implemented here.
*/
public class NavigationDrawerFragment extends Fragment {
/**
* Remember the position of the selected item.
*/
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
/**
* Per the design guidelines, you should show the drawer on launch until the user manually
* expands it. This shared preference tracks this.
*/
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
/**
* A pointer to the current callbacks instance (the Activity).
*/
private NavigationDrawerCallbacks mCallbacks;
/**
* Helper component that ties the action bar to the navigation drawer.
*/
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
public NavigationDrawerFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Read in the flag indicating whether or not the user has demonstrated awareness of the
// drawer. See PREF_USER_LEARNED_DRAWER for details.
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
// Select either the default item (0) or the last selected item.
selectItem(mCurrentSelectedPosition);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Indicate that this fragment would like to influence the set of actions in the action bar.
setHasOptionsMenu(true);
}
**#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mDrawerListView = (ListView) inflater.inflate(
R.layout.drawer_add_info, container, false);
mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
});
mDrawerListView.setAdapter(new ArrayAdapter<String>(
getActionBar().getThemedContext(),
android.R.layout.simple_list_item_activated_1,
android.R.id.text1,
new String[]{
getString(R.string.title_section1),
getString(R.string.title_section2),
getString(R.string.title_section3),
}));
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
return mDrawerListView;
}**
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
/**
* Users of this fragment must call this method to set up the navigation drawer interactions.
*
* #param fragmentId The android:id of this fragment in its activity's layout.
* #param drawerLayout The DrawerLayout containing this fragment's UI.
*/
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the navigation drawer and the action bar app icon.
mDrawerToggle = new ActionBarDrawerToggle(
getActivity(), /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.navigation_drawer_open, /* "open drawer" description for accessibility */
R.string.navigation_drawer_close /* "close drawer" description for accessibility */
) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
if (!mUserLearnedDrawer) {
// The user manually opened the drawer; store this flag to prevent auto-showing
// the navigation drawer automatically in the future.
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
}
getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
// If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
// per the navigation drawer design guidelines.
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Forward the new configuration the drawer toggle component.
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// If the drawer is open, show the global app actions in the action bar. See also
// showGlobalContextActionBar, which controls the top-left area of the action bar.
if (mDrawerLayout != null && isDrawerOpen()) {
inflater.inflate(R.menu.global, menu);
showGlobalContextActionBar();
}
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
if (item.getItemId() == R.id.action_example) {
Toast.makeText(getActivity(), "Example action.", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Per the navigation drawer design guidelines, updates the action bar to show the global app
* 'context', rather than just what's in the current screen.
*/
private void showGlobalContextActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setTitle(R.string.app_name);
}
private ActionBar getActionBar() {
return getActivity().getActionBar();
}
/**
* Callbacks interface that all activities using this fragment must implement.
*/
public static interface NavigationDrawerCallbacks {
/**
* Called when an item in the navigation drawer is selected.
*/
void onNavigationDrawerItemSelected(int position);
}
}
And these are my layout files,
fragment_add_info.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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="tekhinno.com.au.mygulukose.activities.AddInfoActivity$PlaceholderFragment">
<TextView
android:id="#+id/section_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
drawer_add_info.xml
<ListView 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"
android:background="#cccc"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
tools:context="tekhinno.com.au.mygulukose.activities.NavigationDrawerFragment" />
add_info_activity.xml
<!-- A DrawerLayout is intended to be used as the top-level content view using match_parent for both width and height to consume the full space available. -->
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="tekhinno.com.au.mygulukose.activities.AddInfoActivity">
<!-- As the main content view, the view below consumes the entire
space available using match_parent in both dimensions. -->
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- The drawer is given a fixed width in dp and extends the full height of
the container. -->
<fragment
android:id="#+id/navigation_drawer"
android:name="tekhinno.com.au.mygulukose.activities.NavigationDrawerFragment"
android:layout_width="#dimen/navigation_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
tools:layout="#layout/drawer_add_info" />
</android.support.v4.widget.DrawerLayout>
NOTE :- These layout files and NavigationDrawerFragment.java were generated by Android Studio.
Have any idea about this problem ?
You are using getFragmentManager() to get the fragment manager. You need to get SupportFragmentManager if you are extending AppCompatActivity by your BaseActivity.
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
.commit();
}
Note: While using support packages you need to use SupportFragmentManager.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I'm starting with android and just getting crazy with the implements of multiple fragments.
I have two fragments in my MainActivity: QuestionDetail and QuestionListFragment.
When I use a fragment transactions to replace the QuestionDetail fragment when someone click in one of the QuestionListFragment options I get a NullPointerException error.
I have been trying to fix this issue for hours. Any help is greatly appreciated.
QuestionDetail
public class QuestionListFragment extends Fragment{
private RecyclerView recView;
public static QuestionAdapter adapter;
private QuestionListener listener;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_question_list, container, false);
recView = (RecyclerView) v.findViewById(R.id.recView);
return v;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recView.setLayoutManager(layoutManager);
adapter = new QuestionAdapter(QuestionCatalog.getQuestionCatalog().getQuestionList().getList());
adapter.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if (listener!=null) {
listener.onQuestionListener(adapter.getItem(recView.getChildAdapterPosition(v)));
}
}
});
recView.setAdapter(adapter);
}
public interface QuestionListener {
void onQuestionListener(Question q);
}
public void setQuestionListener(QuestionListener listener) {
this.listener=listener;
}
QuestionDetail
public class QuestionDetail extends Fragment {
// We use an ID to know which Question we're using
private long questionId;
public QuestionDetail() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_question_detail, container, false);
}
#Override
public void onStart() {
super.onStart();
//Fragments don’t include findViewById(). To get a reference to a view, we use getView()
View view = getView();
if (view != null) {
TextView title = (TextView) view.findViewById(R.id.textQuestion);
Question question = QuestionCatalog.getQuestionCatalog().getQuestionList().getList().get((int) questionId);
title.setText(question.getName());
TextView kind = (TextView) view.findViewById(R.id.textKind);
kind.setText(question.getKind());
}
}
public void showDetails(String texto) {
TextView txtName = (TextView)getView().findViewById(R.id.textQuestion);
TextView txtKind = (TextView)getView().findViewById(R.id.textKind);
txtName.setText(texto);
txtKind.setText(texto);
}
}
MainActivity
public class MainActivity extends AppCompatActivity implements QuestionListFragment.QuestionListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
QuestionListFragment frg =(QuestionListFragment)getFragmentManager().findFragmentById(R.id.listFragment);
frg.setQuestionListener(this);
}
#Override
public void onQuestionListener(Question q) {
Toast.makeText(this, "num: " + q.getName(),
Toast.LENGTH_LONG).show();
FragmentTransaction t = getSupportFragmentManager().beginTransaction();
QuestionDetail f1 = new QuestionDetail();
f1.showDetails(q.getName());
t.replace(R.id.detailFragment,f1);
t.addToBackStack(null);
t.commit();
}
stacktrace
08-04 09:54:11.914 22277-22277/com.hfad.predictandwin E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at com.hfad.predictandwin.Fragments.QuestionDetail.showDetails(QuestionDetail.java:50)
at com.hfad.predictandwin.MainActivity.onQuestionListener(MainActivity.java:34)
at com.hfad.predictandwin.Fragments.QuestionListFragment$1.onClick(QuestionListFragment.java:55)
at com.hfad.predictandwin.QuestionAdapter.onClick(QuestionAdapter.java:61)
at android.view.View.performClick(View.java:4475)
at android.view.View$PerformClick.run(View.java:18786)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5419)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
at dalvik.system.NativeStart.main(Native Method)
First, don't use getView() in onStart() - You shouldn't have a view to get at that point. Second, you shouldn't be calling methods directly on the Fragment instances from elsewhere, in your case f1.showDetails(q.getName());. There, again, the Fragment has no View. Please see Best practice for instantiating a new Android Fragment for how to pass arguments into Fragment before you load it into the FragmentManager.
Next point - you should initialize your views using findViewById inside of onCreateView just like you did for the other Fragment class. For example,
private TextView txtName, txtKind;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_question_detail, container, false);
txtName = (TextView) rootView.findViewById(R.id.textQuestion);
txtKind = (TextView) rootView.findViewById(R.id.textKind);
// TODO: Read the link how to use these
Bundle arguments = getArguments();
Question question = QuestionCatalog.getQuestionCatalog()
.getQuestionList().getList().get((int) questionId);
showQuestion(question);
return view;
}
private void showQuestion(Question q) {
txtName.setText(q.getName());
txtKind.setText(q.getKind());
}
in QuestionListFragment:
We set click listener for recView, not adapter. You should replace adapter.setOnClickListener with
recView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recView, new ClickListener() {
#Override
public void onClick(View view, int position) {
// do something with position.
}
#Override
public void onLongClick(View view, int position) {
}
}));
in QuestionDetail:
questionId wasn't initialized but you have use it in this line:
Question question = QuestionCatalog.getQuestionCatalog().getQuestionList().getList().get((int) questionId);
Based on stacktrace and your code (not sure which one is line #50 in your QuestionDetail) ether txtName or txtKind evaluates to null (maybe both), so for whatever reason getView().findViewById(R.id.textQuestion) returns null. Probably because getView() in that call doesn't get you a parent view of the TextView in question