getApplicationContext() returns null, but works in other activities

I’m using a SQLite database and whenever I call it, I need to pass the context to it. I usually do this using getApplicationContext() which works in other activities. In my current class it just returns null. Help!

04-06 16:46:19.523: E/AndroidRuntime(4279): Process: com.example.schoolandrevisiontimetable, PID: 4279
04-06 16:46:19.523: E/AndroidRuntime(4279): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.schoolandrevisiontimetable/com.example.schoolandrevisiontimetable.Input_slessontime}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
04-06 16:46:19.523: E/AndroidRuntime(4279):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2225)
04-06 16:46:19.523: E/AndroidRuntime(4279):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2388)
04-06 16:46:19.523: E/AndroidRuntime(4279):     at android.app.ActivityThread.access$800(ActivityThread.java:148)
04-06 16:46:19.523: E/AndroidRuntime(4279):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1292)
04-06 16:46:19.523: E/AndroidRuntime(4279):     at android.os.Handler.dispatchMessage(Handler.java:102)
04-06 16:46:19.523: E/AndroidRuntime(4279):     at android.os.Looper.loop(Looper.java:135)
04-06 16:46:19.523: E/AndroidRuntime(4279):     at android.app.ActivityThread.main(ActivityThread.java:5312)
04-06 16:46:19.523: E/AndroidRuntime(4279):     at java.lang.reflect.Method.invoke(Native Method)
04-06 16:46:19.523: E/AndroidRuntime(4279):     at java.lang.reflect.Method.invoke(Method.java:372)
04-06 16:46:19.523: E/AndroidRuntime(4279):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
04-06 16:46:19.523: E/AndroidRuntime(4279):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
04-06 16:46:19.523: E/AndroidRuntime(4279): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
04-06 16:46:19.523: E/AndroidRuntime(4279):     at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:105)
04-06 16:46:19.523: E/AndroidRuntime(4279):     at com.example.schoolandrevisiontimetable.Input_slessontime.getAmountOfDaysUsed(Input_slessontime.java:95)
04-06 16:46:19.523: E/AndroidRuntime(4279):     at com.example.schoolandrevisiontimetable.Input_slessontime.<init>(Input_slessontime.java:30)
04-06 16:46:19.523: E/AndroidRuntime(4279):     at java.lang.reflect.Constructor.newInstance(Native Method)
04-06 16:46:19.523: E/AndroidRuntime(4279):     at java.lang.Class.newInstance(Class.java:1572)
04-06 16:46:19.523: E/AndroidRuntime(4279):     at android.app.Instrumentation.newActivity(Instrumentation.java:1088)
04-06 16:46:19.523: E/AndroidRuntime(4279):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2215)
04-06 16:46:19.523: E/AndroidRuntime(4279):     ... 10 more

Here is the class it is returning null in package com.example.schoolandrevisiontimetable;

import java.util.List;

import com.astuetz.PagerSlidingTabStrip;


import Database.DatabaseHelper;
import Database.MC_sschoolday;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;

public class Input_slessontime extends FragmentActivity {
    DatabaseHelper db;
    String[] days = new String[getAmountOfDaysUsed()];
    private PagerSlidingTabStrip tabs;
    private ViewPager pager;
    private MyPagerAdapter adapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_input_slessontime);


        tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
        pager = (ViewPager) findViewById(R.id.pager);
        adapter = new MyPagerAdapter(getSupportFragmentManager());

        final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources()
                .getDisplayMetrics());
        pager.setPageMargin(pageMargin);

        tabs.setViewPager(pager);


        if (savedInstanceState == null) {
            getFragmentManager().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.input_slessontime, 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);
    }

    /**
     * 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_input_slessontime, container, false);
            return rootView;
        }
    }

    public int getAmountOfDaysUsed(){
        db = new DatabaseHelper(getApplicationContext());   

        List<MC_sschoolday> MC_sschoolday = db.getAllSSchoolDays(); //gets all the lessons and stores them in a list

        int amountOfDaysUsed=0;

        MC_sschoolday[] sday = new MC_sschoolday[7]; 
        for (int i =0; i<7; i++){
            sday[i]=MC_sschoolday.get(i); //stores the lessons in an array

         }

        for (int i =0; i<7; i++){
            if(sday[i].getUsed().equals("y")){
                amountOfDaysUsed++;
            }
        } 

        db.close();
        return amountOfDaysUsed; 
    }
    public void getTitles(){
        db = new DatabaseHelper(getApplicationContext());   
        MC_sschoolday[] sday = new MC_sschoolday[7];
        List<MC_sschoolday> schoolday = db.getAllSSchoolDays();

        int usedCount2=0;
        for (int i =0; i< db.getAllSSchoolDays().size(); i++){
            sday[i]=schoolday.get(i);
            if(sday[i].getUsed().equals("y")){
                days[usedCount2] = sday[i].getschool_day();
                usedCount2++;
            }
        }
        db.close();
    }


    public class MyPagerAdapter extends FragmentPagerAdapter {



        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return days[position];
        }

        @Override
        public int getCount() {
            return getAmountOfDaysUsed();
        }

        public android.support.v4.app.Fragment switchFragmentDay(int num) {
            DatabaseHelper db;
            db = new DatabaseHelper(getApplicationContext());   
            MC_sschoolday[] sday = new MC_sschoolday[7];
            List<MC_sschoolday> schoolday = db.getAllSSchoolDays();
            int usedCount1=getAmountOfDaysUsed();


            int [] dayID = new int[usedCount1];

            int usedCount2=0;
            for (int i =0; i< db.getAllSSchoolDays().size(); i++){
                sday[i]=schoolday.get(i);
                if(sday[i].getUsed().equals("y")){
                    dayID[usedCount2] = (int) sday[i].getSchool_day_id();
                    usedCount2++;
                }
            }
            db.close();
            switch (dayID[num]){
            case 1:
                return new Input_slessontime_monday();
            case 2:
                return new Input_slessontime_tuesday();
            case 3:
                return new Input_slessontime_wednesday();
            case 4:
                return new Input_slessontime_thursday();
            case 5:
                return new Input_slessontime_friday();
            case 6:
                return new Input_slessontime_saturday();
            case 7:
                return new Input_slessontime_sunday();
            }
            return null;

        }

        @Override
        public android.support.v4.app.Fragment getItem(int position) {

            switch (position){              
            case 0:
                return switchFragmentDay(0);
            case 1:
                return switchFragmentDay(1);
            case 2:
                return switchFragmentDay(2);
            case 3:
                return switchFragmentDay(3);
            case 4:
                return switchFragmentDay(4);
            case 5:
                return switchFragmentDay(5);
            case 6:
                return switchFragmentDay(6);

            }

        return null;
        }

    }


}

thanks for your help!

Answer

String[] days = new String[getAmountOfDaysUsed()];

You’re using the activity as a Context too early, at member variable initialization. You need to wait until onCreate() or later in the activity lifecycle.

Leave a Reply

Your email address will not be published. Required fields are marked *