java - Android Studio: Getters for editText
问题描述
I want to use the value of 2 editTexts from one activity in another. Here is my code so far. I am getting:
java.lang.NullPointerException.
The Code:
public class AddJob extends AppCompatActivity{
// vars
private BottomNavigationView bottomNavigationView;
private EditText editTextLat, editTextLng;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_job);
TextView textView = findViewById(R.id.activityTitleAddJob);
textView.setText("Add a Job");
editTextLat = findViewById(R.id.editTextLat);
editTextLng = findViewById(R.id.editTextLng);
}
public int getLatitude() {
return new Integer(editTextLat.getText().toString());
}
public int getLongitude() {
return new Integer(editTextLng.getText().toString());
}
}
The Stack Trace:
Here is the code snippet from the map class:
AddJob aj = new AddJob();
int lat = aj.getLatitude();
int lng = aj.getLongitude();
Toast.makeText(aj, lat + " " + lng, Toast.LENGTH_LONG).show();
解决方案
请阅读Activity 生命周期。您永远不应该 直接使用
new MyActivity()
这不会启动任何生命周期事件(onCreate
等)或将其绑定到上下文、在其上设置视图层次结构或执行您可能期望的任何常规 Activity 事情。您的程序返回 null 因为onCreate
从未在活动上调用过,如果您只是尝试自己调用它,它可能会崩溃。
如果您希望一个活动的数据在另一个活动中可用,实现此目的的一种简单方法是将数据保存在活动的SharedPreferences中AddJob
(每当更新值时)并MapActivity
从SharedPreferences
. 您还可以通过在启动 Intent 时将数据添加到 Intent 来将数据从一个 Activity 传递到下一个 Activity。
在这里使用 SharedPreferences 的一个优点是用户的选择将从一个应用程序会话保存到下一个应用程序会话,并且如果您有多个可以启动的东西,MapActivity
他们不必一直将这些数据传递给它。
推荐阅读
- flutter - Flutter - 如何用鼠标指针绘制矩形并获取坐标
- type-inference - TypeScript:通过泛型函数时恢复“对象文字只能指定已知属性”检查
- javascript - 计算多个json输入js
- ivy - 在 Angular 10 错误 NG6003 上激活 Ivy 编译器时出错 - 无法解析为 NgModule
- windows - 我安装了 Neo4j 服务。它们究竟是哪些文件,它们在哪里?
- sql - 从单个日期列分别创建开始和结束日期列
- hotwire-rails - 如何重新加载单个涡轮帧并更新 url?
- python - 如何在多个文件上运行脚本
- python - 将许多列添加到数据框中的最快方法是什么?
- xamarin.forms - 如何在 Azure Devops 中为生成 nuget 包的 Xamarin Forms Android 库项目创建 YAML 管道