android - 在 onCreate() 中使用 getIntent() 会阻止 ui 加载...为什么?
问题描述
我有一个列出授权用户的活动,我getIntent()
在活动的onCreate()
方法中使用它来检查活动是否应该在加载时显示一个预填充的添加用户对话框。这是我的代码:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sms_auth_manager);
try{ //check if the activity was launched with a prefill intent
Intent intent = getIntent();
int id = (intent.getIntExtra("notification_id",0));
NotificationUtils notificationUtils = new NotificationUtils();
notificationUtils.hideNotification(this,id);
if (intent.getBooleanExtra("isPrefill",false)){
String preFill = intent.getStringExtra("sender");
showAddUserDialog(preFill);
}
}catch (Exception ignore){} //exception swallowed means no dialog
refreshList(); //loads the list of users into the main listview of the activity
}
我的问题是调用refreshList()
不会导致列表被刷新。我也尝试将它放在 try 块之前,但无论哪种方式都行不通。我用注释掉的 try 块进行了测试,这确实有效,但后来我失去了功能。
以下是该refreshList()
方法的代码,以备不时之需:
private void refreshList(){
SharedPreferences sharedPrefs = getSharedPreferences("users",0);
LinearLayout ll = findViewById(R.id.ll);
ll.removeAllViews();
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT
);
for (String sender : sharedPrefs.getAll().keySet()) {
CheckBox checkBox = new CheckBox(this);
checkBox.setText(getContactDisplayName(sender));
checkBox.setTag(sender);
try{
checkBox.setChecked(sharedPrefs.getBoolean(sender,false));
}catch (Exception e){
checkBox.setChecked(false);
}
checkBox.setLayoutParams(layoutParams);
checkBox.setOnClickListener(v -> {
try {
sharedPrefs.edit().putBoolean(sender, checkBox.isChecked()).apply();
}catch (Exception e){
Toast.makeText(this, "Preference not updated.\n"+e.getMessage(),
Toast.LENGTH_SHORT).show();
}
});
checkBox.setOnLongClickListener(v -> {
showPopupMenu(v);
return false;
});
ll.addView(checkBox);
}
}
为什么 try 块会阻止 UI 刷新,我如何才能实现我正在寻找的功能?
解决方案
如果您打算运行 refreshList 方法,无论是否存在异常,您都可以尝试使用 finally 块来运行代码,而不管异常如何。
推荐阅读
- html - css 的 .htaccess 文件路径
- excel - 传递布尔值的问题 - VBA ADODB Oracle 存储过程
- algorithm - 求两个三角形之间最小距离的算法
- arrays - 垂直扩展 R 3D 数组
- amazon-web-services - 比较 AWS S3 中的 avro 数据类型
- python - 从 .tif 文件中减去 2 个像素值会给出错误的结果
- css - WordPress:独特的自定义插件 CSS
- java - Android - 从另一个类调用时,MediaPlayer 不会释放
- applescript - Applescript 移动到具有顺序命名的新文件夹
- uml-designer - 如何在 UML Designer 中指定操作返回类型?