I'm making an app that uses Android studio to write and call messages. This error message appears during the process of inflating the recycler view into the fragment.
How can I fix it? Why can't this be inflated?
here is error messages...
java.lang.RuntimeException: Unable to start activity ComponentInfo{kr.hnu.project/kr.hnu.project.NavigationActivity}: android.view.InflateException: Binary XML file line #11 in kr.hnu.project:layout/activity_navigation: Binary XML file line #10 in kr.hnu.project:layout/content_navigation: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3270)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
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)
Caused by: android.view.InflateException: Binary XML file line #11 in kr.hnu.project:layout/activity_navigation: Binary XML file line #10 in kr.hnu.project:layout/content_navigation: Error inflating class fragment
Caused by: android.view.InflateException: Binary XML file line #10 in kr.hnu.project:layout/content_navigation: Error inflating class fragment
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void kr.hnu.project.MyRecyclerAdapter.notifyDataSetChanged()' on a null object reference
at kr.hnu.project.ui.home.HomeFragment.setArray(HomeFragment.java:83)
at kr.hnu.project.ui.home.HomeFragment.onCreateView(HomeFragment.java:52)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2995)
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:523)
at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:261)
at androidx.fragment.app.FragmentStore.moveToExpectedState(FragmentStore.java:113)
and this HomeFragment that the recycler view should see.
public class HomeFragment extends Fragment {
private final static String selectMsg = "SELECT sender, receiver, title, date, content FROM MessageDB";
RelativeLayout rel;
LinearLayout lin;
DBHelper dbHelper;
SQLiteDatabase readDB;
Cursor cursor;
ArrayList<MyItem> mailItem;
MyRecyclerAdapter myAdapter;
private FragmentHomeBinding binding;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
HomeViewModel homeViewModel =
new ViewModelProvider(this).get(HomeViewModel.class);
binding = FragmentHomeBinding.inflate(inflater, container, false);
View root = binding.getRoot();
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_home, container, false);
dbHelper = new DBHelper(inflater.getContext());
readDB = dbHelper.getReadableDatabase();
mailItem = new ArrayList<MyItem>();
setArray();
myAdapter = new MyRecyclerAdapter(getActivity(), mailItem);
RecyclerView recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(myAdapter);
return root;
}
public void setArray() {
cursor = readDB.rawQuery(selectMsg, null);
mailItem.clear();
while (cursor.moveToNext()) {
mailItem.add(new MyItem(cursor.getString(cursor.getColumnIndexOrThrow("sender")), cursor.getString(cursor.getColumnIndexOrThrow("receiver")),
cursor.getString(cursor.getColumnIndexOrThrow("title")), cursor.getString(cursor.getColumnIndexOrThrow("date")),
cursor.getString(cursor.getColumnIndexOrThrow("content"))));
}
cursor.close();
//myAdapter.notifyDataSetChanged();
}
This is Navigation Activity with home fragment.
public class NavigationActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
private AppBarConfiguration mAppBarConfiguration;
private ActivityNavigationBinding binding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dataToFragment();
binding = ActivityNavigationBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
setSupportActionBar(binding.appBarNavigation.toolbar);
DrawerLayout drawer = binding.drawerLayout;
NavigationView navigationView = binding.navView;
navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_send, R.id.nav_set, R.id.nav_home)
.setOpenableLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_navigation);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
}
this is activity_navigation.xml in error message
<?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:openDrawer="start">
<include
android:id="#+id/app_bar_navigation"
layout="#layout/app_bar_navigation"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<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"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_navigation"
app:menu="#menu/activity_navigation_drawer" />
</androidx.drawerlayout.widget.DrawerLayout>
this is content_navigation.xml in error message
<?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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/app_bar_navigation">
<fragment
android:id="#+id/nav_host_fragment_content_navigation"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:navGraph="#navigation/mobile_navigation" /
</androidx.constraintlayout.widget.ConstraintLayout>
and this is homeFragment's xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/linear"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".ui.home.HomeFragment">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
because my reputation is less then 50 ,I can't comment on your post so i will comment here .
What does this method do? dataToFragment();
you are calling it before inflating the layout
Related
When starting the app, I see neither the recycle view nor the normal fragment. I'm sure that the Navigation switch the fragments but I do not see results. But when I use the saveInstantState I can get the Recycle view to work but I can't switch fragments anymore...
Any help would be great.
Main.java
public class MainActivity extends AppCompatActivity {
MusicStoreService music;
private DrawerLayout drawerLayout;
private NavController navController;
private NavigationView navigationView;
private AppBarConfiguration appBarConfiguration;
public MainActivity() {
super(R.layout.main);
}
#Nullable
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
music = new MusicStoreServiceMock();
setContentView(R.layout.main);
Toolbar toolbar = findViewById(R.id.toolbar);
// make sure you import androidx.appcompat.widget.Toolbar !
setSupportActionBar(toolbar);
drawerLayout = findViewById(R.id.drawer_layout);
navigationView = findViewById(R.id.nav_view);
NavHostFragment navHostFragment = (NavHostFragment)
getSupportFragmentManager()
.findFragmentById(R.id.nav_host_fragment_container);
navController = navHostFragment.getNavController();
Set<Integer> topLevelDestinations = new HashSet<>();
topLevelDestinations.add(R.id.productListFragment2);
topLevelDestinations.add(R.id.helloworld);
appBarConfiguration = new AppBarConfiguration.Builder(topLevelDestinations)
.setOpenableLayout(drawerLayout)
.build();
NavigationUI.setupWithNavController(toolbar, navController,
appBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.setReorderingAllowed(true)
.add(R.id.nav_host_fragment_container, ProductListFragment.class, null)
.commit();
System.out.println();
}
}
public MusicStoreService getMusic() {
return music;
}
}
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"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<androidx.coordinatorlayout.widget.CoordinatorLayout 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"
android:orientation="vertical"
tools:context=".MainActivity">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:layout_scrollFlags="scroll|enterAlways" />
</com.google.android.material.appbar.AppBarLayout>
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<androidx.fragment.app.FragmentContainerView
android:id="#+id/nav_host_fragment_container"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:navGraph="#navigation/nav_graph" />
</androidx.core.widget.NestedScrollView>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
<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"
android:fitsSystemWindows="true"
app:menu="#menu/nav_menu"
/>
<!-- attribute app:menu isn't mentioned in the documentation! -->
</androidx.drawerlayout.widget.DrawerLayout>
menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item android:title="MusicStore">
<menu>
<item
android:id="#+id/productListFragment2"
android:title="Products" />
</menu>
</item>
<item android:title="Service">
<menu>
<item
android:id="#+id/helloworld"
android:title="Your Account" />
</menu>
</item>
</group>
</menu>
nav_graph.xml
<?xml version="1.0" encoding="utf-8"?>
<navigation 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/nav_graph"
app:startDestination="#id/productListFragment2">
<fragment
android:id="#+id/productListFragment2"
android:name="musicstore.fragments.ProductListFragment"
android:label="Product List" >
<action
android:id="#+id/action_productListFragment2_to_mainActivity2"
app:destination="#id/mainActivity2" />
</fragment>
<fragment
android:id="#+id/helloworld"
android:name=".musicstore.fragments.helloworld"
android:label="Your Account"
tools:layout="#layout/fragment_helloworld" />
<fragment
android:id="#+id/productDetailFragment2"
android:name="musicstore.fragments.ProductDetailFragment"
android:label="ProductDetailFragment" />
<activity
android:id="#+id/mainActivity2"
android:name="musicstore.MainActivity"
android:label="activity_main"
tools:layout="#layout/activity_main" />
</navigation>
Recycle view fragment:
public class ProductListFragment extends Fragment {
RecyclerView recyclerView;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
System.out.println("Hello");
View v = inflater.inflate(R.layout.product_list_fragment, container, false);
recyclerView = (RecyclerView) v.findViewById(R.id.productlist_recycler);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
return v;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
ProductListAdapter pld = new ProductListAdapter(((MainActivity) getActivity()).getMusic(),getContext(),new ClickerListener());
recyclerView.setAdapter(pld);
}
Simple fragment:
public class helloworld extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_helloworld, container, false);
}
}
I've been looking for the cause of this exception in answers for similar issues, and couldn't find what's wrong with my code. I changed the method that instantiates a fragment a few times and got the same exception. Maybe it has something to do with the splash screen. Couldn't find information about that.
Here's the beginning of the MainActivity in which the method for instantiating a fragment is called:
public class MainActivity extends AppCompatActivity {
Context context;
FragmentTransaction ft;
Fragment mlf;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
File file = new File(path);
if (file.exists()) {
Log.d(TAG, path + " exists");
new DBConnection(MainActivity.this);
if(savedInstanceState == null) {
toMovieListFragment();
}
//...
//...
Here's the method:
private void toMovieListFragment() {
mlf = new MovieListFragment();
ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.fragments_ontainer, mlf);
ft.addToBackStack(null); // add to back stack
ft.commit();
}
}
The MainActivity's xml:
<?xml version="1.0" encoding="utf-8"?><android.support.design.widget.CoordinatorLayout 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=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/fragments_container">
</LinearLayout>
The fragment class:
public class MovieListFragment extends Fragment {
Context context;
TextView listTtl;
RecyclerView rvMovies;
Adapter moviesAdapter;
List<Movie> moviesList;
Fragment mdf;
FragmentTransaction ft;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_list_movies, container, false);
context = getActivity();
listTtl = rootView.findViewById(R.id.moviesListTtlId);
rvMovies = rootView.findViewById(R.id.moviesRVId);
moviesList = new ArrayList<>();
moviesAdapter = new Adapter(context, moviesList);
rvMovies.setAdapter(moviesAdapter);
// setting a layout manager
rvMovies.setLayoutManager(new LinearLayoutManager(context)); // a regular one
Log.i(TAG,"In movieListFragment");
return rootView;
}
}
The fragment class's xml file:
<?xml version="1.0" encoding="utf-8"?><android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<LinearLayout
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent">
<TextView
android:id="#+id/moviesListTtlId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="#dimen/dot_height"
android:text="#string/moviesListTitle"
android:textAlignment="center"
android:textColor="#color/colorPrimaryDark"
android:textSize="#dimen/ttlSize" />
<android.support.v7.widget.RecyclerView
android:id="#+id/moviesRVId"
android:layout_margin="#dimen/dimen_10"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
<include layout="#layout/change_name" />
Thanks.
For some reason your main activity layout is called R.layout.activity_splash I believe your intention was for it to be whatever main activity layout is called (the one that has R.id.fragments_container inside).
The crash is when i switch the page from 2 to 0 or 1.
And when i Comment the auto Complete Fragment at activity_maps.xml
Please help me.
--------- beginning of crash
12-04 01:31:01.005 12693-12693/com.handsomelee.gotroute E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.handsomelee.gotroute, PID: 12693
android.view.InflateException: Binary XML file line #10: Binary XML file line #10: Error inflating class fragment
Caused by: android.view.InflateException: Binary XML file line #10: Error inflating class fragment
Caused by: java.lang.IllegalArgumentException: Binary XML file line #10: Duplicate id 0x7f0f00e4, tag null, or parent id 0xffffffff with another fragment for com.google.android.gms.location.places.ui.PlaceAutocompleteFragment
at android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2315)
at android.app.FragmentController.onCreateView(FragmentController.java:98)
at android.app.Activity.onCreateView(Activity.java:5901)
at android.support.v4.app.BaseFragmentActivityApi14.onCreateView(BaseFragmentActivityApi14.java:41)
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:67)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:777)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:858)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
at android.view.LayoutInflater.inflate(LayoutInflater.java:518)
at android.view.LayoutInflater.inflate(LayoutInflater.java:426)
at com.handsomelee.gotroute.Services.GoogleMapSystem.onCreateView(GoogleMapSystem.java:41)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2261)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1419)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1750)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:792)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2590)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2377)
at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2332)
at android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:2209)
at android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:649)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:145)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1238)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:663)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:625)
at android.support.v4.view.ViewPager.setCurrentItem(ViewPager.java:617)
at com.handsomelee.gotroute.MainActivity$1.onTabSelected(MainActivity.java:73)
at android.support.design.widget.TabLayout.dispatchTabSelected(TabLayout.java:1165)
at android.support.design.widget.TabLayout.selectTab(TabLayout.java:1158)
at android.support.design.widget.TabLayout.selectTab(TabLayout.java:1128)
at android.support.design.widget.TabLayout$Tab.select(TabLayout.java:1427)
at android.support.design.widget.TabLayout$TabView.performClick(TabLayout.java:1537)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
--------- beginning of system
this is my MainActivity.java
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
if(tab1 == null){
tab1 = new MapsActivity(R.id.mapView, R.layout.activity_maps, GoogleMap.MAP_TYPE_NORMAL);
}
return tab1;
case 1:
if(tab2 == null)
tab2 = new CarParkingActivity();
return tab2;
case 2:
if(tab3 == null)
tab3 = new ReportActivity();
return tab3;
default:
return null;
}
}
#Override
public int getCount() {
return 3;
}
MapsActivity.java
#Override
public View onCreateView(LayoutInflater layoutInflater, ViewGroup viewGroup, Bundle bundle) {
rootView = layoutInflater.inflate(layoutActivityId, viewGroup, false);
mapView = ((MapView) rootView.findViewById(mapViewId));
mapView.onCreate(bundle);
mapView.getMapAsync(this);
addOn();
return rootView;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(googleMapType);
mMap.setOnMyLocationButtonClickListener(this);
mMap.setOnMyLocationClickListener(this);
mMap.setOnMapLongClickListener(this);
}
}
activity_maps.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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="match_parent"
android:layout_height="match_parent"
tools:context="com.handsomelee.gotroute.Controller.ReportActivity">
<fragment
android:layout_width="0dp"
android:layout_height="50dp"
android:name="com.google.android.gms.location.places.ui.PlaceAutocompleteFragment"
android:id="#+id/placeSearch"
android:layout_weight="0.67"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toLeftOf="parent"/>
<com.google.android.gms.maps.MapView
android:layout_width="0dp"
android:layout_height="0dp"
android:id="#+id/mapView"
android:layout_weight="0.78"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:apiKey="#string/test_google_api"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintTop_toBottomOf="#+id/placeSearch"/>
</android.support.constraint.ConstraintLayout>
ReportActivity.java
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_report, container, false);
spinner = (Spinner) rootView.findViewById(R.id.spinner);
String[] array_Spiner = getResources().getStringArray(R.array.reports_array);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(rootView.getContext(), R.layout.support_simple_spinner_dropdown_item, array_Spiner);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
~
});
return rootView;
}
activity_report.xml
<?xml version="1.0" encoding="utf-8"?>`
<android.support.constraint.ConstraintLayout
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="match_parent"
android:layout_height="match_parent"
tools:context="com.handsomelee.gotroute.Controller.ReportActivity">
<Spinner
android:layout_width="0dp"
android:layout_height="50dp"
android:id="#+id/spinner"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:overlapAnchor="false"
android:dropDownWidth="match_parent"
app:layout_constraintHorizontal_bias="0.0"/>
</android.support.constraint.ConstraintLayout>
SOLVED.
The problem seems like is the fragment id duplicated when the view is created.
so I add the Code below at my MapActivity to remove it.
#Override
public void onDestroyView() {
super.onDestroyView();
android.app.FragmentManager fm = getActivity().getFragmentManager();
android.app.Fragment fragment = fm.findFragmentById(R.id.placeSearch);
android.app.FragmentTransaction ft = fm.beginTransaction();
ft.remove(fragment);
ft.commit();
}
Can somebody explain what is the problem here? The error is bellow:
Code in MainAcitivity:
FragmentManager fm = getSupportFragmentManager();
SvePonudeFragment fragment = (SvePonudeFragment) fm.findFragmentById(R.id.ponudice);
fragment.reloadData();
Fragment Class:
public class SvePonudeFragment extends Fragment {
private RecyclerView rv;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.sve_ponude_fragment, container, false);
rv = (RecyclerView) rootView.findViewById(R.id.rv);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
rv.setLayoutManager(llm);
ArrayList<Ponuda> listaPonuda = null;
initializeAdapter(listaPonuda);
return rootView;
}
private void initializeAdapter(List<Ponuda> preuzetePonude){
RVAdapter adapter = new RVAdapter(preuzetePonude);
rv.setAdapter(adapter);
}
public void reloadData(){
System.out.println("I ENTEEERED");
}
}
XML of fragment:
<?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"
android:id="#+id/ponudice">
<android.support.v7.widget.RecyclerView
android:layout_height="match_parent"
android:layout_width="match_parent"
android:id="#+id/rv"
>
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
What is wrong with this? Can somebody explain me?
this is the error:
W/System.err: java.lang.NullPointerException
W/System.err: at com.example.filip.dajsve.Activities.MainActivity.onDataLoaded(MainActivity.java:190)
W/System.err: at com.example.filip.dajsve.Loaders.DatabaseDataLoader.loadData(DatabaseDataLoader.java:22)
I found the problem. The problem is that you don't link your fragment with mainActivity. first you should add your fragment in xml of mainActivty and give the fragment an id then access it in the main activity with the id of fragment not using this id android:id="#+id/ponudice"> because this id related with relative layout not the fragment. check the xml code of main activity you should find fragment tags like code below
<fragment
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:name="theNameOfYourPackage.theNameOfFragment"
android:id="#+id/ponudice_in_main_activity"/>
Do it like this
FragmentManager fm = getSupportFragmentManager();
SvePonudeFragment fragment = new SvePonudeFragment();
fm.beginTransaction().replace(R.id.framecontainer,fragment).commit();
and your activity_main.xml file will be
<FrameLayout 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:id="#+id/framecontainer"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:padding="16dp"
>
</FrameLayout>
I am trying to open an activity which has recyclerView in it on the click of recyclerView of first activity. But now when I'm clicking the recyclerView app is crashing with the following message.
10-18 09:30:49.912 13018-13018/in.mumbaitravellers.mtleaders
E/AndroidRuntime: FATAL EXCEPTION: main
Process: in.mumbaitravellers.mtleaders, PID: 13018
java.lang.RuntimeException: Unable to start activity
ComponentInfo{in.mumbaitravellers.mtleaders/in.mumbaitravellers.mtleaders.activity.DetailActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.support.v7.widget.RecyclerView.setHasFixedSize(boolean)' on a
null object reference
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2426)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'void
android.support.v7.widget.RecyclerView.setHasFixedSize(boolean)' on a
null object reference
at
in.mumbaitravellers.mtleaders.activity.DetailActivity.setupRecycler(DetailActivity.java:120)
at
in.mumbaitravellers.mtleaders.activity.DetailActivity.onCreate(DetailActivity.java:52)
at android.app.Activity.performCreate(Activity.java:6245)
at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1130)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
10-18 09:31:13.376 1801-2412/? E/native: do suspend false
The java code is as follows:
public class DetailActivity extends AppCompatActivity {
private ExpenseAdapter adapter;
private Realm realm;
private LayoutInflater inflater;
private FloatingActionButton fab;
private RecyclerView recycler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
fab = (FloatingActionButton) findViewById(R.id.fab);
recycler = (RecyclerView) findViewById(R.id.recycler);
//get realm instance
this.realm = RealmController.with(this).getRealm();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
/*String event = getIntent().getStringExtra("eventName");
TextView tv = (TextView) findViewById(R.id.txt_EventName);
tv.setText(event);*/
setupRecycler();
if (!Prefs.with(this).getPreLoad()) {
setRealmData();
}
// refresh the realm instance
RealmController.with(this).refresh();
// get all persisted objects
// create the helper adapter and notify data set changes
// changes will be reflected automatically
setRealmAdapter(RealmController.with(this).getExpenses());
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
inflater = DetailActivity.this.getLayoutInflater();
View content = inflater.inflate(R.layout.activity_add_new_expense, null);
final EditText editExpense = (EditText) content.findViewById(R.id.edtxt_expense);
final EditText editDescription = (EditText) content.findViewById(R.id.edtxt_description);
AlertDialog.Builder builder = new AlertDialog.Builder(DetailActivity.this);
builder.setView(content)
.setTitle("Add Expense")
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Expense expense = new Expense();
expense.setId((int) (RealmController.getInstance().getExpenses().size() + System.currentTimeMillis()));
expense.setAmount(editExpense.getText().toString());
expense.setDescription(editDescription.getText().toString());
realm.beginTransaction();
realm.copyToRealm(expense);
realm.commitTransaction();
adapter.notifyDataSetChanged();
// scroll the recycler view to bottom
recycler.scrollToPosition(RealmController.getInstance().getExpenses().size() - 1);
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
});
}
public void setRealmAdapter(RealmResults<Expense> expenses) {
RealmExpenseAdapter realmExpenseAdapter = new RealmExpenseAdapter(this.getApplicationContext(), expenses, true);
adapter.setRealmAdapter(realmExpenseAdapter);
adapter.notifyDataSetChanged();
}
private void setupRecycler() {
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
recycler.setHasFixedSize(true);
// use a linear layout manager since the cards are vertically scrollable
final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recycler.setLayoutManager(layoutManager);
// create an empty adapter and add it to the recycler view
adapter = new ExpenseAdapter(this);
recycler.setAdapter(adapter);
}
private void setRealmData() {
ArrayList<Expense> expenses = new ArrayList<>();
for (Expense e : expenses) {
// Persist your data easily
realm.beginTransaction();
realm.copyToRealm(e);
realm.commitTransaction();
}
Prefs.with(this).setPreLoad(true);
}
}
And the xml file is as follows:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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"
android:fitsSystemWindows="true"
tools:context="in.mumbaitravellers.mtleaders.activity.DetailActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_detail" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#drawable/ic_action_add" />
</android.support.design.widget.CoordinatorLayout>
Recycler View Code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/card_expense"
style="#style/AppTheme.Card.Margins"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/text_amount"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/margin_small"
android:paddingBottom="#dimen/margin_normal"
android:paddingLeft="#dimen/margin_large"
android:paddingRight="#dimen/margin_large"
android:paddingTop="#dimen/margin_large"
android:textColor="#555555"
android:text="\u20B9"
android:textSize="40dp"
android:textStyle="bold" />
<TextView
android:layout_width="match_parent"
android:layout_height="25dp"
android:id="#+id/text_description"
android:textSize="20dp"/>
</LinearLayout>
</android.support.v7.widget.CardView>
Content Detail.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView 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/recyclerExpense"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:showIn="#layout/activity_detail"
tools:context="in.mumbaitravellers.mtleaders.activity.DetailActivity"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
What is wrong in code, please help.
Thanks in advance!
Your problem lies in incorrect search of RecyclerView
Change your code:
recycler = (RecyclerView) findViewById(R.id.recycler);
to
recycler = (RecyclerView) findViewById(R.id.recyclerExpense);