Recycler view NullPointerException in abstract class [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
I am working on a project which has many activities which uses recycler view in the exact way,just the data and onClickListener changes,
I have the following abstract class for creating different activities with different onClickListener
public abstract class AbstractActivity extends ActionBarActivity implements View.OnClickListener{
private final String[] data;
RecyclerView.LayoutManager layoutManager;
RecyclerView.Adapter adapter;
List<String> list;
Toolbar toolbar;
String title;
int id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recycler);
Toolbar toolbar=(Toolbar)this.findViewById(R.id.toolbar);
toolbar.setLogo(R.drawable.ic_launcher);
toolbar.setTitle(title);
RecyclerView recyclerView=(RecyclerView)this.findViewById(R.id.recycler_view);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.addItemDecoration(new DividerItemDecoration(this, null));
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager=new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
list.add("Hello");
adapter=new CardAdapter(list,id,this);
recyclerView.setAdapter(adapter);
}
public AbstractActivity(String title,String[] data,int id){
this.title=title;
this.data=data;
this.id=id;
}
#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_abstract, 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.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public abstract void onClick(View v);
}
}
The recycler layout file is
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".Syllabus">
<android.support.v7.widget.Toolbar android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:minHeight="#dimen/abc_action_bar_default_height_material"
android:id="#+id/toolbar"
android:background="#03a9f4"
>
</android.support.v7.widget.Toolbar>
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Now when i extend some class to create activity using the abstract class i get nullPointerException.The extend class is
public class Batch extends AbstractActivity {
public Batch(){
super("Hello",new String[]{"B.E Syllabus","B.Arch Syllabus","MBA Syllabus","MCA Syllabus","M.Tech Syllabus"},R.layout.main_page);
}
#Override
public void onClick(View v) {
}
}
logcat entry is
          
02-14 17:07:03.233 2807-2807/android.anoop.com.vtustudent E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{android.anoop.com.vtustudent/android.anoop.com.vtustudent.Batch}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2070)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2095)
at android.app.ActivityThread.access$600(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1201)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4849)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.anoop.com.vtustudent.AbstractActivity.onCreate(AbstractActivity.java:37)
at android.app.Activity.performCreate(Activity.java:5236)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1082)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2034)
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2095)
at android.app.ActivityThread.access$600(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1201)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4849)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
at dalvik.system.NativeStart.main(Native Method)
The toolbar in the recycler file is expanding fine and app runs perfectly if i remove the recyclerView from the layout file.Also if i use the same resource file in some activity directlyit works fine.I am getting the error only when i am using layout resource file from the abstract class.
Why is this happening and how to correct this.Also is the way of abstract class the right way or is there some other way for creating same kind of activities. I am new to android programming and any help will be appreciated.Thank you

list is never initialized. So list.add("Hello"); will throw a NPE.
Simply Change: List<String> list; to List<String> list = new ArrayList<String>();

Related

Custom Adapter not working no matter what I try

I have made an adapter to display images and text from imageview and textview into listview.
I tried my best but the application crashes whenever this activity is called.
ImageAdapter.java:
public class ImageAdapter extends ArrayAdapter<String> {
private final Activity context;
private final String[] filedescrptions;
private final Integer[] filenames;
public ImageAdapter(Activity context, String[] filedescrptions, Integer[] filenames) {
super(context, R.layout.list_item, filedescrptions);
this.context = context;
this.filedescrptions = filedescrptions;
this.filenames = filenames;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView= inflater.inflate(R.layout.list_item, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.txt);
ImageView imageView = (ImageView) rowView.findViewById(R.id.img);
txtTitle.setText(filedescrptions[position]);
imageView.setImageResource(filenames[position]);
return rowView;
}
}
This is the main activity where the adapter is used.
ImageActivity.java:
public class ImageActivity extends AppCompatActivity {
ListView list;
String[] descriptions = {"Abnormal menstrual bleeding",
"Adverse effects of HIV drugs",
"Antibiotics contraindicated during pregnancy",
"Antiemetic drugs"
};
Integer[] fileIds = {
R.drawable.abnromalmenstrualbleeding,
R.drawable.adverseeffectsofhivdrugs,
R.drawable.antibioticscontraindicatedduringpregnancy,
R.drawable.antiemeticdrugs
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ImageAdapter adapter = new ImageAdapter(ImageActivity.this, descriptions, fileIds);
list=(ListView)findViewById(R.id.listview_image);
list.setAdapter(adapter);
}
#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();
return super.onOptionsItemSelected(item);
}
}
list_item.xml:
<?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">
<ImageView
android:id="#+id/img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24sp"
android:textColor="#android:color/black"/>
</LinearLayout>
logcat 38th line referes to list.setAdapter(adapter);
FATAL EXCEPTION: main java.lang.RuntimeException: Unable to start activity ComponentInfo{com.vivek.pocketmedbook/com.vivek.pocketmedbook.ImageActivity}:java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.vivek.pocketmedbook.ImageActivity.onCreate(ImageActivity.java:38)
at android.app.Activity.performCreate(Activity.java:5008)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084) 
at android.app.ActivityThread.access$600(ActivityThread.java:130) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:4745) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:511) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 
at dalvik.system.NativeStart.main(Native Method) 
Modify
ImageAdapter extends BaseAdapter
In getView method View rowView= inflater.inflate(R.layout.list_item, null, false)

