duanbing8817 2015-03-09 21:01
浏览 89

无法重定向到MainActivity屏幕

I am just a newbie and I have build up my application to start with a layout named user_login.xml. When I click on the login button, however it is unable to redirect me to the activity_main.xml. The json should works fine. What should I do in order to solve this? Sorry if I used wrong words to explain my problem. Thanks in advance. Here is the Android Manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.alan.smarthome"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="9"
        android:targetSdkVersion="21" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 

    <application
        android:name="com.alan.smarthome.app.AppController"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/Theme.AppCompat" >
        <activity
            android:name="com.alan.smarthome.UserLogin"
            android:launchMode="singleTop"
            android:windowSoftInputMode="adjustPan" 
            android:label="@string/app_name">

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".RegisterActivity"
                  android:label="Register New Account"
                  android:launchMode="singleTop"
                  android:windowSoftInputMode="adjustPan"/>
        <activity android:name=".MainActivity"
                  android:label="@string/app_name" 
                  android:launchMode="singleTop"/>

    </application>

</manifest>

And this is the UserLogin.java that I have created

package com.alan.smarthome;


import com.alan.smarthome.app.AppConfig;
import com.alan.smarthome.app.AppController;
import com.alan.smarthome.helper.SessionManager;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;  
import android.app.ProgressDialog;
import android.util.Log;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.content.Intent;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;


public class UserLogin extends Activity {

        // LogCat tag
        private static final String TAG = RegisterActivity.class.getSimpleName();
        private Button btnLogin;
        private TextView btnLinkToRegister;
        private EditText inputUsername;
        private EditText inputPassword;
        private ProgressDialog pDialog;
        private SessionManager session;
        /*
        private TextView attempts;
        int counter = 3; */ 

        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.user_login);


                inputUsername = (EditText) findViewById(R.id.btnUsername);
                inputPassword = (EditText) findViewById(R.id.btnPassword);
                btnLogin = (Button) findViewById(R.id.btnLogin);
                btnLinkToRegister = (TextView) findViewById(R.id.btnLinkToRegisterScreen);

                // Progress dialog
                pDialog = new ProgressDialog(this);
                pDialog.setCancelable(false);

                // Session manager
                session = new SessionManager(getApplicationContext());

                // Check if user is already logged in or not
                if (session.isLoggedIn()) {
                    // User is already logged in. Take him to main activity
                    Intent intent = new Intent(UserLogin.this, MainActivity.class);
                    startActivity(intent);
                    finish();
                }


          // Login button Click Event
          btnLogin.setOnClickListener(new View.OnClickListener() {
                public void onClick(View view) {
                        String name = inputUsername.getText().toString();
                        String password = inputPassword.getText().toString();

                        // Check for empty data in the form
                        if (name.trim().length() > 0 && password.trim().length() > 0) {
                            // login user
                            checkLogin(name, password);
                        } else {
                            // Prompt user to enter credentials
                            Toast.makeText(getApplicationContext(),
                                    "Please enter the credentials!", Toast.LENGTH_LONG)
                                    .show();
                        }
                }
          });

          // Link to Register Screen
          btnLinkToRegister.setOnClickListener(new View.OnClickListener() {

                public void onClick(View view) {
                    Intent i = new Intent(getApplicationContext(),
                            RegisterActivity.class);
                    startActivity(i);
                    finish();
                }
            });

        }


        /**
         * function to verify login details in mysql db
         * */
        private void checkLogin(final String name, final String password) {
            // Tag used to cancel the request
            String tag_string_req = "req_login";

            pDialog.setMessage("Logging in ...");
            showDialog();

            StringRequest strReq = new StringRequest(Method.POST,
                    AppConfig.URL_REGISTER, new Response.Listener<String>() {

                        @Override
                        public void onResponse(String response) {
                            Log.d(TAG, "Login Response: " + response.toString());
                            hideDialog();

                            try {
                                JSONObject jObj = new JSONObject(response.substring(response.indexOf("{"), response.lastIndexOf("}") + 1));
                                boolean error = jObj.getBoolean("error");

                                // Check for error node in json
                                if (!error) {
                                    // user successfully logged in
                                    // Create login session
                                    session.setLogin(true);

                                    // Launch main activity                     
                                    Intent intent = new Intent(UserLogin.this,
                                                    MainActivity.class);
                                    startActivity(intent);
                                    finish();
                                } else {
                                    // Error in login. Get the error message
                                    String errorMsg = jObj.getString("error_msg");
                                    Toast.makeText(getApplicationContext(),errorMsg, Toast.LENGTH_LONG).show();


                                }
                            } catch (JSONException e) {
                                // JSON error
                                e.printStackTrace();
                            }

                        }
                    }, new Response.ErrorListener() {

                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Log.e(TAG, "Login Error: " + error.getMessage());
                            Toast.makeText(getApplicationContext(),
                                    error.getMessage(), Toast.LENGTH_LONG).show();
                            hideDialog();
                        }
                    }) {

                        @Override
                        protected Map<String, String> getParams() {
                            // Posting parameters to login url
                            Map<String, String> params = new HashMap<String, String>();
                            params.put("tag", "login");
                            params.put("name", name);
                            params.put("password", password);

                            return params;
                        }

                    };

            // Adding request to request queue
            AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
        }

        private void showDialog() {
            if (!pDialog.isShowing())
                pDialog.show();
        }

        private void hideDialog() {
            if (pDialog.isShowing())
                pDialog.dismiss();
        }

    }

