• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Start Activity from Helper Class

Ikr

Lurker
I'm trying to start an activity from a helper class when a menu item is clicked.

The code crashes here specifically:

Code:
Intent intent = new Intent(context, LoginActivity.class);
startActivity(intent);
finish();

***************************************************************

Here is my class:

Code:
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.widget.Toast;

import java.util.Locale;

public class MenuHelper extends Activity {

    private static final int MENU_LOGIN = Menu.FIRST;
    private static final int MENU_REGISTER = Menu.FIRST + 1;
    private static final int MENU_LOGOUT = Menu.FIRST + 2;
    private static final int MENU_LANG = Menu.FIRST + 3;

    private static Context context;

    public static Menu prepareMenu(Menu menu){
        menu.clear();
        menu.add(0, MENU_LOGIN, Menu.NONE, R.string.login).setIcon(R.drawable.user);
        menu.add(0, MENU_REGISTER, Menu.NONE, R.string.register);
        //if(auth.isLoggedIn()) {
        if(true) {
            menu.add(0, MENU_LOGOUT, Menu.NONE, R.string.logout);
        }

        //Locale currentLocale = getResources().getConfiguration().locale;
        String loc = Locale.getDefault().getLanguage();
        if(loc == "en") {
            menu.add(0, MENU_LANG, Menu.NONE, R.string.arabic);
        }
        else{
            menu.add(0, MENU_LANG, Menu.NONE, R.string.english);
        }

        return menu;
    }

    public boolean itemSelected(Integer item, Context c) {
        context = c;
        switch (item) {
            case MENU_LOGIN: // login
                //doAddStuff();
                Toast.makeText(context, "Login Clicked", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(context, LoginActivity.class);
                startActivity(intent);
                finish();
                break;
            case MENU_REGISTER: // register
                //doListStuff();
                Toast.makeText(context, "Register Clicked", Toast.LENGTH_SHORT).show();
                break;
            case MENU_LOGOUT: // logout
                //if(auth.isLoggedIn()) {
                if(true) {
                    //doLogout();
                    Toast.makeText(context, "Logout Clicked", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(context, "Already logged out", Toast.LENGTH_SHORT).show();
                }
                break;
            case MENU_LANG: // language
                break;
        }
        return false;
    }
}
 
Thanks I found the fix:

Intent intent = new Intent(context, LoginActivity.class);
context.startActivity(intent);
 
Back
Top Bottom