Can't set Text of TextView - java

I wanted to have the Text of a TextView changed to whatever the username of the active user is, but the method updateUI() always returns this error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.cocko.industries.einkaufshelfer.shopper, PID: 18704
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.cocko.industries.einkaufshelfer.shopper/com.cocko.industries.einkaufshelfer.shopper.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: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 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.cocko.industries.einkaufshelfer.shopper.MainActivity.updateUI(MainActivity.java:203)
at com.cocko.industries.einkaufshelfer.shopper.MainActivity.onCreate(MainActivity.java:76)
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)
So what's the problem? It seems to me as if the TextView can't be found and is therefore null. But why? And how can I fix that? Below you can find the MainActivity class with the onCreate and updateUI method and the fragment that I used.
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawer;
private NavigationView nav_view;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mAuth = FirebaseAuth.getInstance();
nav_view = findViewById(R.id.nav_view);
nav_view.setNavigationItemSelectedListener(this);
drawer = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.nav_drawer_open, R.string.nav_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
try {
Intent intent = getIntent();
if (intent.getStringExtra("activity").equals("register")) {
getSupportFragmentManager().beginTransaction().replace(R.id.framgment_container, new UserprofileFragment()).commit();
}
} catch (NullPointerException noIntentExtra) {
getSupportFragmentManager().beginTransaction().replace(R.id.framgment_container, new AssignmentsFragment()).commit();
}
if (mAuth.getCurrentUser() != null){
updateUI();
}
}
And the updateUI function is as follows.
public void updateUI() {
TextView textView = findViewById(R.id.textview_assignemntsheader);
textView.setText("Test");
}
Here's the layout for my fragment, that is fragment_assignments.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">
<TextView
android:id="#+id/textview_assignemntsheader"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:text="#string/textview_assigmentsHeader"
android:textAlignment="center"
android:textAppearance="#style/TextAppearance.AppCompat.Display1"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginStart="8dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textview_assignemntsheader">
<LinearLayout
android:id="#+id/linearlayout_assignments"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
</ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>
And the layout for my activity is activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout 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/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity"
tools:openDrawer="start">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<FrameLayout
android:id="#+id/framgment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<com.google.android.material.navigation.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/nav_header"
app:menu="#menu/menu" />
</androidx.drawerlayout.widget.DrawerLayout>

you can't find your textView in MainActivity because it is not in the main_activity.xml, so updateUI should be in UserProfile Fragment.
in OnCreateView
try this :
View view = inflater.inflate(R.layout.fragment_assignments, container,false);
TextView text=view.findViewById(R.id.textview_assignemntsheader);

