使用Eclipse(Android)奇怪的错误

时间:2013-04-09 12:53:49

标签: java android eclipse

我仍在学习编码,但我持久编码的应用程序无法在2种不同的设备上运行。 Eclipse(最新的android sdk)是错误还是我的每个应用程序的代码错误? 它的力量在2台设备上关闭

    public class MainActivity extends Activity {


Button dugme = (Button) findViewById(R.id.dugme);

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

    dugme.setOnClickListener(new View.OnClickListener(){

@Override
    public void onClick(View v) {
            Cao();
        }   
        });



}
private void Cao(){
    Intent Cao = new Intent(this, Cao.class);
    startActivity(Cao);
}}

这是曹班

    public class Cao  extends Activity{


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

和Manifest

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.book1"
    android:versionCode="1"
     android:versionName="1.0" >

    <uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="17" />

    <application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.example.book1.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.book1.Cao"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.Action.VIEW" />

            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
      </activity>
      </application></manifest>

3 个答案:

答案 0 :(得分:5)

尝试放

Button dugme = (Button) findViewById(R.id.dugme);

onCreate方法中的这一行。一个班级只有变量和方法。这条线是定义。所以我认为这只是代码中的问题。除了你的代码没有任何问题。

答案 1 :(得分:1)

把这一行

Button dugme = (Button) findViewById(R.id.dugme)

之后

setContentView(R.layout.activity_main)
  

Android根据每个布局xml

获取view_id的每个引用

如果android在设置给定活动的布局之前考虑了视图reference_id,那么我们甚至不能为两个不同的布局xml保留相同的视图ID名称。

答案 2 :(得分:0)

这一行错了:

Button dugme = (Button) findViewById(R.id.dugme);

不是因为它不在onCreate方法中,而是因为它出现在此行之前:

 setContentView(R.layout.activity_main);

原因是:如果您没有将布局设置为活动的内容视图,则无法使用findViewById方法,因为找不到此视图的位置(您的布局尚未设置。)