【问题标题】:How to use StringUtils and myString, getting cannot resolve error如何使用 StringUtils 和 myString,得到无法解决错误
【发布时间】:2015-02-25 18:35:56
【问题描述】:

运行以下代码,但无法解析 StringUtils 和 myString... 是否需要导入某些内容或是否有其他方法?这从另一个活动中获取一个字符串,并将其设为一个整数,以允许计算旧值和新值。

   protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            // Setting button as a unique name
            Button buttonAdd = (Button) findViewById(R.id.add_button);
            Button buttonAbout = (Button) findViewById(R.id.about_button);
            Button buttonReset = (Button) findViewById(R.id.reset_button);


            String calorie = getIntent().getStringExtra("calorie");
            TextView textView1 = (TextView)findViewById(R.id.textView1);

            String strOldValue = textView1.getText().toString();

            Integer oldValue = StringUtils.isNotBlank(myString) ? Integer.parseInt(myString) : 0;
            Integer newValue = Integer.parseInt(calorie);



            textView1.setText((oldValue + newValue));

【问题讨论】:

  • myString不是变量,改成strOldValue
  • 如何初始化 myString ?
  • 如果你以 Intent 传递它,你必须调用 myString = getIntent().getStringExtra("YOUR_KEY")

标签: java android android-studio


【解决方案1】:

最安全的方法是使用try {} catch {}阻止如下代码

Integer oldValue;
try{
 oldValue= Integer.parseInt(myString);
}catch(NumberFormatException e){
  oldValue =0;
}

而不是:

 Integer oldValue = StringUtils.isNotBlank(myString) ? Integer.parseInt(myString) : 0;

【讨论】:

  • 他从不显示 myString 的声明,我认为它也不存在。
  • 如果我很好理解他,他会从其他活动传递这个字符串。我想这些代码已被删除以更清晰
  • @Tom 你是什么意思?您初始化 myString 值。对吗?
【解决方案2】:

补充康拉德的答案:

您应该包含所有代码...

如果你试图从之前的 Activity 中获取一个字符串,然后将其解析为一个整数,为什么不直接将它作为一个 int 传递并执行类似的操作:

声明类级变量

private int mPassedInValue;

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

 // Get the Extras Bundle from the Intent
 Bundle previousIntentExtras  = getIntent().getExtras();

 // Check to make sure this is not null
 if(previousIntentExtras != null){
    mPassedInValue = previousIntentExtras.getInt("MyInt",0);

  /* ... Perform the function you want to do since the value you passed in is
   * Is already in the correct form...
   */ 

 }

} 

【讨论】:

    猜你喜欢
    • 2013-06-29
    • 1970-01-01
    • 2017-02-26
    • 2021-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-11
    • 1970-01-01
    相关资源
    最近更新 更多