Where do you inflate fragment_assignments.xml?
in this line, you inflate main_activity.xml
setContentView(R.layout.activity_main);
But, textview_assignemntsheader is in another XML file and can`t find it and returns null.
findViewById will search for ID only in the inflated view.
Move UpdateUI function to UserProfile (where fragment_assignments.xml is inflated)

In your MainActivity you are inflating the activity_main layout which does not have the TextView. Hence you are getting the NullPointerException while trying to find the TextView and assign some text to it.
In the onCreate method of your MainActivity class tries to set a text to a TextView which is not there or not inflated. The fragment_assignments.xml layout might be inflated in your fragment, and hence you will find the layout reference there in your fragment.
Looks like you want to pass the auth information to your fragment and set some value there. In that case, you can just pass the information using a bundle while doing the fragment transaction.
Hence, you might have the following function for your fragment transaction in your activity.
public void launchAssignmentFragment() {
AssignmentFragment frag = new AssignmentFragment();
Bundle bundle = new Bundle();
if (mAuth.getCurrentUser() != null) {
bundle.putBoolean("auth", true);
} else {
bundle.putBoolean("auth", false);
}
// set Arguments to be passed to the fragment
frag.setArguments(bundle);
// Now load the fragment
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, frag);
transaction.addToBackStack(null);
transaction.commit();
}
Now from the onCreateView of your fragment, you can do something like this.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout. fragment_assignments, parent, false);
TextView tv = rootView.findViewById(R.id.textview_assignemntsheader);
// Get the passed-in value here
boolean auth = getArguments().getBoolean("auth");
if (auth) tv.setText("Success");
else tv.setText("Fail");
return rootView;
}
And finally, update your onCreate in the MainActivity as follows.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mAuth = FirebaseAuth.getInstance();
nav_view = findViewById(R.id.nav_view);
nav_view.setNavigationItemSelectedListener(this);
drawer = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.nav_drawer_open, R.string.nav_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
try {
Intent intent = getIntent();
if (intent.getStringExtra("activity").equals("register")) {
getSupportFragmentManager().beginTransaction().replace(R.id.framgment_container, new UserprofileFragment()).commit();
}
} catch (NullPointerException noIntentExtra) {
getSupportFragmentManager().beginTransaction().replace(R.id.framgment_container, new AssignmentsFragment()).commit();
}
if (mAuth.getCurrentUser() != null){
launchAssignmentFragment(); // launch the fragment maybe?
}
}
I hope that helps!

Related

No view found for id 0x7f0800be (com.example.progetto:id/fragment_container_view) for fragment HomeFragment{xx} (xxxx id=0x7f0800be tag=HomeFragment)

I've read these questions/answers:
Android Fragment no view found for ID?
No view found for id for fragment
java.lang.IllegalArgumentException: No view found for id 0x1020002 (android:id/content) for fragment
IllegalArgumentException: No view found for id for fragment
But I couldn't really solve my problem, so here I am asking you!
activity_main.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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<include layout="#layout/topbar"/>
<include layout="#layout/card_layout"/>
<include layout="#layout/buttons"/>
<androidx.fragment.app.FragmentContainerView
android:id="#+id/fragment_container_view"
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>
MainActivity.onCreate()
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//if there was no configuration change, create the fragment
if (savedInstanceState == null)
Utilities.insertFragment(this, new HomeFragment(), FRAGMENT_TAG_HOME);
addViewModel = new ViewModelProvider(this).get(AddViewModel.class);
}
part of AddFragment.java
snackbar = Snackbar.make(activity.findViewById(R.id.fragment_container_view),
"No Internet Available",
Snackbar.LENGTH_INDEFINITE)
.setAction(R.string.settings, new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_WIRELESS_SETTINGS);
intent.setFlags(FLAG_ACTIVITY_NEW_TASK);
if (intent.resolveActivity(activity.getPackageManager()) != null) {
activity.startActivity(intent);
}
}
});
insertFragment method from Utilities.java
static void insertFragment(AppCompatActivity activity, Fragment fragment, String tag) {
FragmentTransaction transaction = activity.getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container_view with this fragment,
transaction.replace(R.id.fragment_container_view, fragment, tag);
//add the transaction to the back stack so the user can navigate back
if (!(fragment instanceof HomeFragment) && !(fragment instanceof SettingsFragment)) {
transaction.addToBackStack(tag);
}
// Commit the transaction
transaction.commit();
}
I know the linked questions are similars but I couldn't solve my situation
Here's my logcat:
Process: com.example.progetto, PID: 32561
java.lang.IllegalArgumentException: No view found for id 0x7f0800be (com.example.progetto:id/fragment_container_view) for fragment HomeFragment{162338d} (62f9659c-9c9e-4173-977c-2f61675677bd id=0x7f0800be tag=HomeFragment)
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:513)
at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:282)
at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:2189)
at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:2100)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:2002)
at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:3134)
at androidx.fragment.app.FragmentManager.dispatchActivityCreated(FragmentManager.java:3068)
at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:251)
at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:501)
at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:210)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1433)
at android.app.Activity.performStart(Activity.java:7924)
at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3332)
at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:221)
at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:201)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:173)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2044)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:224)
at android.app.ActivityThread.main(ActivityThread.java:7560)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)

Java Null Pointer Exception on 'android.view.Window$Callback android.view.Window.getCallback()'

I was trying to add a collapsing Toolbar to a Fragment, but the app crashed as soon as I opened the Fragment:
This is the error I get:
2018-10-19 18:05:38.950 13301-13301/io.github.davidwickerhf.diceroller E/AndroidRuntime: FATAL EXCEPTION: main
Process: io.github.davidwickerhf.diceroller, PID: 13301
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
at androidx.appcompat.app.AppCompatDelegateImpl.<init>(AppCompatDelegateImpl.java:249)
at androidx.appcompat.app.AppCompatDelegate.create(AppCompatDelegate.java:182)
at androidx.appcompat.app.AppCompatActivity.getDelegate(AppCompatActivity.java:520)
at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:191)
at io.github.davidwickerhf.diceroller.ProfileFragment.onCreateView(ProfileFragment.java:36)
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:809)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:166)
at android.app.ActivityThread.main(ActivityThread.java:7436)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:469)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:963)
Fragment Java:
public class ProfileFragment extends Fragment {
private MainActivity mMainActivity;
private SettingsViewModel settingsViewModel;
private SettingAdapter adapter;
private CoordinatorLayout coordinatorLayout;
private View fragmentView;
private TabLayout mTabLayout;
private ViewPager mViewPager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
fragmentView = inflater.inflate(R.layout.fragment_profile, container, false);
mMainActivity = new MainActivity();
androidx.appcompat.widget.Toolbar mToolbar = fragmentView.findViewById(R.id.profile_toolbar);
mMainActivity.setSupportActionBar(mToolbar);
mViewPager = (ViewPager) fragmentView.findViewById(R.id.viewpager);
ViewPagerAdapter adapter = new ViewPagerAdapter(mMainActivity.getSupportFragmentManager());
adapter.AddFragment(new ProfileInfoFragment(), "Profile");
adapter.AddFragment(new ProfileMessagingFragment(), "Messages");
mViewPager.setAdapter(adapter);
mTabLayout = (TabLayout) fragmentView.findViewById(R.id.tab_layout_profile);
mTabLayout.setupWithViewPager(mViewPager);
return fragmentView;
}
}
The Fragment 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"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".ProfileFragment"
android:orientation="vertical">
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/appBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme"
app:toolbarId="#id/profile_toolbar">
<com.google.android.material.appbar.CollapsingToolbarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
app:titleEnabled="false">
<ImageView
android:id="#+id/background_image_Toolbar"
android:layout_width="match_parent"
android:layout_height="256dp"
android:fitsSystemWindows="true"
android:scaleType="centerCrop"
app:layout_collapseMode="parallax" />
<androidx.appcompat.widget.Toolbar
android:layout_marginTop="24dp"
android:id="#+id/profile_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:popupTheme="#style/AppTheme" />
</com.google.android.material.appbar.CollapsingToolbarLayout>
<com.google.android.material.tabs.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="fill"
app:tabMode="fixed"
android:id="#+id/tab_layout_profile"
app:tabTextColor="#color/greyText"
app:tabIndicatorColor="#color/greyText"
android:background="#fafafa"
android:elevation="0dp">
</com.google.android.material.tabs.TabLayout>
</com.google.android.material.appbar.AppBarLayout>
<androidx.viewpager.widget.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/viewpager">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.viewpager.widget.ViewPager>
Please help?
I guess you are getting that error because you are instantiating a new MainActivity object:
mMainActivity = new MainActivity();
In case of Fragments, you can call getActivity() to get the reference of the activity that is hosting your Fragment. Something like:
private MainActivity mMainActivity;
....
mMainActivity = (MainActivity) getActivity();
Or, you don't even need to cast to MainActivity since you are invoking a common method (available on Activity)
private Activity mMainActivity;
....
mMainActivity = getActivity();

Crash on Rotation with this error: Fragment has not been attached yet

i have an Activity with 02 tabLayout
i added First Fragment in my first tab, every thing was just fine since i added my Second Fragment in second tab
my Second Fragment works but when i rotate the device it'll be crash, here is my codes and logCat..
i tried to attach my FragmentTwo to my MainActivity in different ways.. can anybody tell me what's wroNg && how can i do this correctly?
Thanks in advancE.
Main Activity:
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private TabLayout tabLayout;
private ViewPager viewPager;
private int[] tabIcons = {
R.drawable.ic_tab_note,
R.drawable.ic_tab_calendar
};
private static final int TIME_DELAY = 2000;
private static long back_pressed;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//////// TOOLBAR
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setHomeAsUpIndicator(R.drawable.ic_menu);
actionBar.setDisplayHomeAsUpEnabled(true);
///////// DRAWER
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView navigationView =
(NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener
(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
mDrawerLayout.closeDrawers();
Toast.makeText(MainActivity.this,
menuItem.getTitle(),
Toast.LENGTH_LONG).show();
return true;
}
});
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tablayout);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new FragmentOne(), "ONE");
adapter.addFragment(new FragmentTwo(), "TWO");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
// return mFragmentTitleList.get(position);
return null;
}
}
}
FragmentTwo:
import ir.mirrajabi.persiancalendar.PersianCalendarView;
import ir.mirrajabi.persiancalendar.core.PersianCalendarHandler;
import ir.mirrajabi.persiancalendar.core.interfaces.OnDayClickedListener;
import ir.mirrajabi.persiancalendar.core.interfaces.OnMonthChangedListener;
import ir.mirrajabi.persiancalendar.core.models.CalendarEvent;
import ir.mirrajabi.persiancalendar.core.models.PersianDate;
public class FragmentTwo extends Fragment {
private View view;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_two_layout,
container, false);
final PersianCalendarView persianCalendarView = (PersianCalendarView) view.findViewById(R.id.persian_calendar);
final PersianCalendarHandler calendar = persianCalendarView.getCalendar();
final PersianDate today = calendar.getToday();
calendar.addLocalEvent(new CalendarEvent(
today, "Custom event", false
));
calendar.addLocalEvent(new CalendarEvent(
today.clone().rollDay(2, true), "Custom event 2", true
));
calendar.setOnMonthChangedListener(new OnMonthChangedListener() {
#Override
public void onChanged(PersianDate date) {
Toast.makeText(getActivity(), calendar.getMonthName(date), Toast.LENGTH_SHORT).show();
}
});
persianCalendarView.setOnDayClickedListener(new OnDayClickedListener() {
#Override
public void onClick(PersianDate date) {
for (CalendarEvent e : calendar.getAllEventsForDay(date))
Toast.makeText(getActivity(), e.getTitle(), Toast.LENGTH_LONG).show();
calendar.addLocalEvent(new CalendarEvent(
today.clone().rollDay(2, false), "Some event that will be added in runtime", false
));
persianCalendarView.update();
}
});
calendar.setHighlightOfficialEvents(false);
TextView txtDayMonth = (TextView) view.findViewById(R.id.txt_day_month);
TextView txtYear = (TextView) view.findViewById(R.id.txt_year);
String dayAndMonth = calendar.getWeekDayName(today) + calendar.formatNumber(today.getDayOfMonth())
+ calendar.getMonthName(today);
txtDayMonth.setText(dayAndMonth);
txtYear.setText(calendar.formatNumber(today.getYear()));
calendar.setColorBackground(getResources().getColor(android.R.color.holo_blue_dark));
persianCalendarView.update();
return view;
}
}
and here is my activity_main.xml :
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<RelativeLayout
android:id="#+id/base2"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.Dark"/>
<android.support.design.widget.TabLayout
android:id="#+id/tablayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
app:tabGravity="fill"
android:theme="#style/ThemeOverlay.AppCompat.Dark"/>
<RelativeLayout
android:id="#+id/relativee"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
layout_weight="1"/>
</RelativeLayout>
</LinearLayout>
</RelativeLayout>
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/drawer_header"
app:menu="#menu/drawer"/>
</android.support.v4.widget.DrawerLayout>
and here is fragment_two_layout.xml :
<LinearLayout
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"
android:background="#color/colorPrimaryDark"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="24dp">
<ir.mirrajabi.persiancalendar.PersianCalendarView
android:id="#+id/persian_calendar"
android:layout_width="match_parent"
android:layout_height="290sp"
app:pcv_colorBackground="#292929"
app:pcv_colorDayName="#bab6b6"
app:pcv_colorHoliday="#ffd506"
app:pcv_colorHolidaySelected="#f1f2f3"
app:pcv_colorNormalDaySelected="#d9d9d9"
app:pcv_colorNormalDay="#f3f4f5"
app:pcv_eventUnderlineColor="#02f0f0"
app:pcv_fontSize="20sp"
app:pcv_headersFontSize="14sp"/>
</android.support.v7.widget.CardView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginBottom="8dp">
<TextView
android:id="#+id/txt_day_month"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/colorAccent"
android:layout_gravity="center_horizontal"
android:textSize="30sp"/>
<TextView
android:id="#+id/txt_year"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:textColor="#color/colorAccent"
android:textSize="20sp"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal">
<Button
android:id="#+id/change_to_ad"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change to Gregorian Calendar"
android:textSize="14dp"/>
</LinearLayout>
</LinearLayout>
logCat:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.drgnme.listhamrah/com.drgnme.listhamrah.MainActivity}: java.lang.IllegalStateException: Fragment has not been attached yet.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2434)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2494)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4095)
at android.app.ActivityThread.access$1000(ActivityThread.java:153)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1353)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5451)
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.IllegalStateException: Fragment has not been attached yet.
at android.support.v4.app.Fragment.instantiateChildFragmentManager(Fragment.java:2195)
at android.support.v4.app.Fragment.getChildFragmentManager(Fragment.java:745)
at ir.mirrajabi.persiancalendar.core.fragments.CalendarFragment.createViewPagers(CalendarFragment.java:55)
at ir.mirrajabi.persiancalendar.core.fragments.CalendarFragment.access$000(CalendarFragment.java:27)
at ir.mirrajabi.persiancalendar.core.fragments.CalendarFragment$1.update(CalendarFragment.java:46)
at ir.mirrajabi.persiancalendar.PersianCalendarView.update(PersianCalendarView.java:116)
at com.drgnme.listhamrah.FragmentTwo.onCreateView(FragmentTwo.java:87)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2239)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1332)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1574)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1641)
at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:2959)
at android.support.v4.app.FragmentController.dispatchActivityCreated(FragmentController.java:201)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:550)
at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:177)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1238)
at android.app.Activity.performStart(Activity.java:6340)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2397)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2494) 
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4095) 
at android.app.ActivityThread.access$1000(ActivityThread.java:153) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1353) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5451) 
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)
Move all the below code to onActivityCreated():
final PersianCalendarView persianCalendarView = (PersianCalendarView) view.findViewById(R.id.persian_calendar);
final PersianCalendarHandler calendar = persianCalendarView.getCalendar();
final PersianDate today = calendar.getToday();
calendar.addLocalEvent(new CalendarEvent(
today, "Custom event", false
));
calendar.addLocalEvent(new CalendarEvent(
today.clone().rollDay(2, true), "Custom event 2", true
));
calendar.setOnMonthChangedListener(new OnMonthChangedListener() {
#Override
public void onChanged(PersianDate date) {
Toast.makeText(getActivity(), calendar.getMonthName(date), Toast.LENGTH_SHORT).show();
}
});
persianCalendarView.setOnDayClickedListener(new OnDayClickedListener() {
#Override
public void onClick(PersianDate date) {
for (CalendarEvent e : calendar.getAllEventsForDay(date))
Toast.makeText(getActivity(), e.getTitle(), Toast.LENGTH_LONG).show();
calendar.addLocalEvent(new CalendarEvent(
today.clone().rollDay(2, false), "Some event that will be added in runtime", false
));
persianCalendarView.update();
}
});
calendar.setHighlightOfficialEvents(false);
TextView txtDayMonth = (TextView) view.findViewById(R.id.txt_day_month);
TextView txtYear = (TextView) view.findViewById(R.id.txt_year);
String dayAndMonth = calendar.getWeekDayName(today) + calendar.formatNumber(today.getDayOfMonth())
+ calendar.getMonthName(today);
txtDayMonth.setText(dayAndMonth);
txtYear.setText(calendar.formatNumber(today.getYear()));
calendar.setColorBackground(getResources().getColor(android.R.color.holo_blue_dark));
persianCalendarView.update();
It is a best practice not do any works other than inflating the layout inside onCreateView()
Just move the persianCalendarView.update() line inside your FragmentTwo's onAttach and remove it from onCreate() :
#Override
public void onAttachFragment(Fragment childFragment) {
super.onAttachFragment(childFragment);
persianCalendarView.update();
}
Also remove the update() from the inside of persianCalendarView's OnDayClickedListener. I added that line when I was testing and forgot to remove that from the sample app. You don't have to update persianCalendarView unless you need to change the theme or when adding events in runtime.
Problem is not in your app, Problem is in PersianCalendar Lib,
You are inflating PersianCalendarView in your layout in the Fragment class if you check their implementation in PersianCalendarView.java, 1. they are inflating one layout and they are trying to add one Fragment in that layout in that FragmentManager and its working fine. 2. but not only that in that Fragment they are trying to add ViewPager using getChildFragmentManager() Problem comes her only.
You can ask why? In already one FragmentManager added this Fragment that time its working fine but now it's crashing, For that, you can check the difference between that 2 FragmnetManger in this S0 Answer
For this problem, you can do 3 things,
1. You can create ticket to them and wait for the result
2. You can fix that issue
3. Instead of Adding in Layout, Just Create one ViewGroup in Fragment and when onActivtyCreated called you can Add that layout runtime.
EDITED
I tried that sample, And I tried to add it in Fragment, Problem I faced is, Actually the CalendarView fragment is not attached even though our Fragment attached to the Activity, So as I Mentioned in Solution 3 that we can add it in onActivtyCreated that is wrong.
Then how we can solve temporarily?
I solved by adding the view in onStart(I know this is the wrong place this will call multiple time in the life cycle of Fragment), but we can add some logic and we can add this calendar view only once for making it work now till the dev fix in their lib.
My sample :
My fragment Layout:
<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="ir.mirrajabi.pc.sample.BlankFragment">
<LinearLayout
android:id="#+id/calendar_container"
android:layout_width="match_parent"
android:layout_height="290dp"
android:orientation="vertical"/>
<TextView
android:id="#+id/txt_day_month"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:textColor="#f0f2f3"
android:textSize="30sp"/>
<TextView
android:id="#+id/txt_year"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:textColor="#c6d9e2"
android:textSize="20sp"/>
</FrameLayout>
Fragment code
public class BlankFragment extends Fragment {
private LinearLayout mLinearLayout;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_blank, container, false);
mLinearLayout= (LinearLayout) view.findViewById(R.id.calendar_container);
return view;
}
#Override
public void onStart() {
super.onStart();
final PersianCalendarView persianCalendarView = new PersianCalendarView(getContext());
// All your remaining PersianCalendarView implementation code here
mLinearLayout.addView(persianCalendarView);
}
}
Note:
If you take above approach, Please add some logic and make sure it's
not adding multiple time when onStart calls in the Fragment.

Show google map with drawer

We have different differnet activities of google map ( Some with tabs, Some simple, And some other activities), So we are are trying to implement navigation drawer in our app, For this we created a class which extend ActionBarActivity and has drawer, And we are extending this main activity in our classes for navigation drawer, But when we open our application its showing map is null.
Please help.
Here is our files
drawerlist.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FA0"
android:id="#+id/toolbar"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
/>
<FrameLayout
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<android.support.design.widget.NavigationView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:id="#+id/shitstuff"
app:itemTextColor="#000"
app:menu="#layout/drawermenu"
android:layout_marginTop="-24dp"
/>
</android.support.v4.widget.DrawerLayout>
mapload.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ffc17540"
android:id="#+id/maptab"
>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/map"
android:layout_width="fill_parent"
android:gravity="bottom"
android:layout_height="fill_parent"
/>
<RelativeLayout
android:id="#+id/slidingContainer"
android:layout_width="fill_parent"
android:gravity="bottom"
android:layout_height="fill_parent">
<LinearLayout
android:id="#+id/t"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ffff773c"
android:orientation="horizontal">
<RadioGroup
android:id="#+id/rg_views"
android:orientation="horizontal"
android:gravity="bottom"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true">
<RadioButton
android:id="#+id/rb_normal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/str_rb_normal"
android:checked="true" />
<RadioButton
android:id="#+id/rb_satellite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/str_rb_satellite" />
<RadioButton
android:id="#+id/rb_terrain"
android:layout_width="161dp"
android:layout_height="wrap_content"
android:text="#string/str_rb_terrain" />
</RadioGroup>
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:id="#+id/inhorizontalscrollview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageButton"
android:src="#android:drawable/ic_input_add" />
</LinearLayout>
</HorizontalScrollView>
</LinearLayout>
<View
android:id="#+id/transparentView"
android:visibility="gone"
android:layout_width="fill_parent"
android:layout_height="#dimen/map_height"
android:layout_alignParentTop="true"/>
</RelativeLayout>
</RelativeLayout>
BaseActivity.java
public class BaseActivity extends ActionBarActivity
{
public DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.drawer_list);
// Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
// You were missing this setHomeAsUpIndicator
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_navigation_drawer);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView n = (NavigationView) findViewById(R.id.shitstuff);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout , R.string.drawer_open, R.string.drawer_close)
{
/*
* Called when a drawer has settled in a completely closed state
*/
public void onDrawerClosed(View view)
{
Log.d("drawerToggle", "Drawer closed");
super.onDrawerClosed(view);
// getActionBar().setTitle(R.string.app_name);
invalidateOptionsMenu(); //Creates call to onPrepareOptionsMenu()
}
/*
* Called when a drawer has settled in a completely open state
*/
public void onDrawerOpened(View drawerView)
{
Log.d("drawerToggle", "Drawer opened");
super.onDrawerOpened(drawerView);
// getActionBar().setTitle("NavigationDrawer");
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
n.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
////.......
}
mDrawerLayout.closeDrawers(); // CLOSE DRAWER
return true;
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// THIS IS YOUR DRAWER/HAMBURGER BUTTON
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START); // OPEN DRAWER
return true;
}
return super.onOptionsItemSelected(item);
}
}
Mylocation.java
public class MyLocation extends BaseActivity implements View.OnClickListener,OnMapReadyCallback {
GoogleMap googleMap;
#Override
public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
super.onCreate(savedInstanceState);
LayoutInflater inflater = (LayoutInflater)getApplicationContext().getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.mapload, null, false); // line no-74
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
But everytime i run application i am getting this error
java.lang.RuntimeException: Unable to start activity ComponentInfo{MyLocation}: android.view.InflateException: Binary XML file line #24: Binary XML file line #24: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3254)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3350)
at android.app.ActivityThread.access$1100(ActivityThread.java:222)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1795)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7237)
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)
Caused by: android.view.InflateException: Binary XML file line #24: Binary XML file line #24: Error inflating class fragment
at android.view.LayoutInflater.inflate(LayoutInflater.java:551)
at android.view.LayoutInflater.inflate(LayoutInflater.java:429)
at com.myapp.gps.MyLocation.onCreate(MyLocation.java:74) //error here
at android.app.Activity.performCreate(Activity.java:6876)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1135)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3207)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3350) 
at android.app.ActivityThread.access$1100(ActivityThread.java:222) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1795) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:158) 
at android.app.ActivityThread.main(ActivityThread.java:7237) 
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) 
Caused by: android.view.InflateException: Binary XML file line #24: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:788)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:716)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:847)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:810)
at android.view.LayoutInflater.inflate(LayoutInflater.java:527)
at android.view.LayoutInflater.inflate(LayoutInflater.java:429) 
at com.myapp.gps.MyLocation.onCreate(MyLocation.java:74)  //error here
at android.app.Activity.performCreate(Activity.java:6876) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1135) 
What I tried:-
inflater.from(getApplicationContext()).inflate(R.layout.mapload, pageHolder, true);
GoogleMap mapFragment =((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap(); //getting null pointer exception here
another thing which I tried
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, mapFragment).commit(); //same null pointer exception
The line with inflater.inflate is doing nothing useful there in that class. The XML layout isn't loaded and findFragmentById(R.id.map) is returning your null.
I think you wanted something like
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
setContentView(R.layout.mapload);
// Find fragment here
}
Or maybe you maybe you just wanted setContentView from the parent class?
Basically, the error is saying your <fragment> tag is missing a class.
<fragment
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/map"
android:layout_width="fill_parent"
<!-- Needs a class or name attribute -->
android:gravity="bottom"
android:layout_height="fill_parent" />
For example, from the documentation
<fragment
class="com.google.android.gms.maps.SupportMapFragment"
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
(Also worth mentioning that xmlns:android only is to be applied to the root xml element)
Though, I do not think you need a whole separate Activity or layout.
Load the map fragment into this FrameLayout
<FrameLayout
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
just like any regular Fragment...
SupportMapFragment mapFragment = new SupportMapFragment();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content, mapFragment)
.commit();
mapFragment.getMapAsync(this);
add this line to your xml:
android:name="com.google.android.gms.maps.SupportMapFragment"
like this:
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/map"
android:layout_width="fill_parent"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:gravity="bottom"
android:layout_height="fill_parent"/>
and the best way to implement google map with drawer is to use fragment, that's mean change your class "MyLocation" to extends from fragment

NullPointerException with onClickListener for elements in Fragment

I'm having a hell of a time getting fragments to work. The basis of this is to lave a login screen (fragment) appear by default when LoginActivity is created. The fragment has an TextView that when clicked, is supposed to launch a new fragment (form for lost password). I keep getting a NullPointerException when calling forgottenPassword.setOnClickListener from LoginActivity.
The project crashes before I can tell if anything else works.
I'm sure there's some glaring newbie error in here somewhere...
onCreate method from LoginActivity.java:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
if (savedInstanceState == null) {
FragmentManager fragmentManager = getFragmentManager();
int fragmentTransaction = fragmentManager.beginTransaction()
.add(R.id.login_screen_fragment, new FragmentLogin())
.commit();
}
// Listen for FORGOTTEN PASSWORD click event, open ForgottenPassword Fragment //
final TextView forgottenPassword = (TextView) findViewById(R.id.button_lost_pass);
forgottenPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do what I need this to do...
}
});
}
layout_login.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/login_screen_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".LoginActivity"
/>
fragment_login:
<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="come.xxxx.xxxx.ForgottenPasswordFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/login_email"
android:id="#+id/login_forgot"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:text="#string/login_send_lost_pass"
android:id="#+id/button_lost_pass"
/>
</LinearLayout>
</FrameLayout>
fragment_lost_password.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.xxxx.xxx.FragmentLogin">
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fitsSystemWindows="true">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="20dp"
android:orientation="vertical"
android:layout_gravity="center"
android:focusable="true"
android:focusableInTouchMode="true">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="I forgot my password"
android:gravity="center"
android:layout_marginTop="32dp"
android:padding="8dp"
android:textSize="16sp"
android:id="#+id/login_forgot"
/>
</LinearLayout>
</ScrollView>
</FrameLayout>
FragmentLogin.java:
public class FragmentLogin extends Fragment {
public FragmentLogin() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_login, container, false);
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
final Activity activity = getActivity();
}
}
FragmentLostPassword.java
public class FragmentForgottenPassword extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_forgotten_password, container, false);
}
}
Error Trace:
05-13 12:49:37.222 15163-15163/com.xxxxx.xxxxx E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.xxxxx.xxxxx, PID: 15163
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.xxxxx.xxxxx/com.xxxxx.xxxxx.LoginActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
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)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.xxxxx.xxxxx.LoginActivity.onCreate(LoginActivity.java:51)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
at android.app.ActivityThread.access$800(ActivityThread.java:151) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
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) 
05-13 12:50:28.592 15163-15173/com.xxxxx.xxxxx W/art: Suspending all threads took: 15.077ms
05-13 12:50:44.622 15163-15163/? I/Process: Sending signal. PID: 15163 SIG: 9
You have to find the View in your Fragment's layout.
Use the following in your FragmentLogin class:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_login, container, false);
final TextView forgottenPassword = (TextView) view.findViewById(R.id.button_lost_pass);
// Set your onClickListener here
return view;
}
Actually, your fragment might be not accessible when you assign forgetpassword , you can use the following for layout_login.xml:
<fragment
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:name="FragmentLogin"
tools:layout="#layout/fragment_login"
/>
Note you may have to define the right path to FragmentLogin.
This is the new way to work with fragment, that will load your Login fragment automatically without writing anything in onCreate.
Also, it's not a TextView but a Button
Finally, remove the Fragment Transaction code.
Another option, is to move your forgot password button login to FragmentLogin. Because basically you try to access Fragment related element from the activity. Everything should be in your fragment.
You can still access the fragment manager with getActivity().getFragmentManger(), to load the lost_password layout.
What is the activity_login.xml content. I guest wrong id of button button_lost_pass
Inside oncreate() method you called new Fragment but the fragment layout(layout_lost_password) does not contain the id(R.id.button_lost_pass)
Change :
final TextView forgottenPassword = (TextView) findViewById(R.id.button_lost_pass);
To
final Button forgottenPassword = (Button) findViewById(R.id.button_lost_pass);

Categories