gpt4 book ai didi

java - 使用注释在空对象引用上设置文本

转载 作者:行者123 更新时间:2023-12-02 12:44:01 27 4
gpt4 key购买 nike

它不重复,没有 ANDROIDANNOTATIONS 的同一个应用程序工作正常。

由于使用 AndroidAnnotations Framework 修改项目,我的应用程序已停止工作。在我看来,一切看起来都很好,AndroidStudio 中没有任何警告,直到在手机上运行时,应用程序出现错误:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.annotationstest/com.example.annotationstest.MainActivity_}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference

我应该修复或添加什么到代码中?

主要 Activity

 @EActivity(R.layout.activity_main)
public class MainActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {

private static final String SHARED_PREFS_NAME = "abc";
public static final int REQUEST_CODE = 100;
private int number;

@ViewById(R.id.tv2)
TextView tv2;

@ViewById(R.id.tv3)
TextView tv3;

@ViewById(R.id.switch1)
Switch switch1;


@Click
void b1() {
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
startActivityForResult(intent, REQUEST_CODE);
}


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

SharedPreferences preferences = getSharedPreferences(SHARED_PREFS_NAME, MODE_PRIVATE);
number = preferences.getInt("NUMBER", 0);
tv2.setText(""+number);
switch1.setOnCheckedChangeListener(this);

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_CODE) {
number = data.getExtras().getInt("number");
tv2.setText("" + number);
saveNumberToSharedPrefs(number);

}
}
}

private void saveNumberToSharedPrefs(int num) {
SharedPreferences preferences = getSharedPreferences(SHARED_PREFS_NAME, MODE_PRIVATE);
preferences.edit().putInt("NUMBER", num).apply();
}

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

switch (buttonView.getId()) {
case R.id.switch1:
if (isChecked == true) {
tv3.setVisibility(View.VISIBLE);
} else {
tv3.setVisibility(View.INVISIBLE);
}
break;
}

}
}

最佳答案

根据文档, View 可能尚未注入(inject)到 onCreate() 方法中(请参阅 here ):

When onCreate() is called, @ViewById fields are not set yet. Therefore, you can use @AfterViews on methods to write code that depends on views.

也就是说,您应该将代码从 onCreate() 移至新方法,并使用 @AfterViews 进行注释

关于java - 使用注释在空对象引用上设置文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44847949/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com