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.
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" />
I'm trying to get this effect in my UI: https://github.com/traex/ExpandableLayout.
1) I added to my build.gradle the compile '...' for this library
2) I created workout_main.xml file ( I'll post the code below)
3) I use a fragment which extends a base fragment class ( which is created by my activity). I'm able to use inflate view for other fragment in this activity but this one seems to crash because of the library I'm using. I'm not sure if that would be the culprit or the way I'm approaching things
As an aside, I looked on their GitHub open / closed issues and the only "solutions" to this problem was using android.enableAapt2=false in the gradle.properties file. ( which didn't work)
WORKOUT_MAIN.XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:expandable="http://schemas.android.com/apk/com.andexert.expandablelayout.library"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/workout_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="org.liberty.android.fantastischmemo.ui.AnyMemo">
<com.andexert.expandablelayout.library.ExpandableLayout
android:id="#+id/first"
android:layout_width="match_parent"
android:layout_height="wrap_content"
expandable:el_headerLayout="#layout/view_header"
expandable:el_contentLayout="#layout/view_content"
android:background="#e74c3c"/>
<com.andexert.expandablelayout.library.ExpandableLayoutListView
android:id="#+id/listview"
android:layout_below="#+id/first"
android:layout_width="match_parent"
android:layout_marginTop="15dp"
android:layout_height="match_parent"/>
</RelativeLayout>
2)Fragment where it's called
public class WorkoutTabFragment extends BaseFragment {
private ExpandableListView expandableListView;
private final AtomicInteger workoutListVersion = new AtomicInteger(0);
private final static String TAG = WorkoutTabFragment.class.getSimpleName();
private WorkoutListAdapter woAdapter;
#Inject WorkOutListUtil workoutList;
#Inject DatabaseUtil databaseUtil;
#Inject RecentListActionModeUtil recentListActionModeUtil;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fragmentComponents().inject(this);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater){
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.open_screen_menu, menu);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//ERRROR HAPPENS HERE
View v = inflater.inflate( R.layout.workout_main, container, false);
expandableListView = (ExpandableListView) v.findViewById(R.id.listview);
/* pre loading stat */
woAdapter = new WorkoutListAdapter(getContext(), workoutList, recentListActionModeUtil);
final String[] array = {"Hello", "World", "Android", "is", "Awesome", "World", "Android", "is", "Awesome", "World", "Android", "is", "Awesome", "World", "Android", "is", "Awesome"};
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getContext(), R.layout.view_row, R.id.header_text, array);
expandableListView.setAdapter(arrayAdapter);
return v;
}
3) My LOGCAT
-18 11:43:53.672 5331-5331/org.liberty.android.fantastischmemodev E/AndroidRuntime: FATAL EXCEPTION: main
Process: org.liberty.android.fantastischmemodev, PID: 5331
android.view.InflateException: Binary XML file line #12: Binary XML file line #12: Error inflating class com.andexert.expandablelayout.library.ExpandableLayout
Caused by: android.view.InflateException: Binary XML file line #12: Error inflating class com.andexert.expandablelayout.library.ExpandableLayout
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:430)
at android.view.LayoutInflater.createView(LayoutInflater.java:645)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:787)
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 org.liberty.android.fantastischmemo.ui.WorkoutTabFragment.onCreateView(WorkoutTabFragment.java:126)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2248)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1340)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1569)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1636)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:758)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2415)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2201)
at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2155)
at android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:2034)
at android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:626)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:143)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1268)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:668)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:630)
at android.support.v4.view.ViewPager.setCurrentItem(ViewPager.java:611)
at android.support.design.widget.TabLayout$ViewPagerOnTabSelectedListener.onTabSelected(TabLayout.java:2191)
at android.support.design.widget.TabLayout.dispatchTabSelected(TabLayout.java:1164)
at android.support.design.widget.TabLayout.selectTab(TabLayout.java:1157)
at android.support.design.widget.TabLayout.selectTab(TabLayout.java:1127)
at android.support.design.widget.TabLayout$Tab.select(TabLayout.java:1426)
at android.support.design.widget.TabLayout$TabView.performClick(TabLayout.java:1536)
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)
Caused by: java.lang.IllegalArgumentException: HeaderLayout and ContentLayout cannot be null!
at com.andexert.expandablelayout.library.ExpandableLayout.init(ExpandableLayout.java:71)
at com.andexert.expandablelayout.library.ExpandableLayout.<init>(ExpandableLayout.java:52)
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:430)
at android.view.LayoutInflater.createView(LayoutInflater.java:645)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:787)
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 org.liberty.android.fantastischmemo.ui.WorkoutTabFragment.onCreateView(WorkoutTabFragment.java:126)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2248)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1340)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1569)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1636)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:758)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2415)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2201)
at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2155)
at android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:2034)
at android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:626)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:143)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1268)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:668)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:630)
at android.support.v4.view.ViewPager.setCurrentItem(ViewPager.java:611)
at android.support.design.widget.TabLayout$ViewPagerOnTabSelectedListener.onTabSelected(TabLayout.java:2191)
at android.support.design.widget.TabLayout.dispatchTabSelected(TabLayout.java:1164)
at android.support.design.widget.TabLayout.selectTab(TabLayout.java:1157)
at android.support.design.widget.TabLayout.selectTab(TabLayout.java:1127)
at android.support.design.widget.TabLayout$Tab.select(TabLayout.java:1426)
at android.support.design.widget.TabLayout$TabView.performClick(TabLayout.java:1536)
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)
I have my app, it has the following appareance:
The table at the bottom side is a TableLayout.
In my MainActivity.java I am using the following code to populate the whole layout of my app:
setContentView(R.layout.activity_main);
movieCompletionView = (TokenCompletionView)findViewById(R.id.searchMovie);
cineCompletionView = (TokenCompletionView)findViewById(R.id.searchCine);
...
TableLayout tl_Movies = (TableLayout)findViewById(R.id.tableLayoutMovies);
tl_Movies.removeAllViews();
for (...) tl_Movies.addView(someRow);
Then, I googled for some samples to improve the appareance of my table, and I found this:
But this sample builds only the table. In the MainActivity.java the code used for building it :
Table table = new Table(this);
setContentView(table);
And Table class:
public class Table extends LinearLayout {
..
}
Now, what I want is to add the smarter table to the original layout of my app.
I added an empty LinearLayout component in my activity_main.xml and I tried to populate it with this code:
setContentView(R.layout.activity_main);
movieCompletionView = (TokenCompletionView)findViewById(R.id.searchMovie);
cineCompletionView = (TokenCompletionView)findViewById(R.id.searchCine);
...
linearLayout = (LinearLayout) findViewById(R.id.smarterTable);
linearLayout = new Table(this);
But it does not work.
Sorry for the very basic question, but, can you tell me which are the right statements for adding the smarter table to the original layout of my app?
Edit 27-Nov-2017
Following the suggestion on Mike M. and F43nd1r.
I configured my activity_main.xml in this way:
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
tools:context="com.myapps.pavel.myseapp.MainActivity">
<com.myapps.pavel.myseapp.Table
android:id="#+id/smarterTable"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"/>
</LinearLayout>
And I used the following code in my MainActivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linearLayout = (Table) findViewById(R.id.smarterTable);
And I got this error:
FATAL EXCEPTION: main
Process: com.myapps.pavel.myseapp, PID: 5875
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.myapps.pavel.myseapp/com.myapps.pavel.myseapp.MainActivity}: android.view.InflateException: Binary XML file line #12: Binary XML file line #12: Error inflating class com.myapps.pavel.myseapp.Table
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:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
Caused by: android.view.InflateException: Binary XML file line #12: Binary XML file line #12: Error inflating class com.myapps.pavel.myseapp.Table
Caused by: android.view.InflateException: Binary XML file line #12: Error inflating class com.myapps.pavel.myseapp.Table
Caused by: java.lang.NoSuchMethodException: <init> [class android.content.Context, interface android.util.AttributeSet]
at java.lang.Class.getConstructor0(Class.java:2204)
at java.lang.Class.getConstructor(Class.java:1683)
at android.view.LayoutInflater.createView(LayoutInflater.java:618)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:787)
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:289)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
at com.myapps.pavel.myseapp.MainActivity.onCreate(MainActivity.java:83) /* This lane has this statement: setContentView(R.layout.activity_main);*/
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:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
Any suggestions?
Thanks
Solved!:
as Mike M. says, I had to change the parameters of the Table constructor
public Table(Context context,AttributeSet attrs) {
super(context, attrs);
Instead of <LinearLayout> use <com.your.package.Table> in the xml layout.
Then use the following:
linearLayout = (Table) findViewById(R.id.smarterTable);
for (...) linearLayout.addView(someRow);
Edit regarding your edit
Add this constructor to Table:
public Table(Context context, AttributeSet attrs) {
super(context, attrs);
}
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.
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.