我已经初始化了一个双变量,并希望在TextView中显示它
变量名用红色下划线。
我试图将其解析为字符串,但没有成功
public class MainActivity extends AppCompatActivity {
Location currentloc = new Location("currentloc");
double currlat = 0.0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView gpsbox = (TextView) findViewById(R.id.gpsView);
try {
currlat = currentloc.getLatitude();
} catch(Exception e) {
Toast.makeText(this, "Hello, an exception was just thrown but I catched it. " + e.toString(), Toast.LENGTH_SHORT).show();
}
gpsbox.setText(currlat);
setContentView(R.layout.activity_main);
}
}
您必须通过将其分配给String
String.valueOf(currlat);
我希望它对你有用。
尝试这个
setContentView(R.layout.activity_main);
TextView gpsbox = (TextView) findViewById(R.id.gpsView);
try {
currlat = currentloc.getLatitude();
} catch(Exception e) {
Toast.makeText(this, "Hello, an exception was just thrown
but I catched it. " + e.toString(), Toast.LENGTH_SHORT).show();
}
gpsbox.setText(String.valueOf(currlat));
代码中有两个错误。
- Set content视图在findViewById之后使用,这将引发异常
-
double应该用String.valueOf((方法包装以转换为字符串。
公共类MainActivity扩展了AppCompatActivity{
Location currentloc = new Location("currentloc"); double currlat = 0.0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView gpsbox = (TextView) findViewById(R.id.gpsView); try { currlat = currentloc.getLatitude(); } catch (Exception e) { Toast.makeText(this, "Hello, an exception was just thrown but I catched it. " + e.toString(), Toast.LENGTH_SHORT).show(); } gpsbox.setText(String.valueOf(currlat)); }
}