Android - How to access a Fragment from a FragmentActivity

I always get a NullPointerException when I try to access a fragment from inside my main activity. No matter what I do.
The issue is that I use TabsPagerAdapter and ViewPager and I don't know how to get the inflated views (the fragment's onCreate() method returns the inflated view already).
The goal is to get access to an element inside the fragment and hide or show it dynamically by a single background thread which should also do this for more fragments.
MainActivity.java
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener
{
/* swipe view */
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private android.app.ActionBar actionBar;
// tab titles
private String[] tabs = { "Basic", "Advanced", "Settings"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* init swipe views */
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(mAdapter);
actionBar = getActionBar();
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
/* addTab returns void, how to geht my fragements and their views???*/
for (String tabName : tabs)
actionBar.addTab(actionBar.newTab().setText(tabName).setTabListener(this));
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {}
#Override
public void onPageScrollStateChanged(int arg0) {}
});
}
public void testFunction()
{
FragmentPage1 fragmentPage1 = (FragmentPage1) getSupportFragmentManager().findFragmentById(R.layout.fragment_page1);
GridLayout gridlayout = (GridLayout) fragmentPage1.getRootView().findViewById(R.id.adBannerBasicLayout);
gridlayout.setVisibility(GridLayout.VISIBLE); /* THATS MY GOAL */
}
FragmentPage1.java
public class FragmentPage1 extends Fragment {
private View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_page1, container, false);
/* HERE IT IS WORKING FINE,
but later I want to make it visible again
from code OUTSIDE FragmentPage1 ??? */
GridLayout gridlayout = (GridLayout) rootView.findViewById(R.id.adBannerBasicLayout);
gridlayout.setVisibility(GridLayout.GONE);
return rootView;
}
/* so I tried this, but also get always NullPointerException */
public View getRootView()
{
return rootView;
}
}
fragment_page1.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:id="#+id/settings_scroll_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<GridLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#000000"
android:orientation="vertical"
android:rowCount="12"
android:columnCount="5"
>
<!-- Some Banner Ads I want to hide show -->
<!-- I want to access this from everywhere! -->
<GridLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:id="#+id/adBannerBasicLayout"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="fill"
android:rowCount="3"
android:columnCount="1"
android:layout_row="0"
android:layout_column="0"
android:layout_columnSpan="5">
<Space
android:layout_width="0dp"
android:layout_height="5dp"
android:layout_row="0"
android:layout_column="0"
/>
<com.google.android.gms.ads.AdView
android:id="#+id/adBannerBasic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="fill"
ads:adSize="BANNER"
ads:adUnitId="xxxxxxxxxxxxxxxxxxxxxxxxxx"
android:layout_row="1"
android:layout_column="0"
>
</com.google.android.gms.ads.AdView>
<Space
android:layout_width="0dp"
android:layout_height="5dp"
android:layout_row="2"
android:layout_column="0"
/>
</GridLayout>
<!-- more stuff... -->
</GridLayout>
</ScrollView>
Please help me out, I'm totally stuck!
THANKS!
EDIT:
The scond line in testFunction() throws the NullPointerException:
GridLayout gridlayout = (GridLayout) fragmentPage1.getRootView().findViewById(R.id.adBannerBasicLayout);
because getSupportFragmentManager() always returns null:
FragmentPage1 fragmentPage1 = (FragmentPage1) getSupportFragmentManager().findFragmentById(R.layout.fragment_page1);
Logcat Outoput
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:3969)
at android.view.View.performClick(View.java:4633)
at android.view.View$PerformClick.run(View.java:19330)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5356)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3964)
            at android.view.View.performClick(View.java:4633)
            at android.view.View$PerformClick.run(View.java:19330)
            at android.os.Handler.handleCallback(Handler.java:733)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:157)
            at android.app.ActivityThread.main(ActivityThread.java:5356)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
            at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
            at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at org.tzapp.smote.MainActivity.testFuntion(MainActivity.java:393)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at android.view.View$1.onClick(View.java:3964)
            at android.view.View.performClick(View.java:4633)
            at android.view.View$PerformClick.run(View.java:19330)
            at android.os.Handler.handleCallback(Handler.java:733)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:157)
            at android.app.ActivityThread.main(ActivityThread.java:5356)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
            at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
            at dalvik.system.NativeStart.main(Native Method)
