1

我正在尝试按照本教程创建登录界面:http ://www.youtube.com/watch?v=etYVqYAhp6w&feature=bf_prev&list=UUnzGVPkz3rZcrLh9jKbKNQw - 第 1 到 6 部分。

当我在 Android 模拟器上运行应用程序时,它返回 toast 消息“登录失败”(下面 Main.java 文件中声明的异常)。

main.java 文件连接到我保存在 wamp/www/index.php 目录中的 php 文件 index.php,然后它与存储在 wamp 服务器(在我的本地机器上)上的“mobiledb”进行通信。

已在数据库中创建了一个用户,我尝试通过模拟器登录,该模拟器应验证登录详细信息并给出 toast 消息“成功!”。

如果有人可以就可能出现的问题提供任何帮助,将不胜感激。谢谢。

主.java

package com.kibriaali.logintutorial;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
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.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Main extends Activity implements OnClickListener{
    EditText etUser, etPass;
    Button bLogin;

    //Create string variables that will have the input assigned to them
    String username, password;

    //Create a HTTPClient as the form container
    HttpClient httpclient;

    //Use HTTP POST method
    HttpPost httppost;

    //Create an array list for the input data to be sent
    ArrayList<NameValuePair> nameValuePairs;

    //Create a HTTP Response and HTTP Entity
    HttpResponse response;
    HttpEntity entity;



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        initialise();
    }

    private void initialise() {
        // TODO Auto-generated method stub
        etUser = (EditText) findViewById(R.id.etUser);
        etPass = (EditText) findViewById(R.id.etPass);
        bLogin = (Button) findViewById(R.id.bSubmit);
        //Now to set an onClickListener
        bLogin.setOnClickListener(this);
    }

    public void onClick(View v) {
        // This is where we will be working now

        //Create new default HTTPClient
        httpclient = new DefaultHttpClient();

        //Create new HTTP POST with URL to php file as parameter
        httppost = new HttpPost("http://127.0.0.1/wamp/www/index.php"); //92.4.131.132 //127.0.0.1 //10.0.2.2

        //Assign input text to strings
        username = etUser.getText().toString();
        password = etPass.getText().toString();



        //Next block of code needs to be surrounded by try/catch block for it to work
        try {
            //Create new Array List
            nameValuePairs = new ArrayList<NameValuePair>(2);

            //place them in an array list
            nameValuePairs.add(new BasicNameValuePair("user", "username"));
            nameValuePairs.add(new BasicNameValuePair("pass", "password"));

            //Add array list to http post
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            //assign executed form container to response
            response = httpclient.execute(httppost); //response from the PHP file

            //check status code, need to check status code 200
            if(response.getStatusLine().getStatusCode()== 200){

                //assign response entity to http entity
                entity = response.getEntity();

                //check if entity is not null
                if(entity != null){


                    //Create new input stream with received data assigned
                    InputStream instream = entity.getContent();

                    //Create new JSON Object. assign converted data as parameter.
                    JSONObject jsonResponse = new JSONObject(convertStreamToString(instream));

                    //assign json responses to local strings
                    String retUser = jsonResponse.getString("user");//mySQL table field
                    String retPass = jsonResponse.getString("pass");

                    //Validate login
                    if(username.equals(retUser)&& password.equals(retPass)){ //Check whether 'retUser' and 'retPass' matches username/password 

                        //Create a new shared preference by getting the preference
                        //Give the shared preference any name you like.
                        SharedPreferences sp = getSharedPreferences("logindetails", 0);

                        //Edit the Shared Preference
                        SharedPreferences.Editor spedit = sp.edit();

                        //Put the login details as strings
                        spedit.putString("user", username);
                        spedit.putString("pass", password);//May not need to store password

                        //Close the editor
                        spedit.commit();

                        //Display a Toast saying login was a success
                        Toast.makeText(getBaseContext(), "SUCCESS!", Toast.LENGTH_SHORT).show();


                    } else {
                        //Display a Toast saying it failed.

                        Toast.makeText(getBaseContext(), "Invalid Login Details", Toast.LENGTH_SHORT).show();
                    }

                }


            }


        } catch(Exception e){
            e.printStackTrace();
            //Display toast when there is a connection error
            //Change message to something more friendly
            Toast.makeText(getBaseContext(), "Login Unsuccessful.", Toast.LENGTH_SHORT).show();
        }






    }//END onClick()

    private static String convertStreamToString(InputStream is) {
        /*
         * To convert the InputStream to String we use the BufferedReader.readLine()
         * method. We iterate until the BufferedReader return null which means
         * there's no more data to read. Each line will appended to a StringBuilder
         * and returned as String.
         */
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }//END convertStreamToString()

}

索引.PHP 文件

<?php
//turn off error reporting
error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING);

//Create fields for the database
//server, username, password, database

$dbhost = "localhost"; //92.4.131.132 //127.0.0.1 //10.0.2.2
$dbuser = "root";
$dbpass = "";
$dbdb = "mobiledb";

//connect to mySQL
$connect = mysql_connect($dbhost, $dbuser, $dbpass) or die("connection error");

//Select the database
mysql_select_db($dbdb)or die("database selection error");

//Retrieve the login details via POST
$username = $_POST['username'];
$password = $_POST['password'];

//Query the table android login
$query = mysql_query("SELECT * FROM androidlogin WHERE user='$username' AND pass='$password'");

//check if there any results returned
$num = mysql_num_rows($query);

//If a record was found matching the details entered in the query
if($num == 1){
    //Create a while loop that places the returned data into an array
    while($list=mysql_fetch_assoc($query)){
        //Store the returned data into a variable
        $output = $list;

        //encode the returned data in JSON format
        echo json_encode($output);

    }
    //close the connection
    mysql_close();


}

?>

注意:已在 Android 清单文件中启用 Internet 权限。

4

0 回答 0