This is the error I get when I try this call from an outside class. Thanks in Advance.
Function Call
GuessingLettersActivity.userGuess();
Error
Cannot make a static reference to the non-static method userGuess() from the type GuessingLettersActivity
Function in Main Activity (GuessingLettersActivity)
public void userGuess()
{
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Enter A Guess");
alert.setMessage("Enter your guess below. Just enter the letter or symbol. It is case sensitive!");
// Set an EditText view to get user input
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
CharSequence val开发者_如何学JAVAue = input.getText();
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
// see http://androidsnippets.com/prompt-user-input-with-an-alertdialog
}
to activate non static method, you must have an instance, otherwise - what will this
refer to?
you can create a dummy instance and invoke userGuess() on it: (new GuessingLettersActivity()).userGuess();
however, if you realy do not need an instance, the this
is not really needed, find a way not to use it, and declare userGuess()
as static, it will be much more elegant.
if the instance is critical, there is a code smell here, how come you want to invoke userGuess() as static, but you need a specific instance? this can create a bug that will be caught only on later stages, so I suggest investigating it now.
The solution was to change how I get context in the onCreate function. It is not this which is passed to the alertDialog function and works like a champ
context = this;
The reason for this is because you are trying to make a static reference to a non-static method as the error suggests. Change your method signature to the following:
public static void userGuess()
精彩评论