我写了一个简单的登录程序,在Android Studio Emulator上测试它,它工作正常。 然后我尝试使用我的手机进行调试,并在按下发送按钮后立即崩溃。 这是代码:
public class MainActivity extends AppCompatActivity implements LoginFrag.PinManager {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LoginFrag fragment = new LoginFrag();
getFragmentManager()
.beginTransaction()
.add(R.id.main_frame_layout, fragment)
.commit();
}
@Override
public void checkPin(int i) {
int pin = i;
if (pin!=123){
Toast.makeText(this, "Wrong password", Toast.LENGTH_LONG).show();
}
else {
loadMenu();
}
}
public class LoginFrag extends Fragment {
private Button button;
private EditText editText;
PinManager pinActivity;
public interface PinManager{
public void checkPin(int i);
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
try {
pinActivity = (PinManager) context;
} catch (ClassCastException e){
throw new ClassCastException(context.toString());
}
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.login_frag, container, false);
button = (Button) view.findViewById(R.id.login_button);
editText = (EditText) view.findViewById(R.id.pin);
button.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
pinReader(v);
}
}
);
return view;
}
public void pinReader(View v){
pinActivity.checkPin(Integer.parseInt(editText.getText().toString()));
editText.setText("");
}
}
错误如下:
W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x41781e48)
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.max.passwordmanager, PID: 13259
java.lang.NullPointerException
at com.example.max.passwordmanager.LoginFrag.pinReader(LoginFrag.java:57)
at com.example.max.passwordmanager.LoginFrag$1.onClick(LoginFrag.java:47)
at android.view.View.performClick(View.java:4461)
at android.view.View$PerformClick.run(View.java:18523)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5118)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:606)
at dalvik.system.NativeStart.main(Native Method)
I/Process: Sending signal. PID: 13259 SIG: 9
Application terminated.
我在两个手机上运行了代码,一个用android 4.4.2,另一个用android 5.0.2,一旦你点击按钮发送引脚就会崩溃。