java - 我的应用程序无法启动 Activity ?

标签 java android eclipse logcat

当我尝试在手机上运行该应用程序时,当我尝试执行 Activity 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();
            }

        });
    }
}

提前致谢

最佳答案

您需要修改您的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) 引用您的按钮并设置您的点击监听器。

关于java - 我的应用程序无法启动 Activity ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8859578/

相关文章:

java - 递归打印 ArrayList<ArrayList<String>> 的所有可能组合

android - Admob 横幅布局错误,以编程方式设置大小

android - Android 上的 JPEG2000 查看器和支持

java - 滑动拼图代码

java - 如何在 Spring Boot 中通过代码创建 couchbase 存储桶

java - 获取仅包含 JSON 的日志

java - android中使用WebView显示页面时如何处理白屏和清除之前的web缓存?

从通知发送的android明确 Intent

c++ - gcc 版本会影响 malloc 等功能吗?

java - 如何在 Java EE Spring Boot Web 应用程序中使用 Angular 2 减少构建时间