You are using the wrong static value from the auto generated R file!
Instead of using R.layout.fragment_page1 which references the XML resource you should use R.id.fragment_page1 which should be the id of the fragment in your R.layout.activity_main XML file at /res/layout/activity_main.xml
R.layout references XML layout files
R.id references individual XML nodes (Views, Fragments etc.)
So in short, change:
FragmentPage1 fragmentPage1 = (FragmentPage1) getSupportFragmentManager().findFragmentById(R.layout.fragment_page1);
To:
FragmentPage1 fragmentPage1 = (FragmentPage1) getSupportFragmentManager().findFragmentById(R.id.fragment_page1);
And make sure that your fragment id in /res/layout/activity_main.xml is set to R.id.fragment_page1 like so:
<fragment android:name="com.example.yourpackage.FragmentPage1"
android:id="#+id/fragment_page1"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
you use getSupportFragmentManager() to get fragment.
Please double check if your FragmentPage1 extends a android.support.v4.app.Fragment;
not a
android.Fragment;
After updating SDK and repository, there is new trouble. I cant build anymore and I dont want to compile on level 23 :(
Information:Gradle tasks [clean, :app:generateDebugSources, :app:generateDebugTestSources]
:app:clean
:app:preBuild
:app:preDebugBuild
:app:checkDebugManifest
:app:preReleaseBuild
:app:prepareComAndroidSupportAppcompatV72300Library
:app:prepareComAndroidSupportSupportV42300Library
:app:prepareComGoogleAndroidGmsPlayServicesAds750Library
:app:prepareComGoogleAndroidGmsPlayServicesAnalytics750Library
:app:prepareComGoogleAndroidGmsPlayServicesBase750Library
:app:prepareComInstabugLibraryInstabugcore161Library
:app:prepareComInstabugLibraryInstabugsupport161Library
:app:prepareDebugDependencies
:app:compileDebugAidl
:app:compileDebugRenderscript
:app:generateDebugBuildConfig
:app:generateDebugAssets UP-TO-DATE
:app:mergeDebugAssets
:app:generateDebugResValues UP-TO-DATE
:app:generateDebugResources
:app:mergeDebugResources
:app:processDebugManifest
:app:processDebugResources
C:\Users\Tom\AndroidStudioProjects\SSMote\app\build\intermediates\exploded-aar\com.android.support\appcompat-v7\23.0.0\res\values-v23\values-v23.xml
Error:(1) Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Inverse'.
Error:(1) Error retrieving parent for item: No resource found that matches the given name 'android:Widget.Material.Button.Colored'.
Error:Execution failed for task ':app:processDebugResources'.
> com.android.ide.common.internal.LoggedErrorException: Failed to run command:
C:\Users\Tom\AppData\Local\Android\sdk\build-tools\21.1.2\aapt.exe package -f --no-crunch -I C:\Users\Tom\AppData\Local\Android\sdk\platforms\android-21\android.jar -M C:\Users\Tom\AndroidStudioProjects\SSMote\app\build\intermediates\manifests\full\debug\AndroidManifest.xml -S C:\Users\Tom\AndroidStudioProjects\SSMote\app\build\intermediates\res\debug -A C:\Users\Tom\AndroidStudioProjects\SSMote\app\build\intermediates\assets\debug -m -J C:\Users\Tom\AndroidStudioProjects\SSMote\app\build\generated\source\r\debug -F C:\Users\Tom\AndroidStudioProjects\SSMote\app\build\intermediates\res\resources-debug.ap_ --debug-mode --custom-package org.tzapp.smote -0 apk --output-text-symbols C:\Users\Tom\AndroidStudioProjects\SSMote\app\build\intermediates\symbols\debug
Error Code:
1
Output:
C:\Users\Tom\AndroidStudioProjects\SSMote\app\build\intermediates\res\debug\values-v23\values.xml:5: error: Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Inverse'.
C:\Users\Tom\AndroidStudioProjects\SSMote\app\build\intermediates\res\debug\values-v23\values.xml:20: error: Error retrieving parent for item: No resource found that matches the given name 'android:Widget.Material.Button.Colored'.
Information:BUILD FAILED
Information:Total time: 40.157 secs
Information:3 errors
Information:0 warnings
Also I found another answer, which is I think most satisfying :)
I forgot to mention that there is another class. It all comes from that stupid piece of example code for Swipe Views which is avaible somewhere on developers.google.com ...
Everytime I tried to access the FragmentPages via my TabPagerAdapter class using the stupid getItem(int i) method, I created a new Fragment() :-/ Very irritating!
Class TabsPagerAdapter from bad google example
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm, MainActivity mainActivity){
super(fm);
}
// page index, fragment selector
#Override
public Fragment getItem(int index) {
switch (index)
{
case 0: return new FragmentPage1(); // bad practice
case 1: return new FragmentPage2(); // why should one do that?
case 2: return new FragmentPage3();
}
return null;
}
#Override
public int getCount() {
return 3;
}
}
What a piece of crap ^^ And I just copied it over and then totally forgot about it's existence ;)
Moved instanciation of fragments to constructor and keeped them for later use. Works perfectly now.
Class TabsPagerAdapter after optimization
public class TabsPagerAdapter extends FragmentPagerAdapter {
// hosted fragments
private FragmentPage fragmentPageBasic;
private FragmentPage fragmentPageAdvanced;
private FragmentPage fragmentPageSettings;
//constructor
public TabsPagerAdapter(FragmentManager fm, MainActivity mainActivity){
super(fm);
fragmentPageBasic = new FragmentPage();
fragmentPageBasic.setMainActivity(mainActivity);
fragmentPageBasic.setLayoutResource(R.layout.fragment_page1);
fragmentPageBasic.setAdBannerResource(R.id.adBannerBasic);
fragmentPageBasic.setAdBannerLayoutResource(R.id.adBannerBasicLayout);
fragmentPageAdvanced = new FragmentPage();
fragmentPageAdvanced.setMainActivity(mainActivity);
fragmentPageAdvanced.setLayoutResource(R.layout.fragment_page2);
fragmentPageAdvanced.setAdBannerResource(R.id.adBannerAdvanced);
fragmentPageAdvanced.setAdBannerLayoutResource(R.id.adBannerAdvancedLayout);
fragmentPageSettings = new FragmentSettingsPage();
fragmentPageSettings.setMainActivity(mainActivity);
fragmentPageSettings.setLayoutResource(R.layout.fragment_page3);
fragmentPageSettings.setAdBannerResource(R.id.adBannerSettings);
fragmentPageSettings.setAdBannerLayoutResource(R.id.adBannerSettingsLayout);
}
// page index, fragment selector
#Override
public Fragment getItem(int index) {
switch (index)
{
case 0: return fragmentPageBasic;
case 1: return fragmentPageAdvanced;
case 2: return fragmentPageSettings;
}
return null;
}
#Override
public int getCount() {
return 3;
}
// GETTERS
public FragmentPage getFragmentPageBasic() {return fragmentPageBasic;}
public FragmentPage getFragmentPageAdvanced() {return fragmentPageAdvanced;}
public FragmentPage getFragmentPageSettings() {return fragmentPageSettings;}
}
Instead of having redundant FragmentPage1, Fragment2, FragmentPage3 classes, of course now there is only FragmentPage and FragmentSettingsPage (extends FragmentPage to override OnCreateView method), which results in a much cleaner and more understandable code.
Class FragmentPage
public class FragmentPage extends Fragment {
protected MainActivity mainActivity;
// layout resource
protected int layoutResource;
// view
protected View rootView;
//Admob
protected AdView adBanner;
protected int adBannerResource;
protected int adBannerLayoutResource;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
onCreate(inflater, container);
return rootView;
}
// manage common onCreate things
protected void onCreate(LayoutInflater inflater, ViewGroup container)
{
rootView = inflater.inflate(layoutResource, container, false);
// admob banner
adBanner = (AdView) rootView.findViewById(adBannerResource);
adBanner.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
}
#Override
public void onAdOpened() {
}
#Override
public void onAdClosed() {
newAdBannerRequest();
}
#Override
public void onAdFailedToLoad(int errorCode) {
newAdBannerRequest();
}
#Override
public void onAdLeftApplication() {
}
});
if(mainActivity.showAdBanners())
{
newAdBannerRequest();
showAdBanner();
}
else
hideAdBanner();
}
// ADMOB
public void newAdBannerRequest()
{
AdRequest request = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR) // All emulators
.addTestDevice("XXXXXXXXXXXXXXXXXXXXXXXXXX") // My Galaxy Nexus test phone
.build();
adBanner.loadAd(request);
}
public void showAdBanner()
{
GridLayout adBannerLayout = (GridLayout) rootView.findViewById(adBannerLayoutResource);
if(adBannerLayout.getVisibility() == GridLayout.GONE)
adBannerLayout.setVisibility(GridLayout.VISIBLE);
}
public void hideAdBanner()
{
GridLayout adBannerLayout = (GridLayout) rootView.findViewById(adBannerLayoutResource);
if(adBannerLayout.getVisibility() == GridLayout.VISIBLE)
adBannerLayout.setVisibility(GridLayout.GONE);
}
// GETTERS
public AdView getAdBanner() { return adBanner;}
public View getRootView() { return rootView;}
// SETTERS
public void setMainActivity(MainActivity mainActivity) {this.mainActivity = mainActivity;}
public void setLayoutResource(int layoutResource){this.layoutResource = layoutResource;}
public void setAdBannerResource(int adBannerResource){this.adBannerResource = adBannerResource;}
public void setAdBannerLayoutResource(int adBannerLayoutResource){this.adBannerLayoutResource = adBannerLayoutResource;}
}
Class FragmentSettingsPage
public class FragmentSettingsPage extends FragmentPage {
// Preferences
public static final String PREFS_NAME = "Preferences";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(inflater, container);
SharedPreferences preferences = mainActivity.getSharedPreferences(PREFS_NAME, 0);
// do some other top secret stuff here ;)
return rootView;
}
}
Any ideas how to improve this further ?
Use import android.support.v4.app.Fragment instead import android.app.Fragment
Please add this in your gradle dependencies
compile 'com.android.support:support-v4:22.1.1'
Edit : please use findFragmentById(R.id.fragment_page1) instead R.layout
FragmentPage1 fragmentPage1 = (FragmentPage1) getSupportFragmentManager().findFragmentById(R.id.fragment_page1);