And this is the error I get from LogCat when I try to login to the activity_main.xml

03-09 16:53:13.975: W/System.err(783): org.json.JSONException: Expected ':' after main at character 6 of {main}(  )</td><td title='C:\wamp\www\android_login_api\index.php' bgcolor='#eeeeec'>..\index.php<b>:</b>0</td></tr>
03-09 16:53:13.975: W/System.err(783): <tr><td bgcolor='#eeeeec' align='center'>2</td><td bgcolor='#eeeeec' align='center'>0.0010</td><td bgcolor='#eeeeec' align='right'>279456</td><td bgcolor='#eeeeec'>DB_Functions->__construct(  )</td><td title='C:\wamp\www\android_login_api\index.php' bgcolor='#eeeeec'>..\index.php<b>:</b>19</td></tr>
03-09 16:53:13.975: W/System.err(783): <tr><td bgcolor='#eeeeec' align='center'>3</td><td bgcolor='#eeeeec' align='center'>0.0020</td><td bgcolor='#eeeeec' align='right'>285592</td><td bgcolor='#eeeeec'>DB_Connect->connect(  )</td><td title='C:\wamp\www\android_login_api\include\DB_Functions.php' bgcolor='#eeeeec'>..\DB_Functions.php<b>:</b>13</td></tr>
03-09 16:53:13.985: W/System.err(783): <tr><td bgcolor='#eeeeec' align='center'>4</td><td bgcolor='#eeeeec' align='center'>0.0020</td><td bgcolor='#eeeeec' align='right'>286432</td><td bgcolor='#eeeeec'><a href='http://www.php.net/function.mysql-connect' target='_new'>mysql_connect</a>
03-09 16:53:13.985: W/System.err(783): (  )</td><td title='C:\wamp\www\android_login_api\include\DB_Connect.php' bgcolor='#eeeeec'>..\DB_Connect.php<b>:</b>18</td></tr>
03-09 16:53:13.985: W/System.err(783): </table></font>
03-09 16:53:13.985: W/System.err(783): {"tag":"login","error":false,"uid":"54fdd87267a3f5.49630793","user":{"name":"Alan","email":"alan@hotmail.com","created_at":"2015-03-10 01:29:22","updated_at":null}}
03-09 16:53:13.985: W/System.err(783):  at org.json.JSONTokener.syntaxError(JSONTokener.java:450)
03-09 16:53:13.985: W/System.err(783):  at org.json.JSONTokener.readObject(JSONTokener.java:379)
03-09 16:53:13.985: W/System.err(783):  at org.json.JSONTokener.nextValue(JSONTokener.java:100)
03-09 16:53:13.995: W/System.err(783):  at org.json.JSONObject.<init>(JSONObject.java:155)
03-09 16:53:13.995: W/System.err(783):  at org.json.JSONObject.<init>(JSONObject.java:172)
03-09 16:53:13.995: W/System.err(783):  at com.alan.smarthome.UserLogin$3.onResponse(UserLogin.java:129)
03-09 16:53:13.995: W/System.err(783):  at com.alan.smarthome.UserLogin$3.onResponse(UserLogin.java:1)
03-09 16:53:13.995: W/System.err(783):  at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
03-09 16:53:13.995: W/System.err(783):  at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
03-09 16:53:13.995: W/System.err(783):  at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
03-09 16:53:13.995: W/System.err(783):  at android.os.Handler.handleCallback(Handler.java:733)
03-09 16:53:13.995: W/System.err(783):  at android.os.Handler.dispatchMessage(Handler.java:95)
03-09 16:53:13.995: W/System.err(783):  at android.os.Looper.loop(Looper.java:136)
03-09 16:53:13.995: W/System.err(783):  at android.app.ActivityThread.main(ActivityThread.java:5017)
03-09 16:53:13.995: W/System.err(783):  at java.lang.reflect.Method.invokeNative(Native Method)
03-09 16:53:13.995: W/System.err(783):  at java.lang.reflect.Method.invoke(Method.java:515)
03-09 16:53:13.995: W/System.err(783):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-09 16:53:13.995: W/System.err(783):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
03-09 16:53:13.995: W/System.err(783):  at dalvik.system.NativeStart.main(Native Method)

