php登录时的NullPointerException android

时间:2013-04-28 21:48:25

标签: android nullpointerexception

我试图让我的Android应用程序与php网站一起工作。 我有数据库存储有关用户的信息,如用户ID,密码等。 但是当我从mainactivity应用程序中单击登录按钮时停止。

我的login.java如下

    public class Login extends Activity {

    Button home,login;
    EditText uname,pword;
    Context context;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        getActionBar().setDisplayHomeAsUpEnabled(true);
        addListenerOnHome();
        addListenerOnBtnlogin();   //this is line 42

        uname = (EditText) findViewById(R.id.txtuserid);
        pword = (EditText) findViewById(R.id.txtuserpass);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_login, menu);
        return true;
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                NavUtils.navigateUpFromSameTask(this);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void addListenerOnHome() {
        final Context context = this;
        home = (Button)findViewById(R.id.btnhome);
        home.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context,MainActivity.class);
                startActivity(intent);   
            }
        });
    }

    public void addListenerOnBtnlogin() {
        context = this;
        final String username = uname.getText().toString();   //this is line 79        
        final String password = pword.getText().toString();

        login = (Button)findViewById(R.id.btnlogin);
        login.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Thread t = new Thread() {
                    public void run() {
                        postLoginData(username,password);
                    }
                };
                t.start();
            }
        });
    }

    private void postLoginData(String username,String password) {

        try {
            // Create a new HttpClient and Post Header
            HttpClient httpclient = new DefaultHttpClient();
            Log.e("Response-->", "after httpclient");

            HttpPost httppost = new HttpPost("http://10.0.2.2/dealnow/login.php");
            Log.e("Response-->", "after httppost");


            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("username", username));
            nameValuePairs.add(new BasicNameValuePair("password", password));

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            Log.e("Responce-->", "after using the list name pair");

            // Execute HTTP Post Request
            Log.w("SENCIDE", "Execute HTTP Post Request");
            HttpResponse response = httpclient.execute(httppost);
            Log.e("Responce-->", "after execute the http response");
            String str = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);

            if (str.toString().equalsIgnoreCase("true")) {

                runOnUiThread(new Runnable() {
                    public void run() {
                        Intent intent = new Intent(context,MainActivity.class);
                        startActivity(intent);

                    }
                });


            } else {
                runOnUiThread(new Runnable() {
                    public void run() {
                        //notlogged in

                    }
                });
            }

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

和login.php是

<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="user"; // Database name
$tbl_name="user_det"; // Table name

// Connect to server and select databse.
mysql_connect("$host","$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

// username and password sent from form
$myusername=$_POST['username'];
$mypassword=$_POST['password'];

// To protect MySQL injection
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);

$sql="SELECT * FROM $tbl_name WHERE user_id='$myusername' and 
app_pass='$mypassword'";

$result=mysql_query($sql);

// Mysql_num_row is counting table row
$count=mysql_num_rows($result);

// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){
echo "true";
}
else {
echo "Login Failed";
}
?>

和logcat显示

04-29 03:16:11.355: D/dalvikvm(454): GC_FOR_ALLOC freed 30K, 3% free 7683K/7879K, paused 56ms
04-29 03:16:11.365: I/dalvikvm-heap(454): Grow heap (frag case) to 8.065MB for 495616-byte allocation
04-29 03:16:11.546: D/dalvikvm(454): GC_FOR_ALLOC freed <1K, 3% free 8166K/8391K, paused 83ms
04-29 03:16:11.765: D/dalvikvm(454): GC_CONCURRENT freed 1K, 3% free 8173K/8391K, paused 5ms+14ms
04-29 03:16:11.805: D/AndroidRuntime(454): Shutting down VM
04-29 03:16:11.805: W/dalvikvm(454): threadid=1: thread exiting with uncaught exception (group=0x40014760)
04-29 03:16:11.825: E/AndroidRuntime(454): FATAL EXCEPTION: main
04-29 03:16:11.825: E/AndroidRuntime(454): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.test/com.example.test.Login}: java.lang.NullPointerException
04-29 03:16:11.825: E/AndroidRuntime(454):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1736)
04-29 03:16:11.825: E/AndroidRuntime(454):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1752)
04-29 03:16:11.825: E/AndroidRuntime(454):  at android.app.ActivityThread.access$1500(ActivityThread.java:123)
04-29 03:16:11.825: E/AndroidRuntime(454):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:993)
04-29 03:16:11.825: E/AndroidRuntime(454):  at android.os.Handler.dispatchMessage(Handler.java:99)
04-29 03:16:11.825: E/AndroidRuntime(454):  at android.os.Looper.loop(Looper.java:126)
04-29 03:16:11.825: E/AndroidRuntime(454):  at android.app.ActivityThread.main(ActivityThread.java:3997)
04-29 03:16:11.825: E/AndroidRuntime(454):  at java.lang.reflect.Method.invokeNative(Native Method)
04-29 03:16:11.825: E/AndroidRuntime(454):  at java.lang.reflect.Method.invoke(Method.java:491)
04-29 03:16:11.825: E/AndroidRuntime(454):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
04-29 03:16:11.825: E/AndroidRuntime(454):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
04-29 03:16:11.825: E/AndroidRuntime(454):  at dalvik.system.NativeStart.main(Native Method)
04-29 03:16:11.825: E/AndroidRuntime(454): Caused by: java.lang.NullPointerException
04-29 03:16:11.825: E/AndroidRuntime(454):  at com.example.test.Login.addListenerOnBtnlogin(Login.java:79)
04-29 03:16:11.825: E/AndroidRuntime(454):  at com.example.test.Login.onCreate(Login.java:42)
04-29 03:16:11.825: E/AndroidRuntime(454):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1048)
04-29 03:16:11.825: E/AndroidRuntime(454):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1700)
04-29 03:16:11.825: E/AndroidRuntime(454):  ... 11 more
04-29 03:16:14.684: I/Process(454): Sending signal. PID: 454 SIG: 9

1 个答案:

答案 0 :(得分:2)

我可能错了,但我认为它正在发生,因为您试图在btnLogin listener 中获取EditTexts 的值,然后才能正确引用它们来自您的XML布局文件。

首先使用 findViewById(..) 正确定义引用,然后调用侦听器。

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        getActionBar().setDisplayHomeAsUpEnabled(true);
        uname = (EditText) findViewById(R.id.txtuserid);
        pword = (EditText) findViewById(R.id.txtuserpass);

        addListenerOnHome();
        addListenerOnBtnlogin();  
    }