【问题标题】:My app is unable to start activity?我的应用无法启动活动?
【发布时间】:2012-01-14 02:05:50
【问题描述】:

当我尝试在手机上运行该应用程序时,它会在我尝试执行活动 3 时强制关闭。 Logcat 说:

01-13 17:53:25.368: E/AndroidRuntime(3235): 引起: java.lang.NullPointerException 01-13 17:53:25.368: E/AndroidRuntime(3235): 在 android.app.activity3.onCreate(activity3.java:18)

第 18 行在哪里

Button wg = (Button) findViewById(R.id.Back); 

这是我的 activity3.java 的完整代码:

package android.app;
import android.app.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;


public class activity3 extends Activity{

    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main3);

        Button wg = (Button) findViewById(R.id.Back);
        wg.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Intent intent = new Intent();
                setResult(RESULT_OK, intent);
                finish();
            }

        });
    }
}

提前致谢

【问题讨论】:

  • 这里 main3.xml schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height ="fill_parent" android:orientation="vertical" android:text="@string/Back" >

标签: java android eclipse logcat


【解决方案1】:

你需要修改你的xml:

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

    <!-- your textview -->
    <TextView
        android:id="@+id/text1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/text1"
        android:textAppearance="?android:attr/textAppearanceMedium"
        />

    <!-- your back button -->
    <Button
        android:id="@+id/back"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/Back"
        />

</RelativeLayout>

我做了什么:

  • 从根 RelativeLayout 中删除了文本和方向,这些没有任何作用。
  • 修改了您的高度和宽度,请随意更改。
  • 添加了一个按钮,其 id 为 R.id.back,文本为 @string/Back。

您现在可以使用 findViewById(R.id.back) 引用您的按钮并设置您的点击监听器。

【讨论】:

  • 谢谢!即使你是最后一个我喜欢这个答案,这也付出了最大的努力。其他的,谢谢
【解决方案2】:

我在 xml 中没有看到按钮。一旦你有了它,它就需要:

android:id="@+id/Back"

【讨论】:

  • O 所以我应该在 xml 中添加一个按钮?
  • 是的。当您说“findViewById”时,它正在寻找 XML 中的视图。它没有找到它并抛出一个空指针。
【解决方案3】:

发生这种情况是因为您没有在视图中声明按钮。只有一个文本视图。您必须在视图中创建按钮。您没有引用任何内容,因此为空。

你可以找到一个很好的例子来说明如何制作一个按钮here

【讨论】:

    【解决方案4】:

    您没有在 xml 中发布 id 为“Back”的按钮,这就是为什么您在那里得到 null 的原因。在您的 xml 中添加按钮条目。

    【讨论】:

      猜你喜欢
      • 2017-05-31
      • 1970-01-01
      • 2014-10-11
      • 1970-01-01
      • 1970-01-01
      • 2016-04-21
      • 1970-01-01
      • 2012-07-08
      相关资源
      最近更新 更多