So I'm trying to create a fragment in my app that contains a toolbar (as an action bar) using appcompat activity so I can reuse it across multiple views.
I've tested a simple text-only fragment using a class that extends fragment only and got that to work, but to include a toolbar I need to extend AppCompatActivity in the view (I think).
When I try to get this to work, I get an error that says that my action_bar_fragment is not a Fragment.
I fell like I'm missing something basic here. Any ideas?
Main Activity:
package com.example.aaron.personaldataassistant;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.support.v7.widget.Toolbar;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.view.Menu;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// action_bar_fragment = (Toolbar) findViewById(R.id.action_bar_fragment);
// setSupportActionBar(action_bar_fragment);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater mi=getMenuInflater();
mi.inflate(R.menu.action_bar, menu);
return super.onCreateOptionsMenu(menu);
}
Main Activity Layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
android:id="#+id/activity_main"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.aaron.personaldataassistant.MainActivity">
<fragment
android:id="#+id/action_bar_fragment"
android:layout_width="wrap_content"
android:layout_height="match_parent"
class="com.example.aaron.personaldataassistant.action_bar_fragment"
tools:layout="#layout/action_bar_fragment" />
</LinearLayout>
Action Bar Fragment:
package com.example.aaron.personaldataassistant;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
public class action_bar_fragment extends AppCompatActivity {
public action_bar_fragment() {
}
Toolbar action_bar;
#Nullable
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.action_bar_fragment, container, false);
}
#Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.action_bar_fragment);
action_bar = (Toolbar) findViewById(R.id.action_bar);
setSupportActionBar(action_bar);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.action_bar, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int i = item.getItemId();
if (i == R.id.item1) {
Toast.makeText(action_bar_fragment.this, "Item 1", Toast.LENGTH_SHORT).show();
} else if (i == R.id.item2) {
Toast.makeText(action_bar_fragment.this, "Item 2", Toast.LENGTH_SHORT).show();
} else if (i == R.id.item3) {
Toast.makeText(action_bar_fragment.this, "Item 3", Toast.LENGTH_SHORT).show();
}
//replace toasts with desired actions: Settings, Help and Exit. Settigns is blank, help is context-dependent, exit gives possibility to exit
return super.onOptionsItemSelected(item);
}
}
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"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="layout.Fragment_1">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/hello_blank_fragment" />
<android.support.v7.widget.Toolbar
android:id="#+id/action_bar"
android:layout_width="300dp"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimaryDark"
android:elevation="8dp"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
/>
</FrameLayout>
And of course the error message:
--------- beginning of crash
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.aaron.personaldataassistant, PID: 2481
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.aaron.personaldataassistant/com.example.aaron.personaldataassistant.MainActivity}: android.view.InflateException: Binary XML file line #19: Binary XML file line #19: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: android.view.InflateException: Binary XML file line #19: Binary XML file line #19: Error inflating class fragment
Caused by: android.view.InflateException: Binary XML file line #19: Error inflating class fragment
Caused by: android.app.Fragment$InstantiationException: Trying to instantiate a class com.example.aaron.personaldataassistant.action_bar_fragment that is not a Fragment
at android.app.Fragment.instantiate(Fragment.java:617)
at android.app.Fragment.instantiate(Fragment.java:593)
at android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2302)
at android.app.FragmentController.onCreateView(FragmentController.java:98)
at android.app.Activity.onCreateView(Activity.java:5884)
at android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:36)
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:75)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java: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 android.view.LayoutInflater.inflate(LayoutInflater.java:377)
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:284)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
at com.example.aaron.personaldataassistant.MainActivity.onCreate(MainActivity.java:24)
at android.app.Activity.performCreate(Activity.java:6662)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.ClassCastException
at android.app.Fragment.instantiate(Fragment.java:618)
at android.app.Fragment.instantiate(Fragment.java:593)
at android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2302)
at android.app.FragmentController.onCreateView(FragmentController.java:98)
at android.app.Activity.onCreateView(Activity.java:5884)
at android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:36)
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:75)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java: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 android.view.LayoutInflater.inflate(LayoutInflater.java:377)
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:284)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
at com.example.aaron.personaldataassistant.MainActivity.onCreate(MainActivity.java:24)
at android.app.Activity.performCreate(Activity.java:6662)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Application terminated.
Thank you for your time.
UPDATE
This is great, the top answer helped me figure out that doing things in a fragment can require different methods than doing them in an Activity. Googling "How do I do X in a fragment" turned out to give me almost everything I needed. There is only one problem left now: I changed the Action Bar Fragment line 37 to
setHasOptionsMenu(true);
action_bar = (Toolbar) getView().findViewById(R.id.action_bar);
This is giving me a null object reference, but the layout definitely exists! Any idea what's going on?
The relevant part of the error message is:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
Sorry for the long delay getting back to you, I had work. Should be faster this time!
I will also clean up the comment I made on your reply.
This is because your intended fragment is not a Fragment but an Activity, where:
action_bar_fragment extends AppCompatActivity {
}
is an Activity, so you should be extends action_bar_fragment with Fragment:
action_bar_fragment extends Fragment {
}
And please change your code style, where action_bar_fragment should be something like ActionBarFragment. A class name should be started with uppercase.
Please read Creating and Using Fragments.
I came upon this question because of the main title "Trying to instantiate a class that is not a Fragment". So maybe my solution can help. I'm using Android Studio 2.2.3 and targeting API 15.
I got that error:
...
Caused by: android.app.Fragment$InstantiationException: Trying to instantiate a class com.xyz.tuv.MyFragment that is not a Fragment
because I was importing:
import android.support.v4.app.Fragment;
instead of
import android.app.Fragment;
Since API 11, you can use a regular activity (android.app.Activity) for inserting fragments as documented here. But in that case you also have to use android.app.Fragment, contrary to what the main example shows.
In your MainActivity class, you have to change the order of some of code, they are:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater mi=getMenuInflater();
mi.inflate(R.menu.action_bar, menu);
return super.onCreateOptionsMenu(menu);
}
Change it to :
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.action_bar, menu);
return true;
}
and try again.
Related
I have reviewed multiple solutions to my question, but each attempt results in my android application crashing due to the data being sent returning null. I am attempting to send a ArrayList of Strings to a fragment, but when I launch my application I receive the following error.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.assignment2, PID: 17719
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.assignment2/com.example.assignment2.MainActivity}: android.view.InflateException: Binary XML file line #9 in com.example.assignment2:layout/activity_main: Binary XML file line #9 in com.example.assignment2:layout/activity_main: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: android.view.InflateException: Binary XML file line #9 in com.example.assignment2:layout/activity_main: Binary XML file line #9 in com.example.assignment2:layout/activity_main: Error inflating class fragment
Caused by: android.view.InflateException: Binary XML file line #9 in com.example.assignment2:layout/activity_main: Error inflating class fragment
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.ArrayList android.os.Bundle.getStringArrayList(java.lang.String)' on a null object reference
at com.example.assignment2.TickerListFragment.onCreateView(TickerListFragment.java:21)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2963)
at androidx.fragment.app.FragmentStateManager.ensureInflatedView(FragmentStateManager.java:386)
at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:281)
at androidx.fragment.app.FragmentLayoutInflaterFactory.onCreateView(FragmentLayoutInflaterFactory.java:140)
at androidx.fragment.app.FragmentController.onCreateView(FragmentController.java:135)
at androidx.fragment.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:319)
at androidx.fragment.app.FragmentActivity.onCreateView(FragmentActivity.java:298)
at android.view.LayoutInflater.tryCreateView(LayoutInflater.java:1067)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:995)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:959)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:1121)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1082)
at android.view.LayoutInflater.inflate(LayoutInflater.java:680)
at android.view.LayoutInflater.inflate(LayoutInflater.java:532)
at android.view.LayoutInflater.inflate(LayoutInflater.java:479)
at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:706)
at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:195)
at com.example.assignment2.MainActivity.onCreate(MainActivity.java:18)
at android.app.Activity.performCreate(Activity.java:8000)
at android.app.Activity.performCreate(Activity.java:7984)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
W/System: A resource failed to call close.
The following is my MainActivity class
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.os.Bundle;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayList<String> tickers;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().hide();
tickers = new ArrayList<String>();
tickers.add("BAC");
tickers.add("BTC");
tickers.add("APPL");
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Bundle bundle = new Bundle();
bundle.putStringArrayList("def", tickers);
TickerListFragment list = new TickerListFragment();
list.setArguments(bundle);
fragmentTransaction.replace(R.id.list_fragment, list).commit();
}
}
The following is the XML for the main activity class.
<?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">
<fragment
android:id="#+id/list_fragment"
android:name="com.example.assignment2.TickerListFragment"
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
The following is the fragment class
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;
import androidx.fragment.app.Fragment;
import java.util.ArrayList;
public class TickerListFragment extends Fragment {
ArrayList<String> def_tickers;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle state) {
View view = inflater.inflate(R.layout.fragment_tickerlist, container, false);
def_tickers = this.getArguments().getStringArrayList("def");
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
LinearLayout layout = (LinearLayout) view.findViewById(R.id.list_layout);
}
}
And the following is the XML for the fragment
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/list_layout"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical">
</LinearLayout>
</ScrollView>
If someone could point out my oversight as to why the sent data is being retrieved as null that would be much appreciated.
AFAIK when you use <fragment> in xml it is automatically inflated, when the view is inflated, i.e. setContentView(R.layout.activity_main);
This means the fragment is created before you got the chance to pass in the bundled args.
Back in the day it was standard practice to use a FrameLayout instead like you've stated in your comment. But now it is best to use FragmentContainerView as it respects animations among other things.
<FragmentContainerView
android:id="#+id/list_fragment"
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
HomeFragment.java
package com.example.starcitizen.fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import androidx.fragment.app.Fragment;
import com.example.starcitizen.R;
public class HomeFragment extends Fragment {
public HomeFragment(){ }
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
String url = "http://google.com";
WebView view = (WebView) rootView.findViewById(R.id.home_webview);
view.getSettings().setJavaScriptEnabled(true);
view.loadUrl(url);
return rootView ;
}
}
fragment_home
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.starcitizen.fragment.HomeFragment">
<WebView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/home_webview"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
I looked at other questions. but my app is not works.
So I wonder if I need to fix my main activity. So I attached the main activity.
MainActivity.java
package com.example.starcitizen;
import android.os.Bundle;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.google.android.material.navigation.NavigationView;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.Menu;
public class MainActivity extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_guide, R.id.nav_maps,
R.id.nav_ships, R.id.nav_weapons, R.id.nav_mission)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
}
Sorry I'm not good at english. So with help of a translator...
and I asked stackoverflow for the first time.
I'm working on an app for koreans. but I have some problem in fragment.
If a webview is entered, App will be turned off without running.
please help me.
add logcat!
11-15 20:00:31.465 3666-3666/com.example.starcitizen E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.starcitizen, PID: 3666
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.starcitizen/com.example.starcitizen.MainActivity}: android.view.InflateException: Binary XML file line #8: Error inflating class android.webkit.WebView
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:905)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)
Caused by: android.view.InflateException: Binary XML file line #8: Error inflating class android.webkit.WebView
at android.view.LayoutInflater.createView(LayoutInflater.java:633)
at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:55)
at android.view.LayoutInflater.onCreateView(LayoutInflater.java:682)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:741)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
at com.example.starcitizen.fragment.HomeFragment.onCreateView(HomeFragment.java:18)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2600)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:881)
at androidx.fragment.app.FragmentManagerImpl.addAddedFragments(FragmentManagerImpl.java:2100)
at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1874)
at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1830)
at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1727)
at androidx.fragment.app.FragmentManagerImpl.dispatchStateChange(FragmentManagerImpl.java:2663)
at androidx.fragment.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManagerImpl.java:2613)
at androidx.fragment.app.Fragment.performActivityCreated(Fragment.java:2624)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:904)
at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303)
at androidx.fragment.app.FragmentManagerImpl.dispatchStateChange(FragmentManagerImpl.java:2659)
at androidx.fragment.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManagerImpl.java:2613)
at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:246)
at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:542)
at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:201)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1236)
at android.app.Activity.performStart(Activity.java:6006)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2288)
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:905)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:288)
at android.view.LayoutInflater.createView(LayoutInflater.java:607)
at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:55)
at android.view.LayoutInflater.onCreateView(LayoutInflater.java:682)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:741)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
at com.example.starcitizen.fragment.HomeFragment.onCreateView(HomeFragment.java:18)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2600)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:881)
at androidx.fragment.app.FragmentManagerImpl.addAddedFragments(FragmentManagerImpl.java:2100)
at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1874)
at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1830)
at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1727)
at androidx.fragment.app.FragmentManagerImpl.dispatchStateChange(FragmentManagerImpl.java:2663)
at androidx.fragment.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManagerImpl.java:2613)
at androidx.fragment.app.Fragment.performActivityCreated(Fragment.java:2624)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:904)
at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303)
at androidx.fragment.app.FragmentManagerImpl.dispatchStateChange(FragmentManagerImpl.java:2659)
at androidx.fragment.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManagerImpl.java:2613)
at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:246)
at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:542)
at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:201)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1236)
at android.app.Activity.performStart(Activity.java:6006)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2288)
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:905)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)
Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x2040003
at android.content.res.Resources.getText(Resources.java:299)
at android.content.res.Resources.getString(Resources.java:385)
at com.android.org.chromium.content.browser.ContentViewCore
Tried to understand but failed..
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:openDrawer="start">
<include
layout="#layout/app_bar_main"
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_main"
app:menu="#menu/activity_main_drawer" />
</androidx.drawerlayout.widget.DrawerLayout>
There is no difference to use WebView in Activity and Fragment.
I can't figure your troubleshooting but I recommend you to check the following things.
check the permission in manifest
<uses-permission android:name="android.permission.INTERNET" />
check if there is Runtime Exception in onAttach() of HomeFragment.
If you wanna see the WebView in Fragment, you should declare the following code.
view.setWebViewClient(new WebViewClient());
Update
final String source = "http://google.com";
final WebView webView = (WebView) rootView.findViewById(R.id.home_webview);
//webView.loadUrl(url);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
//Do some like progress bar loading here.
}
#Override
public void onPageFinished(WebView view, String url) {
webView.loadUrl(source);
}
});
I have a database containing of Texts.My activity has a TextView at the top(this should be constantly intact throughout) and below that I have a RelativeLayout which will be my container. In my code, as soon as the activity (in which I will be inserting view dynamically) launches, I create a LinearLayoutCompact object and set some properties. Then I process the cursor to the table data and I create a TextView for each database element and add it to the LinearLayoutCompat object. Finally I try to add this object into the RelativeLayout container where the app crashes. I am using LayoutInflater and treating the RelativeLayout container as a ViewGroup (I found this way after doing some research). However, if I simply use setContentView on the LinearLayoutCompat object it works fine but also replaces that TextView I want to be present. Here are the files I think will be necessary :
veg_option.xml (layout of my activity)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView <!-- The one I want intact throughout -->
android:id="#+id/narrowText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Let's narrow down now !"
android:textSize="20sp"
android:textColor="#color/wineBrown"
android:gravity="center"
android:padding="10dp"
android:layout_marginTop="30dp"
android:elevation="4dp"/>
<RelativeLayout <!-- Trying to use this as container -->
android:id="#+id/dataCont"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
</RelativeLayout>
</LinearLayout>
VegOptions.java (The activity where all action is supposed to happen)
package com.techpappy.whattoeat;
/**
* Created by Mehul on 31-05-2017.
*/
import android.content.Context;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.Typeface;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutCompat;
import android.support.v7.widget.AppCompatTextView;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.util.ArrayList;
public class VegOptions extends AppCompatActivity{
protected DBSource vegDBSource;
private Cursor cursor;
protected ArrayList<String> mTypes;
LayoutInflater li = (LayoutInflater)getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = li.inflate(R.layout.veg_option, null);
ViewGroup dataConPt = (ViewGroup) findViewById(R.id.dataCont);
#Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.veg_option);
vegDBSource = new DBSource(VegOptions.this);
disp();
}
private void disp()
{
vegDBSource.open();
cursor = vegDBSource.getInfo();
LinearLayoutCompat linearLayoutCompat = defaultPage(cursor);
//setContentView(linearLayoutCompat); Works fine but replaces all
dataConPt.addView(linearLayoutCompat);
}
//Here my LinearLayoutCompat object is prepared and returned
public LinearLayoutCompat defaultPage(Cursor mCursor) {
LinearLayoutCompat layout = new LinearLayoutCompat(this);
LinearLayoutCompat.LayoutParams params = new LinearLayoutCompat.LayoutParams(LinearLayoutCompat.LayoutParams.MATCH_PARENT, LinearLayoutCompat.LayoutParams.MATCH_PARENT);
layout.setLayoutParams(params);
layout.setGravity(Gravity.CENTER);
layout.setOrientation(LinearLayoutCompat.VERTICAL);
mCursor.moveToFirst(); //Each iteration adds one TextView
do {
AppCompatTextView defaultText = new AppCompatTextView(this);
defaultText.setText(mCursor.getString(mCursor.getColumnIndex(DataBaseHelper.COLUMN_TYPES)));
defaultText.setTextAppearance(getApplicationContext(), R.style.TextFontMain);
defaultText.setTextSize(30);
defaultText.setPadding(0,30,0,30);
final String temp = (String) defaultText.getText();
defaultText.setGravity(Gravity.CENTER);
defaultText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(getApplicationContext(), temp, Toast.LENGTH_SHORT).show();
}
});
layout.addView(defaultText);
mCursor.moveToNext();
} while(mCursor.isAfterLast() == false);
return layout; //LinearLayoutCompat containing all Texts returned
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
vegDBSource.close();
overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
}
}
My previous questions have been downvoted but this time I have done a fair amount of research and found the correct way but I can't get it to work in my unique case
stacktrace
6-05 19:32:17.679 3450-3450/com.techpappy.whattoeat E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.techpappy.whattoeat, PID: 3450
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.techpappy.whattoeat/com.techpappy.whattoeat.VegOptions}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2567)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
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)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:106)
at com.techpappy.whattoeat.VegOptions.<init>(VegOptions.java:33)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1078)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2557)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
Simply initialized the LayoutInflator, View and the ViewGroup inside the onCreate() method and the problem was fixed.
I'm new to developing for Android and I'm trying to add TextView object to a fragment layout dynamically, however I keep getting this null reference error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.takemeout/com.takemeout.android.event.EventOverviewActivity}: android.view.InflateException: Binary XML file line #16: Binary XML file line #16: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
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)
Caused by: android.view.InflateException: Binary XML file line #16: Binary XML file line #16: Error inflating class fragment
Caused by: android.view.InflateException: Binary XML file line #16: Error inflating class fragment
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.LinearLayout.addView(android.view.View)' on a null object reference
at com.takemeout.android.event.EventListFragment.onCreateView(EventListFragment.java:36)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2189)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1255)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1472)
at android.support.v4.app.FragmentManagerImpl.addFragment(FragmentManager.java:1691)
at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:3413)
at android.support.v4.app.FragmentController.onCreateView(FragmentController.java:120)
at android.support.v4.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:378)
at android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:33)
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:79)
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 android.view.LayoutInflater.inflate(LayoutInflater.java:377)
at com.android.internal.policy.PhoneWindow.setContentView(PhoneWindow.java:412)
at android.app.Activity.setContentView(Activity.java:2414)
at com.takemeout.android.event.EventOverviewActivity.onCreate(EventOverviewActivity.java:33)
at android.app.Activity.performCreate(Activity.java:6679)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
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)
I'm unsure as of how to initialise the TextView object in onCreateView, as everything I've tried has produced this same message. Here is my code:
package com.takemeout.android.event;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.takemeout.android.R;
import java.util.Calendar;
import java.util.List;
public class EventListFragment extends Fragment {
EventOverviewProvider provider = new EventOverviewProvider();
List<EventOverviewProjection> eventsToday = provider.getTodayEvents();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_event_list, container, false);
//getEventsToday(eventsToday, v);
LinearLayout ll = (LinearLayout) v.findViewById(R.id.fragment_event_list);
TextView text = new TextView(this.getActivity());
text.setText("Sample text");
ll.addView(text);
// Inflate the layout for this fragment
return v;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
Here is my fragment_event_list.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1">
</LinearLayout>
Anyone have an idea of what I might be doing wrong?
Your LinearLayout is missing id. Just add android:id="#+id/fragment_event_list to LinearLayout in your xml. But you should choose a better name, something like #+id/list_view
Add the ID: in Xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/fragment_event_list" //add this
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="1">
</LinearLayout>
The ID is not added properly. That's why it gives null.
Update your onCreateView method to :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_event_list, container, false);
//getEventsToday(eventsToday, v);
LinearLayout ll = (LinearLayout) v;
TextView text = new TextView(this.getActivity());
text.setText("Sample text");
ll.addView(text);
// Inflate the layout for this fragment
return v;
}
since your parent layout itself is the layout you want to use to add textView, you can just typecast it and you are good to go.
i am using Maps API to create a simple android app and i get a wierd error i can't solve. It usually happens when i rotate my device. I'm using google services 8.4.0
4-23 15:39:47.503 9419-9419/com.licenta.vladut.mmap E/Parcel: Class not found when unmarshalling: android.support.v7.widget.Toolbar$SavedState
java.lang.ClassNotFoundException: android.support.v7.widget.Toolbar$SavedState
at java.lang.Class.classForName(Native Method)
at java.lang.Class.forName(Class.java:308)
at android.os.Parcel.readParcelableCreator(Parcel.java:2275)
at android.os.Parcel.readParcelable(Parcel.java:2239)
at android.os.Parcel.readValue(Parcel.java:2146)
at android.os.Parcel.readSparseArrayInternal(Parcel.java:2540)
at android.os.Parcel.readSparseArray(Parcel.java:1868)
at android.os.Parcel.readValue(Parcel.java:2203)
at android.os.Parcel.readArrayMapInternal(Parcel.java:2479)
at android.os.BaseBundle.unparcel(BaseBundle.java:221)
at android.os.Bundle.getBundle(Bundle.java:782)
at com.google.android.gms.maps.internal.ao.a(:com.google.android.gms.alldynamite:74)
at maps.ei.bu.a(Unknown Source)
at maps.ei.n.a(Unknown Source)
at com.google.android.gms.maps.internal.i$a.onTransact(:com.google.android.gms.alldynamite:107)
at android.os.Binder.transact(Binder.java:380)
at com.google.android.gms.maps.internal.IMapFragmentDelegate$zza$zza.onCreateView(Unknown Source)
at com.google.android.gms.maps.SupportMapFragment$zza.onCreateView(Unknown Source)
at com.google.android.gms.dynamic.zza$4.zzb(Unknown Source)
at com.google.android.gms.dynamic.zza.zza(Unknown Source)
at com.google.android.gms.dynamic.zza.onCreateView(Unknown Source)
at com.google.android.gms.maps.SupportMapFragment.onCreateView(Unknown Source)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1036)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1230)
at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2315)
at android.support.v4.app.FragmentController.onCreateView(FragmentController.java:120)
at android.support.v4.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:357)
at android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:31)
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:80)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:733)
at android.view.LayoutInflater.inflate(LayoutInflater.java:482)
at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:276)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:136)
at com.licenta.vladut.mmap.MainActivity.onCreate(MainActivity.java:54)
at android.app.Activity.performCreate(Activity.java:6020)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2259)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2368)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3947)
at android.app.ActivityThread.access$900(ActivityThread.java:149)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1290)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5292)
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:908)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)
Caused by: java.lang.ClassNotFoundException: Didn't find class "android.support.v7.widget.Toolbar$SavedState" on path: DexPathList[[zip file "/data/data/com.google.android.gms/app_chimera/m/00000000/DynamiteModules-prod.apk"],nativeLibraryDirectories=[/data/data/com.google.android.gms/app_chimera/m/00000000/n/armeabi-v7a, /vendor/lib, /system/lib]]
at dalvik.system.BaseDexClassLoader.f
04-23 15:39:47.503 9419-9419/com.licenta.vladut.mmap D/AndroidRuntime: Shutting down VM
04-23 15:39:47.505 9419-9419/com.licenta.vladut.mmap E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.licenta.vladut.mmap, PID: 9419
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.licenta.vladut.mmap/com.licenta.vladut.mmap.MainActivity}: android.view.InflateException: Binary XML file line #2: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2306)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2368)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3947)
at android.app.ActivityThread.access$900(ActivityThread.java:149)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1290)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5292)
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:908)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)
Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:763)
at android.view.LayoutInflater.inflate(LayoutInflater.java:482)
at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:276)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:136)
at com.licenta.vladut.mmap.MainActivity.onCreate(MainActivity.java:54)
at android.app.Activity.performCreate(Activity.java:6020)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2259)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2368)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3947)
at android.app.ActivityThread.access$900(ActivityThread.java:149)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1290)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5292)
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:908)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)
Caused by: android.os.BadParcelableException: ClassNotFoundException when unmarshalling: android.support.v7.widget.Toolbar$SavedState
at android.os.Parcel.readParcelableCreator(Parcel.java:2289)
at android.os.Parcel.readParcelable(Parcel.java:2239)
at android.os.Parcel.readValue(Parcel.java:2146)
at android.os.Parcel.readSparseArrayInternal(Parcel.java:2540)
at android.os.Parcel.readSparseArray(Parcel.java:1868)
at android.os.Parcel.readValue(Parcel.java:2203)
at android.os.Parcel.readArrayMapInternal(Parcel.java:2479)
at android.os.BaseBundle.unparcel(BaseBundle.java:221)
at android.os.Bundle.getBundle(Bundle.java:782)
at com.google.android.gms.maps.internal.ao.a(:com.google.android.gms.alldynamite:74)
at maps.ei.bu.a(Unknown Source)
at maps.ei.n.a(Unknown Source)
at com.google.android.gms.maps.internal.i$a.onTransact(:com.google.android.gms.alldynamite:107)
at android.os.Binder.transact(Binder.java:380)
at com.google.android.gms.maps.internal.IMapFragmentDelegate$zza$zza.onCreateView(Unknown Source)
at com.google.android.gms.maps.SupportMapFragment$zza.onCreateView(Unknown Source)
at com.google.android.gms.dynamic.zza$4.zzb(Unknown Source)
at com.google.android.gms.dynamic.zza.zza(Unknown Source)
at com.google.android.gms.dynamic.zza.onCreateView(Unknown Source)
at com.google.android.gms.maps.SupportMapFragment.onCreateView(Unknown Source)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1036)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1230)
at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2315)
at android.support.v4.app.FragmentController.onCreateView(FragmentController.java:120)
at android.support.v4.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:357)
at android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:31)
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:80)
at android.view.LayoutInf
My MainActivity.java is
package com.licenta.vladut.mmap;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
public class MainActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener, OnMapReadyCallback {
GoogleMap mMap;
private static final double BM_LAT = 47.6595076, BM_LNG = 23.5631243;
private Toolbar toolbar;
private GoogleApiClient mGoogleApiClient;
private static final String TAG = "SignInActivity";
private static final int ERROR_DIALOG_REQUEST = 9001;
private static final int RC_SIGN_IN = 9002;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.addApi(AppIndex.API).build();
if (checkPlayServices()) {
setContentView(R.layout.activity_map);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
(MainActivity.this).setSupportActionBar(toolbar);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
} else {
setContentView(R.layout.activity_main);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.sign_out) {
signOut();
return true;
}
return super.onOptionsItemSelected(item);
}
private void signOut() {
Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
toSignIn();
}
});
}
private void toSignIn() {
Intent i = new Intent(this, SignInActivity.class);
startActivity(i);
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
// An unresolvable error has occurred and Google APIs (including Sign-In) will not
// be available.
Log.d(TAG, getString(R.string.onConnectionFailed) + connectionResult);
}
private boolean checkPlayServices() {
GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
int result = googleAPI.isGooglePlayServicesAvailable(this);
if (result != ConnectionResult.SUCCESS) {
if (googleAPI.isUserResolvableError(result)) {
googleAPI.getErrorDialog(this, result,
ERROR_DIALOG_REQUEST).show();
} else {
Toast.makeText(this, "Nu se poate conecta la Google Play Services!", Toast.LENGTH_SHORT).show();
}
return false;
}
return true;
}
#Override
public void onMapReady(final GoogleMap map) {
this.mMap = map;
gotoLocation(BM_LAT,BM_LNG,18);
}
private void gotoLocation(double lat, double lng, float zoom){
LatLng latLng = new LatLng(lat, lng);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(latLng,zoom);
mMap.moveCamera(update);
}
}
Activity_main.xml is
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="match_parent"
tools:context="com.licenta.vladut.mmap.MainActivity">
<include
android:id="#+id/toolbar"
layout="#layout/toolbar"
/>
</RelativeLayout>
activity_map.xml is
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include
android:id="#+id/toolbar"
layout="#layout/toolbar"
/>
</fragment>
and finally, toolbar.xml is
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
android:background="?attr/colorPrimary"
android:id="#+id/toolbar"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:minHeight="?attr/actionBarSize"
android:layout_width="match_parent"
android:layout_alignParentStart="true"
android:elevation="4dp"
app:popupTheme="#style/AppTheme.PopupOverlay"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
</android.support.v7.widget.Toolbar>
I didn't like provided solutions as it imposed on my layouts and architecture.
Here's what I did to make it work. If you look at your stacktrace the ClassNotFoundException is coming from the line on GoogleMaps. So if we just fix that, the issue is gone.
GoogleMaps pukes/throw an error when the savedInstanceState has other items in it besides it's own. The solution is to just give GoogleMaps it's own dedicated bundle.
// class property
private static final String KEY_MAP_SAVED_STATE = "mapState";
// class methods
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mapView = findMapView(); // make your own method here
Bundle mapState = (savedInstanceState != null)
? savedInstanceState.getBundle(KEY_MAP_SAVED_STATE): null;
mapView.onCreate(mapState);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Bundle mapState = new Bundle();
mapView.onSaveInstanceState(mapState);
outState.putBundle(KEY_MAP_SAVED_STATE, mapState);
}
One thing to note is I'm not using the SupportMapFragment. I'm using a MapView directly. You may have to extend the SupportMapFragment so you can catch the hook methods and provide a blank/clean bundle
Upon rotation, your SupportMapFragment gets destroyed and recreated. Before it's destroyed, it writes its current state to a Parcel, to be used in restoring its state when recreated. The Fragment's saved state will include the state of its child Views, and since you've nested a Toolbar within it, it attempts to save and restore that, as well. The Toolbar class does not have an inner class SavedState necessary for that, so this process fails when trying to restore the Toolbar instance from the Parcel.
The solution is to not nest the Toolbar - or any other View, for that matter - within the <fragment> element. Instead, pull the <include> out of the <fragment>, and put them both in another ViewGroup; for example, a vertical LinearLayout, or a RelativeLayout.
Changing activity_map.xml to this worked, thanks again Mike.
<?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">
<include
android:id="#+id/toolbar"
layout="#layout/toolbar" />
<fragment xmlns:map="http://schemas.android.com/apk/res-auto"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent">
</fragment>
</RelativeLayout>
I had a similar problem with my custom view and found this solution.
I noticed that this crash occurred when I extended RecyclerView or AppCompatSpinner and needed to save the state. The crash will probably happen for other views as well.
Basically the crash is caused by a bug in AbsSavedState as mentioned here.
And the crash only occurs when the constructor of the SavedState is called without a class loader. It seemed like this was an old issue however I started getting crash reports for Android 9 and 10.
So the fix was to change:
public SavedState(Parcel source) {
super(source);
//...
}
to:
public SavedState(Parcel source) {
super(source, LinearLayoutManager.class.getClassLoader());
//...
}
Edit
I was on the right track, but then I was looking at some Android code and found out that there was actually a constructor missing that caused the crash. So I had the following constructor for the SavedState:
SavedState(Parcel in)
{
super(in);
//...
}
And I needed to add the following:
#RequiresApi(Build.VERSION_CODES.N)
SavedState(Parcel in, ClassLoader loader)
{
super(in, loader);
//...
}
And then I needed to change the creator:
public static final Creator<SavedState> CREATOR = new ClassLoaderCreator<SavedState>()
{
#Override
public SavedState createFromParcel(Parcel source, ClassLoader loader)
{
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.N ? new SavedState(source, loader) : new SavedState(source);
}
#Override
public SavedState createFromParcel(Parcel source)
{
return createFromParcel(source, null);
}
public SavedState[] newArray(int size)
{
return new SavedState[size];
}
};