【问题标题】:Using getIntent() in onCreate() prevents ui from loading... why?在 onCreate() 中使用 getIntent() 会阻止 ui 加载...为什么?
【发布时间】:2020-06-23 15:05:09
【问题描述】:

我有一个列出授权用户的活动,我在活动的onCreate() 方法中使用getIntent() 来检查活动是否应该在加载时显示一个预先填写的添加用户对话框。这是我的代码:

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 刷新,我如何才能实现我正在寻找的功能?

【问题讨论】:

  • 我认为您遇到了异常,请评论 try catch 块并运行
  • 如果我这样做它会加载,但我确实需要检查意图

标签: android user-interface android-intent oncreate


【解决方案1】:

如果你打算不管是否有异常都运行 refreshList 方法,你可以尝试使用 finally 块,它会运行代码而不管异常。

【讨论】:

  • 为什么和我现在的有什么不同?如果我吞下异常,无论如何都应该继续执行下一行。
  • 此代码失败的最可能原因是某处可能存在异常,这就是为什么它不会进入下一行我的建议是如果你不使用 finally 块t 打算做任何例外的事情。这只是一种安全编码的方式。
猜你喜欢
  • 1970-01-01
  • 2011-03-27
  • 1970-01-01
  • 2018-02-16
  • 2010-10-24
  • 2012-06-21
  • 1970-01-01
  • 1970-01-01
  • 2016-02-03
相关资源
最近更新 更多