[英]it closes rapidly as soon as it opens on running in physical device
java android
主要活動
這里在物理設備上運行時應用程序快速關閉,只能看到應用程序打開和關閉的 flash 用於添加 2 個數字,沒有顯示錯誤,應用程序運行時沒有錯誤,但在 logcat 中顯示“無法實例化活動 ComponentInfo{com .example.addingtwonumbers/com.example.addingtwonumbers.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference"
package com.example.twonumbersaddition;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity
{
EditText n1 = (EditText)findViewById(R.id.INPUT1);
EditText n2 = (EditText)findViewById(R.id.INPUT2);
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void add(View v) //add method for adding 2 numbers
{
int i = Integer.parseInt(n1.getText().toString());
int j = Integer.parseInt(n2.getText().toString());
int k= i+j;
}
}
清單文件
清單文件
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.addingtwonumbers">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.AddingTwoNumbers">
<activity android:name=".MainActivity"> // activity is defined as
<intent-filter>//it is automatically ,have not modified it
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
調用 setContentView 后,將 findViewById 調用移至 onCreate 方法。
public class MainActivity extends AppCompatActivity
{
EditText n1;
EditText n2;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
n1 = (EditText)findViewById(R.id.INPUT1);
n2 = (EditText)findViewById(R.id.INPUT2);
}
public void add(View v) //add method for adding 2 numbers
{
int i = Integer.parseInt(n1.getText().toString());
int j = Integer.parseInt(n2.getText().toString());
int k= i+j;
}
}
當你在 onCreate 之前調用 findViewById 時,在 Activity 實例化時它會嘗試綁定你的視圖,因為 Activity 組件還不存在,你會得到一些錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.