And the php files:

DB_Connect.php

<?php
class DB_Connect {

    // constructor
    function __construct() {

    }

    // destructor
    function __destruct() {
        // $this->close();
    }

    // Connecting to database
    public function connect() {
        require_once 'include/config.php';
        // connecting to mysql
        $con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
        // selecting database
        mysql_select_db(DB_DATABASE);

        // return database handler
        return $con;
    }

    // Closing database connection
    public function close() {
        mysql_close();
    }

}

?>

config.php

<?php

    /**
     * Database config variables
     */
    define("DB_HOST", "localhost");
    define("DB_USER", "root");
    define("DB_PASSWORD", "");
    define("DB_DATABASE", "android_api");
    ?>

DB_Functions.php

<?php

class DB_Functions {

    private $db;

    //put your code here
    // constructor
    function __construct() {
        require_once 'DB_Connect.php';
        // connecting to database
        $this->db = new DB_Connect();
        $this->db->connect();
    }

    // destructor
    function __destruct() {

    }

    /**
     * Storing new user
     * returns user details
     */
    public function storeUser($name, $email, $password) {
        $uuid = uniqid('', true);
        $hash = $this->hashSSHA($password);
        $encrypted_password = $hash["encrypted"]; // encrypted password
        $salt = $hash["salt"]; // salt
        $result = mysql_query("INSERT INTO users(unique_id, name, email, encrypted_password, salt, created_at) VALUES('$uuid', '$name', '$email', '$encrypted_password', '$salt', NOW())");
        // check for successful store
        if ($result) {
            // get user details 
            $uid = mysql_insert_id(); // last inserted id
            $result = mysql_query("SELECT * FROM users WHERE uid = $uid");
            // return user details
            return mysql_fetch_array($result);
        } else {
            return false;
        }
    }

    /**
     * Get user by name and password
     */
    public function getUserByNameAndPassword($name, $password) {
        $result = mysql_query("SELECT * FROM users WHERE name = '$name'") or die(mysql_error());
        // check for result 
        $no_of_rows = mysql_num_rows($result);
        if ($no_of_rows > 0) {
            $result = mysql_fetch_array($result);
            $salt = $result['salt'];
            $encrypted_password = $result['encrypted_password'];
            $hash = $this->checkhashSSHA($salt, $password);
            // check for password equality
            if ($encrypted_password == $hash) {
                // user authentication details are correct
                return $result;
            }
        } else {
            // user not found
            return false;
        }
    }

