我最近从初始屏幕加载登录活动时遇到错误。这会导致致命的崩溃。
这是代码:
if(response.contains("Success") && isStored == false){
Intent Login = new Intent(SplashScreen.this, LoginScreen.class);
Login.putExtra("EXTRA_PHONE_NUMBER", phoneNumber);
startActivity(Login);
// close this activity
finish();
}
我注意到,如果我用mainactivity.class切换出LoginScreen.class,它就可以正常工作。有人知道这里发生了什么吗?
这是LoginScreen的代码:
public class LoginScreen extends Activity {
EditText email;
EditText pass;
Button LoginButton;
ImageView image;
String phoneNumber;
String userPhone;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//These 2 lines hide the action bar
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
getActionBar().hide();
setContentView(R.layout.activity_login);
email = (EditText)findViewById(R.id.emailTxt);
pass = (EditText)findViewById(R.id.passwordTxt);
image = (ImageView)findViewById(R.id.ImageViewLogo);
userPhone = getPhoneNumber();
//Displays the logo in the ImageViewLogo
image.setImageResource(R.drawable.autotrak_logo);
final String EMAIL_PATTERN = "^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$";
LoginButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
final String userEmail = email.getText().toString();
final String userPass = pass.getText().toString();
if(userEmail.length() == 0)
{
email.requestFocus();
email.setError("No Email Entered");
}
else if(!userEmail.matches(EMAIL_PATTERN))
{
email.requestFocus();
email.setError("Invalid Email");
}
else if(userPass.length() == 0)
{
pass.requestFocus();
pass.setError("No Password Entered");
}else if(checkForUser(userEmail, userPass).contains("Bad")){
String toastText = "Incorrect email or password";
Toast.makeText(getApplicationContext(), toastText, Toast.LENGTH_SHORT).show();
pass.requestFocus();
}else
{
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
SharedPreferences.Editor editor = prefs.edit();
editor.putString("storedEmail", userEmail);
editor.putString("storedPass", userPass);
editor.putString("storedPhone", userPhone);
editor.apply();
Intent BluetoothDemo = new Intent(LoginScreen.this, BluetoothDemo.class);
startActivity(BluetoothDemo);
}
}
});
}
public String checkForUser(String email, String pass) {
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost("http://xxxx.xxxx.net/xxxx.php");
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("email", email));
nameValuePairs.add(new BasicNameValuePair("password", pass));
nameValuePairs.add(new BasicNameValuePair("phoneNumber", userPhone));
try {
request.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(20);
int current = 0;
while((current = bis.read()) != -1)
{
baf.append((byte)current);
}
String bytesSent = new String(baf.toByteArray());
// for receiving response from the server
return bytesSent;
} catch (Exception e) {
e.printStackTrace();
String stackTrace = Log.getStackTraceString(e);
String toastText = "Error sending data: " + stackTrace;
Toast.makeText(getApplicationContext(), toastText, Toast.LENGTH_SHORT).show();
return null;
}
} catch (Exception e) {
String toastText = "Error preparing data";
Toast.makeText(getApplicationContext(), toastText, Toast.LENGTH_SHORT).show();
return null;
}
}
return null;
}
public String getPhoneNumber(){
Bundle extras;
extras = getIntent().getExtras();
if(extras == null) {
phoneNumber = null;
} else {
phoneNumber = extras.getString("EXTRA_PHONE_NUMBER");
}
return phoneNumber;
}
}
这是堆栈跟踪:
11-23 13:08:00.626 1242-1242/my.obd2connector E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: my.obd2connector, PID: 1242
java.lang.RuntimeException: Unable to start activity ComponentInfo{my.obd2connector/my.obd2connector.LoginScreen}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2305)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
at android.app.ActivityThread.access$900(ActivityThread.java:161)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5356)
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:1265)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at my.obd2connector.LoginScreen.onCreate(LoginScreen.java:58)
at android.app.Activity.performCreate(Activity.java:5426)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2269)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
at android.app.ActivityThread.access$900(ActivityThread.java:161)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5356)
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:1265)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
at dalvik.system.NativeStart.main(Native Method)
最佳答案
造成原因:java.lang.NullPointerException
因为在LoginScreen
活动中您要在setOnClickListener
Button实例初始化之前调用LoginButton
的LoginButton
方法,所以请在setContentView
之后执行此操作:
LoginButton = (Button)findViewById(R.id.Login_Button_ID);