首页 > 解决方案 > 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:

enter image description here

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();

标签: javaandroidgetter

解决方案


请阅读Activity 生命周期。您永远不应该 直接使用

new MyActivity()

这不会启动任何生命周期事件(onCreate等)或将其绑定到上下文、在其上设置视图层次结构或执行您可能期望的任何常规 Activity 事情。您的程序返回 null 因为onCreate从未在活动上调用过,如果您只是尝试自己调用它,它可能会崩溃。

如果您希望一个活动的数据在另一个活动中可用,实现此目的的一种简单方法是将数据保存在活动的SharedPreferencesAddJob(每当更新值时)并MapActivitySharedPreferences. 您还可以通过在启动 Intent 时将数据添加到 Intent 来将数据从一个 Activity 传递到下一个 Activity。

在这里使用 SharedPreferences 的一个优点是用户的选择将从一个应用程序会话保存到下一个应用程序会话,并且如果您有多个可以启动的东西,MapActivity他们不必一直将这些数据传递给它。


推荐阅读