Why is my Android app crashing with 'Error inflating class fragment'? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
So I added a <WebView> to the standard navigation drawer template and added some code to the java file. However, now the app keeps on crashing. The error it throws in the console is Error inflating class fragment
It does compile though. So how can I fix this? Should I add the <WebView> somewhere else?
activity_login.xml
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".login">
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/main_webview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<fragment android:id="#+id/navigation_drawer"
android:layout_width="#dimen/navigation_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
android:name="test.vwebviewdrawer.NavigationDrawerFragment"
tools:layout="#layout/fragment_navigation_drawer" />
</android.support.v4.widget.DrawerLayout>
main.java
package test.webviewdrawer;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.view.View.OnClickListener;
//...
public class login extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
private NavigationDrawerFragment mNavigationDrawerFragment;
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
WebView myWebView = (WebView) findViewById(R.id.main_webview);
String pageUrl = "http://www.google.com";
myWebView.loadUrl(pageUrl);
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
case 4:
mTitle = getString(R.string.title_section4);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
getMenuInflater().inflate(R.menu.login, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_login, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((login) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
UPDATE:
I added the error message as requested in the comment section.
06-21 19:42:52.109 17625-17625/test.webviewdrawer E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: test.webviewdrawer, PID: 17625
java.lang.RuntimeException: Unable to start activity ComponentInfo{test.webviewdrawer/test.webviewdrawer.login}: android.view.InflateException: Binary XML file line #28: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2596)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2653)
at android.app.ActivityThread.access$800(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1355)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5872)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:852)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:668)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #28: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:713)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:375)
at android.app.Activity.setContentView(Activity.java:1997)
at android.support.v7.app.ActionBarActivity.superSetContentView(ActionBarActivity.java:216)
at android.support.v7.app.ActionBarActivityDelegateICS.setContentView(ActionBarActivityDelegateICS.java:110)
at android.support.v7.app.ActionBarActivity.setContentView(ActionBarActivity.java:76)
at test.webviewdrawer.login.onCreate(login.java:46)
at android.app.Activity.performCreate(Activity.java:5312)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1111)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2552)
There's a typo in your XML layout, at this line:
android:name="test.vwebviewdrawer.NavigationDrawerFragment"
It should be:
android:name="test.webviewdrawer.NavigationDrawerFragment"
instead :-)