    /**
     * Check user is existed or not
     */
    public function isUserExisted($name) {
        $result = mysql_query("SELECT name from users WHERE name = '$name'");
        $no_of_rows = mysql_num_rows($result);
        if ($no_of_rows > 0) {
            // user existed 
            return true;
        } else {
            // user not existed
            return false;
        }
    }

    /**
     * Encrypting password
     * @param password
     * returns salt and encrypted password
     */
    public function hashSSHA($password) {

        $salt = sha1(rand());
        $salt = substr($salt, 0, 10);
        $encrypted = base64_encode(sha1($password . $salt, true) . $salt);
        $hash = array("salt" => $salt, "encrypted" => $encrypted);
        return $hash;
    }

    /**
     * Decrypting password
     * @param salt, password
     * returns hash string
     */
    public function checkhashSSHA($salt, $password) {

        $hash = base64_encode(sha1($password . $salt, true) . $salt);

        return $hash;
    }

}

?>

Index.php

<?php

/**
 * File to handle all API requests
 * Accepts GET and POST
 * Each request will be identified by TAG
 * Response will be JSON data

  /**
 * check for POST request 
 */
if (isset($_POST['tag']) && $_POST['tag'] != '') {
    // get tag
    $tag = $_POST['tag'];

    // include db handler
    require_once 'include/DB_Functions.php';
    $db = new DB_Functions();

    // response Array
    $response = array("tag" => $tag, "error" => FALSE);

    // check for tag type
    if ($tag == 'login') {
        // Request type is check Login
        $name = $_POST['name'];
        $password = $_POST['password'];

        // check for user
        $user = $db->getUserByNameAndPassword($name, $password);
        if ($user != false) {
            // user found
            $response["error"] = FALSE;
            $response["uid"] = $user["unique_id"];
            $response["user"]["name"] = $user["name"];
            $response["user"]["email"] = $user["email"];
            $response["user"]["created_at"] = $user["created_at"];
            $response["user"]["updated_at"] = $user["updated_at"];
            echo json_encode($response);
        } else {
            // user not found
            // echo json with error = 1
            $response["error"] = TRUE;
            $response["error_msg"] = "Incorrect name or password!";
            echo json_encode($response);
        }
    } else if ($tag == 'register') {
        // Request type is Register new user
        $name = $_POST['name'];
        $email = $_POST['email'];
        $password = $_POST['password'];

        // check if user is already existed
        if ($db->isUserExisted($email)) {
            // user is already existed - error response
            $response["error"] = TRUE;
            $response["error_msg"] = "User already existed";
            echo json_encode($response);
        } else {
            // store user
            $user = $db->storeUser($name, $email, $password);
            if ($user) {
                // user stored successfully
                $response["error"] = FALSE;
                $response["uid"] = $user["unique_id"];
                $response["user"]["name"] = $user["name"];
                $response["user"]["email"] = $user["email"];
                $response["user"]["created_at"] = $user["created_at"];
                $response["user"]["updated_at"] = $user["updated_at"];
                echo json_encode($response);
            } else {
                // user failed to store
                $response["error"] = TRUE;
                $response["error_msg"] = "Error occured in Registration";
                echo json_encode($response);
            }
        }
    } else {
        // user failed to store
        $response["error"] = TRUE;
        $response["error_msg"] = "Unknow 'tag' value. It should be either 'login' or 'register'";
        echo json_encode($response);
    }
} else {
    $response["error"] = TRUE;
    $response["error_msg"] = "Required parameter 'tag' is missing!";
    echo json_encode($response);
}
?>
  • 写回答

4条回答

  • dongmou5628 2015-03-10 02:47
    关注

    org.json.JSONException: Expected ':'after main at character 6 of...

    Clearly you are not receiving a valid JSON response (it looks like HTML).

    This part:

    03-09 16:53:13.985: W/System.err(783): 40.0020286432http://www.php.net/function.mysql-connect' target='_new'>mysql_connect 03-09 16:53:13.985: W/System.err(783): ( )..\DB_Connect.php:18

    Suggest that you need to fix errors in your PHP script, also you should log the error, and if you need to send it in json format

    评论

报告相同问题?

悬赏问题

  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败