I am pretty new to android app development and java and I encountered the following error when trying to call a method from another class:
Cannot make a static reference to the non-static method showToast(String) from the type LoginActivity
The reason I want to call this in the other class and not instantiate it in the class itself is because of adaptability and upgradeability issues. This seems a fine concept by me or is it something that is way overrated?
The relevant code is:
CreateAccountActivity
public class NewAccountActivity extends Activity{
private Button mCreateAccountButton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newaccount);
mCreateAccountButton = (Button) findViewById(R.id.createaccount_button);
registerButtonListeners();
}
private void registerButtonListeners() {
mCreateAccountButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
LoginActivity.showToast(getString(R.string.createaccount_message));
}
});
}
}
LoginActivity
public void showToast(String toastString) {
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root));
ImageView image = (ImageView) layout.findViewById(R.id.toastImage);
image.setImageResource(R.drawable.android);
TextView text = (TextView) layout.findViewById(R.id.toastText);
text.setText(toastString);
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
toast.show();
}
Creating a new LoginActivity object and then calling showToast on it makes the error messages go away but gives me a NullPointerException instead.
if you want to call showToast in the static way you have to make the method showToast static.
Edit: where do you get the NullPointerException?