简体   繁体   中英

Trouble launching activity from class method

I'm new to Java and Android Studio, and to learn I'm building a character generator app for Dungeons and Dragons. You choose a race, character class, and skills, then the app calculates everything and builds a final character sheet.

I have an activity that allows the user to select a class (fighter, wizard, etc.) from a list. It then stores the selection in a SharedPreferences File.

I want to call different sub activities for different classes. In these activities, a selection is made and is written to the SharedPreferences File. For example, a fighter gets to choose a fighting style while a wizard gets to choose spells.

Right now I have a (java)class for the fighter class, and one for the wizard class. Both have a public void create() method.

Calling the method:

if (chosenClass.equalsIgnoreCase("fighter")){
            Fighter classObject = new Fighter();
            Fighter.create();
        }

Here is the code from the Fighter class:

import android.content.Intent;

public class Fighter {

    public Fighter(){}

    public void create(){
        Intent fightingStyle = new Intent(this, ChooseFightingStyle.class);
        startActivity(fightingStyle);
    }  
}

However, I'm getting an error message saying "Cannot resolve constructor 'Intent(...)'

Can anyone give me some insight on what I'm doing wrong? Or suggestions on how to do this better? Thanks so much.

That's because "this" in your case does not represent a Context, you should try something like this:

public void create(Context context){
    Intent fightingStyle = new Intent(context, ChooseFightingStyle.class);
    startActivity(fightingStyle);
} 

As per documentation of Intent class constructors, they can take a string as first argument or a Context. Your Fighter class should be of type Context to pass it as argument. However, if you have a reference to the context, you can pass it too in the Intent constructor.

A suggestion: when you select the Fighter class from the list in the main activity, you can pass the context from the main activity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM