为什么Android中的TAG没有收到我的PHP脚本?

时间:2013-12-13 07:06:13

标签: php android json

这是我的Login.java

public class Login extends ActionBarActivity implements OnClickListener {

    private Button login, register;
    private EditText email, password;

    private JSONArray loginposition = null;
    // Progress Dialog
    private ProgressDialog pDialog;

    // JSON parser class
    JSONParser jsonParser = new JSONParser();

    private static final String LOGIN_URL = "http://192.168.1.10:1234/PMSS/login.php";
    // JSON element ids from repsonse of php script:
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_MESSAGE = "message";
    private static final String TAG_POSTS = "posts";
    private static final String TAG_POSITION = "position";

    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        login = (Button) findViewById(R.id.login);
        register = (Button) findViewById(R.id.registerlauncher);
        email = (EditText) findViewById(R.id.userid);
        password = (EditText) findViewById(R.id.password);

        login.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                String Username = email.getText().toString();
                String Password = password.getText().toString();
                new AttemptLogin(Username, Password).execute();
            }
        });

        register.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(Login.this, Register.class);
                startActivity(intent);

            }
        });
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            // For the main activity, make sure the app icon in the action bar
            // does not behave as a button
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.login, menu);
        return true;
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        /*
         * case R.id.login: new AttemptLogin().execute(); break; case
         * R.id.register: Intent i = new Intent(Login.this, Register.class);
         * startActivity(i); break;
         */
        default:
            break;
        }
    }

    class AttemptLogin extends AsyncTask<String, String, Integer> {

        private final String TAG = null;
        boolean failure = false;
        String res;
        String Username;
        String Password;
        String Position;
        int success;

        public AttemptLogin(String Username, String Password) {
            this.Username = Username;
            this.Password = Password;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(Login.this);
            pDialog.setMessage("Attempting login...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();

        }

        protected Integer doInBackground(String... args) {

            try {
                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("username", Username));
                params.add(new BasicNameValuePair("password", Password));

                Log.d("request!", "starting");
                // getting product details by making HTTP request
                JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST",
                        params);
                // check your log for json response
                Log.d("Login attempt", json.toString());                

                 //json success tag
                success = json.getInt(TAG_SUCCESS);
                res = json.getString(TAG_MESSAGE);
                loginposition = json.getJSONArray(TAG_POSTS);

                //            // looping through all posts according to the json object
                //            // returned
                            for (int i = 0; i < loginposition.length(); i++) {
                                JSONObject c = loginposition.getJSONObject(i);
                                // gets the content of each tag
                                // String content = c.getString(TAG_USERID);
                                Position = c.getString(TAG_POSITION);
                            }
            } catch (JSONException e) {
                Log.e(TAG, "JSON error", e);
                success = Integer.valueOf(0);
            }
            return success;

        }

        protected void onPostExecute(Integer success) {
            // dismiss the dialog once product deleted
            pDialog.dismiss();

            if (success != null && success == 1) {
                Log.d("Login Successful!", "res: " + res);
                // save user data
                SharedPreferences sp = PreferenceManager
                        .getDefaultSharedPreferences(Login.this);
                Editor edit = sp.edit();
                edit.putString("email", Username);
                edit.commit();                  

                if(Position != "user"){
                    Intent user = new Intent(Login.this, MainMenu.class);
                    startActivity(user);
                }
                else if(Position != "staff"){
                    Intent staff = new Intent(Login.this, StaffMainMenu.class);
                    startActivity(staff);
                }
                Toast.makeText(
                        Login.this,
                        res == null ? "Please enter both user id and password  (success)"
                                : res, Toast.LENGTH_LONG).show();
                email.setText(null);
                password.setText(null);
            } else {
                Log.d("Login Failure!", "res: " + res);
                Toast.makeText(
                        Login.this,
                        res == null ? "Please enter both user id and password  (failed)"
                                : res, Toast.LENGTH_LONG).show();
            }

        }
    }
}

这是我的Login.php

<?php

//load and connect to MySQL database stuff
require("config.inc.php");

