Converting EditText to TextView type in android studio [duplicate]
Converting EditText to TextView type in android studio [duplicate]
This question already has an answer here:
I'm trying to convert my EditText to String type and then evaluate a mathematical expression(given by user) to display it in a textView type but my app crashes every time a try to run it.
package com.example.abhishek.edittexttrial;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
//import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import net.objecthunter.exp4j.Expression;
import net.objecthunter.exp4j.ExpressionBuilder;
public class MainActivity extends AppCompatActivity {
private TextView txtScreen = (TextView)findViewById(R.id.txtScreen);
private EditText etxt = (EditText)findViewById(R.id.editText);
private double ans;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btnCalc).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
display();
}
});
}
public void display(){
try{
String str = etxt.getText().toString().trim();
String result = str.substring(0, str.length() - 1);
Expression exp = new ExpressionBuilder(result).build();
this.ans = exp.evaluate();
txtScreen.setText(Double.toString(ans));
}catch(NumberFormatException exception){
this.ans = 0;
txtScreen.setText(Double.toString(ans));
}
}
}
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
findViewById()
onCreate()
setContentView()
private TextView txtScreen;
onCreate()
txtScreen = (TextView)findViewById(R.id.txtScreen);
You can't call
findViewById()
in a field initializer; i.e., outside of a class method. Move those calls to insideonCreate()
, after thesetContentView()
call. For example,private TextView txtScreen;
, then inonCreate()
,txtScreen = (TextView)findViewById(R.id.txtScreen);
.– Mike M.
6 mins ago