我正在创建一个登录页面并使用php验证用户名和密码,当我输入用户名和密码后点击登录按钮获取应用程序已意外停止并且NullPointerException,已附加我的代码请任何人告诉我我做了什么错误
谢谢。 mainactivity.java
package com.example.validation;
import java.io.InputStream;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
Button login;
String name="",pass="";
byte[] data;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
InputStream inputStream;
SharedPreferences app_preferences ;
CheckBox check;
private EditText username=null;
private EditText password=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
username = (EditText) findViewById(R.id.editText1);
password = (EditText) findViewById(R.id.editText2);
login = (Button) findViewById(R.id.button);
check = (CheckBox) findViewById(R.id.check);
String Str_user = app_preferences.getString("username","0" );
String Str_pass = app_preferences.getString("password", "0");
String Str_check = app_preferences.getString("checked", "no");
if(Str_check.equals("yes"))
{
username.setText(Str_user);
password.setText(Str_pass);
check.setChecked(true);
}
login.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
name = username.getText().toString();
pass = password.getText().toString();
String Str_check2 = app_preferences.getString("checked", "no");
if(Str_check2.equals("yes"))
{
SharedPreferences.Editor editor = app_preferences.edit();
editor.putString("username", name);
editor.putString("password", pass);
editor.commit();
}
if(name.equals("") || pass.equals(""))
{
Toast.makeText(MainActivity.this, "Blank Field..Please Enter", Toast.LENGTH_LONG).show();
}
else
{
try {
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://localhost/Purchase Order/userlogin.php");
// Add your data
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("UserEmail", name.trim()));
nameValuePairs.add(new BasicNameValuePair("Password", pass.trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
response = httpclient.execute(httppost);
inputStream = response.getEntity().getContent();
data = new byte[256];
buffer = new StringBuffer();
int len = 0;
while (-1 != (len = inputStream.read(data)) )
{
buffer.append(new String(data, 0, len));
}
inputStream.close();
}
catch (Exception e)
{
Toast.makeText(MainActivity.this, "error"+e.toString(), Toast.LENGTH_LONG).show();
}
if(buffer.charAt(0)=='Y')
{
Toast.makeText(MainActivity.this, "login successfull", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(MainActivity.this, "Invalid Username or password", Toast.LENGTH_LONG).show();
}
}
}
});
check.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
// Perform action on clicks, depending on whether it's now checked
SharedPreferences.Editor editor = app_preferences.edit();
if (((CheckBox) v).isChecked())
{
editor.putString("checked", "yes");
editor.commit();
}
else
{
editor.putString("checked", "no");
editor.commit();
}
}
});
}
public void sendMessage(View view)
{
Intent intent = new Intent(MainActivity.this, Mainpage.class);
startActivity(intent);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
activity_main.xml中
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/ic_launcher"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText2"
android:layout_centerHorizontal="true"
android:onClick="sendMessage"
android:layout_marginTop="32dp"
android:layout_toLeftOf="@+id/textview"
android:layout_toStartOf="@+id/textview"
android:text="login" />
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_below="@+id/imageView"
android:layout_marginTop="33dp"
android:ems="10"
android:focusable="true"
android:hint="Enter Name"
android:textColorHighlight="#ff7eff15"
android:textColorHint="#ffff25e6" />
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignEnd="@+id/editText"
android:layout_alignLeft="@+id/editText1"
android:layout_alignRight="@+id/editText"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_below="@+id/editText1"
android:layout_marginTop="29dp"
android:ems="10"
android:hint="Password"
android:inputType="textPassword"
android:textColorHint="#ffff299f" />
<CheckBox
android:id="@+id/check"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText2"
android:layout_below="@+id/button"
android:text="Remember me" />
</RelativeLayout>
userlogin.php
<?php
require_once('Purchase Order/dao/connectDB');
mysql_select_db($database_localhost,$localhost);
$username = $_POST['UserEmail'];
$password = $_POST['Password'];
$query_search = "select * from user_login where username = '".$username."' AND password = '".$password. "'";
$query_exec = mysql_query($query_search) or die(mysql_error());
$rows = mysql_num_rows($query_exec);
if($rows --> 0) {
echo "Y";
}
else {
echo "N";
}
?>
logcat的:
06-03 17:56:38.044: D/AndroidRuntime(416): Shutting down VM
06-03 17:56:38.044: W/dalvikvm(416): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
06-03 17:56:38.063: E/AndroidRuntime(416): FATAL EXCEPTION: main
06-03 17:56:38.063: E/AndroidRuntime(416): java.lang.NullPointerException
06-03 17:56:38.063: E/AndroidRuntime(416): at com.example.validation.MainActivity$1.onClick(MainActivity.java:110)
06-03 17:56:38.063: E/AndroidRuntime(416): at android.view.View.performClick(View.java:2408)
06-03 17:56:38.063: E/AndroidRuntime(416): at android.view.View$PerformClick.run(View.java:8816)
06-03 17:56:38.063: E/AndroidRuntime(416): at android.os.Handler.handleCallback(Handler.java:587)
06-03 17:56:38.063: E/AndroidRuntime(416): at android.os.Handler.dispatchMessage(Handler.java:92)
06-03 17:56:38.063: E/AndroidRuntime(416): at android.os.Looper.loop(Looper.java:123)
06-03 17:56:38.063: E/AndroidRuntime(416): at android.app.ActivityThread.main(ActivityThread.java:4627)
06-03 17:56:38.063: E/AndroidRuntime(416): at java.lang.reflect.Method.invokeNative(Native Method)
06-03 17:56:38.063: E/AndroidRuntime(416): at java.lang.reflect.Method.invoke(Method.java:521)
06-03 17:56:38.063: E/AndroidRuntime(416): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
06-03 17:56:38.063: E/AndroidRuntime(416): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
06-03 17:56:38.063: E/AndroidRuntime(416): at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:0)
假设以下行位于文件的第110行。 (但是,在发布源代码之后行已经转移了,我认为)
if(buffer.charAt(0)=='Y')
NullPointerException
表示达到此点时缓冲区仍为null
。
要快速修复此错误,请将其更改为:
if((buffer != null) && buffer.charAt(0)=='Y')