我有一些问题解决onClick函数上的空点异常 - 我会把代码放在这里,希望有人能发现我不能发现的东西。
主要课程:
package org.matthewdann.mathsapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//insert buttons to get different activities
//SUVAT
Button buttonSUVAT = (Button) findViewById(R.id.buttonSUVAT);
buttonSUVAT.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, suvatSolver.class));
}
});
//Temp Converter
Button tempConvertButton = (Button) findViewById(R.id.temp_convert_button);
tempConvertButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, TempConverter.class));
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
清单:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.matthewdann.mathsapp">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name="org.matthewdann.mathsapp.MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="org.matthewdann.mathsapp.suvatSolver"
android:label="@string/title_activity_suvat_solver"
android:theme="@style/AppTheme.NoActionBar" />
<activity
android:name="org.matthewdann.mathsapp.TempConverter"
android:label="@string/title_activity_temp_converter"
android:theme="@style/AppTheme.NoActionBar">
</activity>
</application>
</manifest>
logcat的:
03-10 21:32:27.061 11535-11535/org.matthewdann.mathsapp D/AndroidRuntime: Shutting down VM
03-10 21:32:27.062 11535-11535/org.matthewdann.mathsapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: org.matthewdann.mathsapp, PID: 11535
java.lang.RuntimeException: Unable to start activity ComponentInfo{org.matthewdann.mathsapp/org.matthewdann.mathsapp.TempConverter}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at org.matthewdann.mathsapp.TempConverter.onCreate(TempConverter.java:42)
at android.app.Activity.performCreate(Activity.java:6251)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
编辑:content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="org.matthewdann.mathsapp.MainActivity"
tools:showIn="@layout/activity_main">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="@string/app_name"
android:id="@+id/mainPageHeader"
android:layout_below="@+id/adView1"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/buttonSUVAT"
android:id="@+id/buttonSUVAT"
android:layout_below="@+id/mainPageHeader"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/temp_convert_button"
android:id="@+id/temp_convert_button"
android:layout_below="@+id/buttonSUVAT"
android:layout_alignRight="@+id/buttonSUVAT"
android:layout_alignEnd="@+id/buttonSUVAT"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
编辑2 - tempConverter:
package org.matthewdann.mathsapp;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.text.DecimalFormat;
public class TempConverter extends AppCompatActivity {
private EditText tempEditText;
private TextView showTempTextView;
DecimalFormat round = new DecimalFormat("0.0");
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//define Text and button variables
tempEditText = (EditText) findViewById(R.id.TempInput);
Button cButton = (Button) findViewById(R.id.buttonC);
Button fButton = (Button) findViewById(R.id.buttonF);
showTempTextView = (TextView) findViewById(R.id.Output);
//button event listeners
fButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//hide keyboard
InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow((null == getCurrentFocus()) ? null : getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
//error if empty
String editTextVal = tempEditText.getText().toString();
if (editTextVal.isEmpty()) {
Toast.makeText(getApplicationContext(), "Enter a value", Toast.LENGTH_LONG).show();
} else {
//something has been entered - parse into decimal
double doubleEditText = Double.parseDouble(editTextVal);
//convert
double convertedVal1 = convertToCelsius(doubleEditText);
double convertedVal2 = (273.15 + convertedVal1);
if (0 < convertedVal2) {
//parse into string for output
String stringResult = String.valueOf(round.format(convertedVal1) + " C ; " + round.format(convertedVal2) + " K ");
showTempTextView.setText(stringResult);
} else {
String stringResult = String.valueOf("Error!");
showTempTextView.setText(stringResult);
Toast.makeText(getApplicationContext(), "Value is too small!", Toast.LENGTH_LONG).show();
}
}
}
});
cButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//convert to f
InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow((null == getCurrentFocus()) ? null : getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
String editTextVal = tempEditText.getText().toString();
if (editTextVal.isEmpty()) {
Toast.makeText(getApplicationContext(), "Edit a value", Toast.LENGTH_LONG).show();
} else {
//something entered
double doubleEditText = Double.parseDouble(editTextVal);
double convertedVal = convertToF(doubleEditText);
double convertedVal2 = (273.15 + doubleEditText);
if (0 < convertedVal2) {
String stringResult = String.valueOf(round.format(convertedVal) + " F ; " + round.format(convertedVal2) + " K ");
showTempTextView.setText(stringResult);
} else {
Toast.makeText(getApplicationContext(), "Value is too small!", Toast.LENGTH_LONG).show();
String stringResult = String.valueOf("Error!");
showTempTextView.setText(stringResult);
}
}
}
});
}
public double convertToCelsius (double farVal) {
double resultCel;
resultCel = (farVal - 32) * 5/9;
return resultCel;
}
public double convertToF (double celVar) {
double resultF;
resultF = (celVar * 9/5) + 32;
return resultF;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
答案 0 :(得分:0)
首先检查是否
R.id.temp_convert_button
与
在同一XML中R.layout.activity_main.
你可能会发现findViewById()返回null。 试试
Button tempConvertButton = (Button) findViewById(R.id.temp_convert_button)
Log.i("test"," is null " +(null == tempConvertButton));
答案 1 :(得分:0)
问题不在于onClick方法,它是您注册监听器的地方!按钮对象为null,如果在尚未加载所需的XML文件时尝试使用findViewById()
,则最有可能发生这种情况。尝试将监听器注册移至onCreateView()
答案 2 :(得分:0)
我认为你正在调用错误的布局。
在您的代码中,您要求activity_main
布局,但您的布局文件似乎是content_main.xml
。
尝试将setContentView(R.layout.activity_main);
更改为setContentView(R.layout.content_main);
或者只需将content_main.xml
文件重命名为activity_main.xml
编辑:
在第二次编辑之后,您似乎正在为两个活动使用相同的布局。在某些情况下,您可能会提到错误的布局。
答案 3 :(得分:0)
所以我有一个setContentView(R.layout.activity_main);
的流氓实例
在应用程序中 - 修复似乎解决了这个问题!