无法启动另一个“活动”在Android中 - 发生错误 [英] Can't start another "Activity" in Android - Gives Error

查看:171
本文介绍了无法启动另一个“活动”在Android中 - 发生错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个较大代码的简化版本。我刚刚开始使用Android编程,并严重阻碍了这个问题一个多小时。

This is simplified version of a larger code. I've just started with Android programming and badly stuck with this problem for past an hour.

    /**Main Activity**/

    sumBut.setOnClickListener(new OnClickListener(){
        @Override
        public void onClick(View arg0) {
            Intent intent = new Intent(MainActivity.this, SumActivity.class);
            intent.putExtra("var1", et1.getText().toString());
            intent.putExtra("var2", et2.getText().toString());
            startActivity(intent);
        }
    });

此代码从文本框中获取两个变量,并将用户驱动到另一个活动,其中总和将显示数字。

This code takes two variable from the text boxes and drives the user to another activity where the sum of these numbers will be shown.

这是目标活动:

    public class SumActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sum);

    TextView tv = (TextView) findViewById(R.id.textView1);
    Intent intent = getIntent();
    int a = Integer.parseInt(intent.getStringExtra("var1"));
    int b = Integer.parseInt(intent.getStringExtra("var2"));
    int c = a+b;
    tv.setText(c);
}

所有类的res / layout文件夹内都有关联的xml文件, ve创建。

There are associated xml files inside res/layout folder for all the classes I've created.

我的Manifest.xml文件中的示例

  <activity
        android:name="com.example.summer.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name="com.example.summer.SumActivity"></activity>
    <activity android:name="com.example.summer.DifActivity"></activity>

LogCat

推荐答案

这是你的问题

 tv.setText(c);

将其更改为

 tv.setText(String.valueOf(c));

有不同的 setText()方法您将在文档中看到这里。您调用的那个,它接受一个 int 作为参数,用于查找具有该'id'的资源,因此您需要将变量更改为字符串。这就是为什么你得到一个资源未找到异常。它不能找到 String资源 id 的任何变量 c 是。

There are different setText() methods as you will see here in the docs. The one that you are calling, which accepts an int as a parameter, is used to find a resource with that 'id' so you need to change your variable to a String. This is why you get a Resource Not found exception. It can't find a String resource with the id of whatever variable c is.

只是一个旁注,但你可能想要将解析代码包裹在一个 try / catch 除非您正在进行其他错误检查,否则,如果用户输入非整数值,则可能会导致数字格式异常

Just a side note but you might want to wrap your parsing code in a try/catch unless you are doing some other error checking or you may end up with a Number Format Exception if the user enters a non-integer value.

这篇关于无法启动另一个“活动”在Android中 - 发生错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