I have just written my first android app, and after 3 hours it still doesn't work

I have just started writing my first piece of code in an android app, however when I run it with the following section uncommented it crashes (anything else I tell you would be a useless guess):
public void onButton1Click(View v){
if(v.getId() == R.id.button1){
StringBuilder str = new StringBuilder("");
if (pepBox.isChecked()) {
str.append("Pepperoni"+" ");
}
if (cheeseBox.isChecked()) {
str.append("Extra Cheese");
}
if (str.length() == 0) {
str.append("Plain");
}
textView.setText(str);
}
}
With the following error log:
04-07 17:45:30.897: E/AndroidRuntime(15210): FATAL EXCEPTION: main
04-07 17:45:30.897: E/AndroidRuntime(15210): Process: com.ollieapps.helloworld, PID: 15210
04-07 17:45:30.897: E/AndroidRuntime(15210): java.lang.IllegalStateException: Could not execute method of the activity
04-07 17:45:30.897: E/AndroidRuntime(15210): at android.view.View$1.onClick(View.java:3823)
04-07 17:45:30.897: E/AndroidRuntime(15210): at android.view.View.performClick(View.java:4438)
04-07 17:45:30.897: E/AndroidRuntime(15210): at android.view.View$PerformClick.run(View.java:18422)
04-07 17:45:30.897: E/AndroidRuntime(15210): at android.os.Handler.handleCallback(Handler.java:733)
04-07 17:45:30.897: E/AndroidRuntime(15210): at android.os.Handler.dispatchMessage(Handler.java:95)
04-07 17:45:30.897: E/AndroidRuntime(15210): at android.os.Looper.loop(Looper.java:136)
04-07 17:45:30.897: E/AndroidRuntime(15210): at android.app.ActivityThread.main(ActivityThread.java:5017)
04-07 17:45:30.897: E/AndroidRuntime(15210): at java.lang.reflect.Method.invoke(Native Method)
04-07 17:45:30.897: E/AndroidRuntime(15210): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-07 17:45:30.897: E/AndroidRuntime(15210): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-07 17:45:30.897: E/AndroidRuntime(15210): Caused by: java.lang.reflect.InvocationTargetException
04-07 17:45:30.897: E/AndroidRuntime(15210): at java.lang.reflect.Method.invoke(Native Method)
04-07 17:45:30.897: E/AndroidRuntime(15210): at android.view.View$1.onClick(View.java:3818)
04-07 17:45:30.897: E/AndroidRuntime(15210): ... 9 more
04-07 17:45:30.897: E/AndroidRuntime(15210): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.widget.CheckBox.isChecked()' on a null object reference
04-07 17:45:30.897: E/AndroidRuntime(15210): at com.ollieapps.helloworld.MainActivity.onButton1Click(MainActivity.java:59)
04-07 17:45:30.897: E/AndroidRuntime(15210): ... 11 more
I'm sorry if I have included to much or too little, this is my first question, also I have already searched for 3 hours.
Full Code:
package com.ollieapps.helloworld;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
TextView textView; CheckBox pepBox, cheeseBox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pepBox = (CheckBox) findViewById(R.id.checkBox1);
cheeseBox = (CheckBox) findViewById(R.id.checkBox2);
textView = (TextView) findViewById(R.id.textView1);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
#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 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onButton1Click(View v){
if(v.getId() == R.id.button1){
StringBuilder str = new StringBuilder("");
if (pepBox.isChecked()) {
str.append("Pepperoni"+" ");
}
if (cheeseBox.isChecked()) {
str.append("Extra Cheese");
}
if (str.length() == 0) {
str.append("Plain");
}
textView.setText(str);
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
xml:
fragment:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.ollieapps.helloworld.MainActivity$PlaceholderFragment" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:orientation="vertical" >
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pepperoni" />
<CheckBox
android:id="#+id/checkBox2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ExtraCheese" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onButton1Click"
android:text="Show" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Plain" />
</LinearLayout>
</RelativeLayout>
Main:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.ollieapps.helloworld.MainActivity"
tools:ignore="MergeRootFrame" />
It seems you built your views inside fragment_main.xml and not activity_main.xml.
When you first create a new android project, you have these files which are automatically created and opened:
Then, when you begin, you add views (e.g: a TextView) inside fragment_main.xml file. Finally, you tried to do a basically event with this view inside your Activity, something like this:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); // Using layout activity_main.xml
// You try to set a simple text on the view (TextView) previously added
TextView text = (TextView) findViewById(R.id.textView1);
text.setText("Simple Text"); // And you get an error here!
/*
* You do an fragment transaction to add PlaceholderFragment Fragment
* on screen - this below snippnet is automatically created.
*/
if(savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
You cannot run your app or sometimes you have only a white screen, because the views that you tried to call/display are into the wrong layout..
Solution: Move all your stuff inside onCreateView method into the Fragment class.
As DoctororDrive said in his comment
Call views and do something in the related fragment and not the parent activity.
For example, in your case, these following lines:
pepBox = (CheckBox) findViewById(R.id.checkBox1);
cheeseBox = (CheckBox) findViewById(R.id.checkBox2);
textView = (TextView) findViewById(R.id.textView1);
might be inside your fragment because you created it in fragment_main.xml layout. Then:
// start fragment
public static class PlaceholderFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Use the layout which is displayed it's fragment_main.xml
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
// Find your views here!
// Don't forget to findViewById attached to the inflated view "rootView.findView..."
pepBox = (CheckBox) rootView.findViewById(R.id.checkBox1);
cheeseBox = (CheckBox) rootView.findViewById(R.id.checkBox2);
textView = (TextView) rootView.findViewById(R.id.textView1);
/*
* Do something here: click listener, set a text, check a box..
*/
return rootView;
}
/*
* Perform other methods still inside the fragment
*/
public void onButton1Click(View v){
if(v.getId() == R.id.button1){
StringBuilder str = new StringBuilder("");
if (pepBox.isChecked()) {
str.append("Pepperoni"+" ");
}
if (cheeseBox.isChecked()) {
str.append("Extra Cheese");
}
if (str.length() == 0) {
str.append("Plain");
}
textView.setText(str);
}
}
}
// end fragment
if (pepBox.isChecked()) {
This line of code is failing with a NullPointerException because pepBox was declared but it's not being initialized as it should (and is therefore null at this point in the code).
Here is its declaration line:
TextView textView; CheckBox pepBox, cheeseBox;
And here is its initialization:
pepBox = (CheckBox) findViewById(R.id.checkBox1);
The problem is that (a) this line is not be called, or (b) findViewById(R.id.checkBox1) is returning null.
If findViewByID is returning null then you probably want to refer to this question, which addresses exactly this issue. Its "related questions", down the right-hand side, should also be helpful.

Android nullPointerException using EditText

In my app, I am trying to manipulate an EditText element, but every time I try to do so, it throws a nullPointerException at me. I don't know why its doing this because it only seems to happen to this one EditText, docTitle, not for any of the others I have.
Here is the part of the java class that throws the exception:
public class MainActivity extends FragmentActivity implements RichText.EditTextImeBackListener, OnTouchListener, OnClickListener, TextWatcher{
private String[] drawerListViewItems1;
private String[] drawerListViewItems2;
private ArrayList<Editable> undoStrings;
private int undoIndex;
//this is the EditText that is giving me trouble, it is defined down in onCreate
public EditText docTitle;
private int styleStart;
private ListView drawerListView1;
private ListView drawerListView2;
private RelativeLayout formatBar;
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle actionBarDrawerToggle;
private RichText richText;
private SaveFragment saveFragment;
private ToggleButton boldButton;
private ToggleButton emButton;
private ToggleButton uButton;
private ToggleButton strikeButton;
private boolean keyboardShown;
private boolean alreadyShown;
private boolean isMainContent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//finds the left drawer
drawerListView1 = (ListView) findViewById(R.id.left_drawer);
//finds right drawer
drawerListView2 = (ListView)findViewById(R.id.right_drawer);
//loads the first drawer
loadDrawer1();
//loads the second drawer
loadDrawer2();
//finds the drawer layout
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
//assign ActionBarDrawerToggle
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.ic_drawer,
R.string.drawer_open, R.string.drawer_close);
//sets the drawer listener
drawerLayout.setDrawerListener(new DrawerLayout.SimpleDrawerListener() {
#Override
public void onDrawerOpened(View drawerLayout){
//hides format bar when a drawer is opened
if(keyboardShown){
hideFormatBarAnim();
}
}
#Override
public void onDrawerClosed(View drawerLayout){
//shows format bar when closed
showFormatBar();
}
});
//enable and show "up" arrow
getActionBar().setDisplayHomeAsUpEnabled(true);
// just styling option for the drawer layout
drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
//item click listener for drawer items
drawerListView1.setOnItemClickListener(new DrawerItemClickListener());
drawerListView2.setOnItemClickListener(new DrawerItemClickListener());
isMainContent= true;
alreadyShown=false;
keyboardShown=false;
undoIndex=0;
undoStrings = new ArrayList<Editable>();
//assigns formatBar to its XML layout
formatBar = (RelativeLayout)findViewById(R.id.formatBar);
//assigns docTitle to its XML layout
docTitle = (EditText)findViewById(R.id.docTitle);
//This line here throws the error
docTitle.setText("Hello");
//defines save fragment
saveFragment = new SaveFragment();
//assigns richText to its XML layout and adds a TextChangeListener
richText= (RichText)findViewById(R.id.edit_text);
richText.addTextChangedListener(this);
//assigns boldButton to its XML layout and adds an OnClickListener
boldButton=(ToggleButton)findViewById(R.id.bold);
boldButton.setOnClickListener(this);
//assigns emButton to its XML layout and adds an OnClickListener
emButton=(ToggleButton)findViewById(R.id.ital);
emButton.setOnClickListener(this);
//assigns uButton to its XML layout and adds an OnClickListener
uButton=(ToggleButton)findViewById(R.id.underline);
uButton.setOnClickListener(this);
//assigns strikeButton to its XML layout and adds an onClickListener
strikeButton=(ToggleButton)findViewById(R.id.strike);
strikeButton.setOnClickListener(this);
//initiates sofKeyboardHook
softKeyboardHook();
//creates the default saving directory
Doc.makeDefaultDir();
lookForFiles();
}
And here is the XML layout that goes with it:
<?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"
android:background="#ffffff">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="400dp"
android:background="#1E772F"
android:layout_marginTop="350dp">
<EditText
android:id="#+id/docTitle"
android:text="DefaultDocName"
android:paddingTop="20dp"
android:layout_centerHorizontal="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="6dp"/>
<Button
android:id="#+id/save"
android:layout_height="wrap_content"
android:layout_width="150dp"
android:text="Save"
android:layout_below="#+id/docTitle"
android:layout_marginLeft="10dp"
android:layout_marginTop="20dp"
android:onClick="onSaveDoneClick"/>
<Button
android:id="#+id/cancel"
android:layout_height="wrap_content"
android:layout_width="150dp"
android:text="Cancel"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:layout_below="#+id/docTitle"
android:layout_toRightOf="#+id/save"
android:onClick="cancelSave"/>
</RelativeLayout>
</ScrollView>
Heres the log for the error it throws:
03-19 09:48:50.246 12996-12996/com.noahl98.jotmobile E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.noahl98.jotmobile, PID: 12996
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.noahl98.jotmobile/com.noahl98.jotmobile.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2190)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2250)
at android.app.ActivityThread.access$700(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1411)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5083)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.noahl98.jotmobile.MainActivity.onCreate(MainActivity.java:133)
at android.app.Activity.performCreate(Activity.java:5260)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2154)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2250)
            at android.app.ActivityThread.access$700(ActivityThread.java:139)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1411)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:5083)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
            at dalvik.system.NativeStart.main(Native Method)
Thanks in advance for your help.
The layout you are inflating is called 'activity_main.xml' and it seems to contain a number of drawers and other things that are not in the layout file you attached. Are you sure that you are not confusing your layout files.
basically it appears like you don't have 'docTitle' in the 'activity_main.xml' file which is why
//assigns docTitle to its XML layout
docTitle = (EditText)findViewById(R.id.docTitle);
//This line here throws the error
docTitle.setText("Hello");
gives you 'docTitle = null'
The problem is that the layout that you are loading in your onCreate function is not the one which has the editText,
you can check:
setContentView(R.layout.activity_main);
is this activity_main layout the one that you have posted?
Because later in your onCreate method you are using drawerListView1 which is not in the XML you have pasted, and that one is not null.
Please ensure: the views you're using should been in the layout that you are loading

Categories