I am extremely extremely new to Java and programming in general. I wrote this for a basic program to add 2 numbers input by the user and add them up and display them in the output box, however I'm getting Non-static method 'setText(java.lang.CharSequence)' cannot be referenced from a static context
, but I don't know what the static thing is
private void onClick(View v) {
EditText input1 = (EditText) findViewById(R.id.input1);
double calc1 = Double.parseDouble(String.valueOf(input1));
EditText input2 = (EditText) findViewById(R.id.input2);
double calc2 = Double.parseDouble(String.valueOf(input2));
double total = calc1 + calc2;
String result = Double.toString(total);
EditText output1 = (EditText) findViewById(R.id.output);
EditText.setText(result);
}
The line giving the error:
EditText.setText(result);
Sorry if I'm being extremely incompetent but I searched and I couldn't really understand how to fix it. Thanks.
There is one simple way of solving the non-static variable cannot be referenced from a static context error. Address the non-static variable with the object name. In a simple way, we have to create an object of the class to refer to a non-static variable from a static context.
Therefore, this issue can be solved by addressing the variables with the object names. In short, we always need to create an object in order to refer to a non-static variable from a static context. Whenever a new instance is created, a new copy of all the non-static variables and methods are created.
And if no class instance is created, the non-static variable is never initialized and there is no value to reference. For the same reasons, a non-static method cannot be referenced from a static context, either, as the compiler cannot tell which particular object the non-static member belongs to.
i.e. referring a variable using static reference implies to referring using the class name. But, to access instance variables it is a must to create an object, these are not available in the memory, before instantiation. Therefore, you cannot make static reference to non-static fields(variables) in Java.
In a static context, you don't have an object (instance of the class), but the instance variables and methods depend on them.
You have an instance, called output1, but you try to call your method 'setText' through the class's name (which is a static approach).
Change your lines
EditText output1 = (EditText)findViewById(R.id.output);
EditText.setText(result);
to
EditText output1 = (EditText)findViewById(R.id.output);
output1.setText(result);
Change
EditText.setText(result);
to
output1.setText(result);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With