Search code examples
androidoncreate

Getting Error while call a method from adapter class. java.lang.IllegalStateException: System services not available to Activities before onCreate()


When I try to call a method from my adapter class, I'm getting an error System services not available to Activities before onCreate();

MainTask.Class

public class MainTask extends AppCompatActivity  {
    public static final String mypreference = "mypref";
    public static String Name = "nameKey";
    SharedPreferences taskcount, currenttime;
    public static int completask;
    long shared_time;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_task);
             Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        ViewPager viewPager = (ViewPager) findViewById(R.id.viewPager);
       setupViewPager(viewPager);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabLayout);
        tabLayout.setupWithViewPager(viewPager);//setting tab over viewpager

        taskcount = getSharedPreferences(mypreference,
                MainActivity.MODE_PRIVATE);
        completask = taskcount.getInt(Name, 0);

    }
public void propertask(){
    final NiftyDialogBuilder dialog1 = NiftyDialogBuilder.getInstance(MainTask.this);
    Effectstype effect;
    effect = Effectstype.SlideBottom;
    dialog1.setCancelable(false);
    dialog1.isCancelableOnTouchOutside(false)
            .withTitle(null)
            .withMessage(null)
            .withEffect(effect)
            .setCustomView(R.layout.proper_task, MainTask.this)
            .show();


    Button rate = (Button) dialog1.findViewById(R.id.rate_button);


    rate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            dialog1.dismiss();

        }
    });
    dialog1.show();
}

GridListAdapter.Java

 if(taskvalue==0)
     {
   MainTask mainTask=new MainTask();
   mainTask.propertask();

  }

Please help me, how I can access propertask method from my Adapter class. Thanks in advance.


Solution

  • You do not have to create an object for an Activity. Actually what CommonsWare said you shouldn't do it.

    You can call that function like this

    if(taskvalue==0)
     {
      // assuming you have passed context to your adapter. If not, then do it.
      ((MainTask)context).propertask();
    
     }
    

    EDIT: As you said in your comments "you do not have context so you couldn't made Dialog from Adapter". But now since you have passed it, you can do it now from your Adapter and remove this unnecessary casting-to-activity function call.