if (!empty($_POST)) {

    if(empty($_POST['username']) || empty($_POST['password'])) {

        $response["success"] = 0;
        $response["message"] = "Please fill in the login details!";
        die(json_encode($response));
    }

    $query = "SELECT  email, password, position FROM user   WHERE   email = :email ";

    $query_params = array(':email' => $_POST['username'],);

    try {
        $stmt   = $db->prepare($query);
        $result = $stmt->execute($query_params);
    }
    catch (PDOException $ex) {
    // For testing, you could use a die and message. 
    //die("Failed to run query: " . $ex->getMessage());

    //or just use this use this one to product JSON data:
        $response["success"] = 0;
        $response["message"] = "Database Error1. Please Try Again!";
        die(json_encode($response));

    }

    //This will be the variable to determine whether or not the user's information is correct.
    //we initialize it as false.
    $validated_info = false;
    $login_ok = false;

    //fetching all the rows from the query
    $row = $stmt->fetch();
    if ($row) {
        //if we encrypted the password, we would unencrypt it here, but in our case we just
        //compare the two passwords
        if ($_POST['password'] === $row['password']) {
            $login_ok = true;       
        }

    // If the user logged in successfully, then we send them to the private members-only page 
    // Otherwise, we display a login failed message and show the login form again 
        if ($login_ok) {
            $response["success"] = 1;
            $response["message"] = "Login Successful!";
            $response["posts"]   = array();

                $post = array();
                do {

                    $post = $row["position"];
                    array_push($response["posts"], $post);

                } while ($row = $stmt->fetch()); 

            die(json_encode($response));
        } 
        else {
            $response["success"] = 0;
            $response["message"] = "Invalid Credentials!";
            die(json_encode($response));
        }

    } 
}   
else {
    ?>
    <h1>Login</h1> 
    <form action="login.php" method="post"> 
        Username:<br /> 
        <input type="text" name="username" placeholder="username" /> 
        <br /><br /> 
        Password:<br /> 
        <input type="password" name="password" placeholder="password" value="" /> 
        <br /><br /> 
        <input type="submit" value="Login" /> 
    </form> 
    <a href="register.php">Register</a>
    <?php
}
?>

我在浏览器上测试我的php脚本,它确实回显了我的标签posts":["staff"],这意味着php没有问题。现在主要的问题是为什么我的android应用程序没有从我的Login.php接收TAG_POSTS ..我已经测试了几次我的代码稍微更改但最终我的TAG_Position是空的,它不能满足if语句< / p>

    if(Position == "user"){
        Intent user = new Intent(Login.this, MainMenu.class);
        startActivity(user);
    }
    else if(Position == "staff"){
        Intent staff = new Intent(Login.this, StaffMainMenu.class);
        startActivity(staff);
    }

我的代码既没有编译错误也没有运行时错误

点击登录按钮后,这是我的logcat

12-13 15:25:22.009: D/request!(26763): starting
12-13 15:25:22.309: D/Login attempt(26763): {"posts":["user"],"message":"Login Successful!","success":1}
12-13 15:25:22.309: E/(26763): JSON error
12-13 15:25:22.309: E/(26763): org.json.JSONException: Value user at 0 of type java.lang.String cannot be converted to JSONObject
12-13 15:25:22.309: E/(26763):  at org.json.JSON.typeMismatch(JSON.java:96)
12-13 15:25:22.309: E/(26763):  at org.json.JSONArray.getJSONObject(JSONArray.java:484)
12-13 15:25:22.309: E/(26763):  at com.pmss.Login$AttemptLogin.doInBackground(Login.java:157)
12-13 15:25:22.309: E/(26763):  at com.pmss.Login$AttemptLogin.doInBackground(Login.java:1)
12-13 15:25:22.309: E/(26763):  at android.os.AsyncTask$2.call(AsyncTask.java:185)
12-13 15:25:22.309: E/(26763):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
12-13 15:25:22.309: E/(26763):  at java.util.concurrent.FutureTask.run(FutureTask.java:138)
12-13 15:25:22.309: E/(26763):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
12-13 15:25:22.309: E/(26763):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
12-13 15:25:22.309: E/(26763):  at java.lang.Thread.run(Thread.java:1019)
12-13 15:25:22.319: D/Login Failure!(26763): res: Login Successful!

0 个答案:

没有答案