<?php
class DB_Functions {
include 'config.php'
private $db;
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD,DB_DATABASE);
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 = mysqli_query($con,"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 = mysqli_insert_id(); // last inserted id
$result = mysqli_query($con,"SELECT * FROM users WHERE uid = $uid");
// return user details
return mysqli_fetch_array($result);
} else {
return false;
}
}
/**
* Get user by email and password
*/
public function getUserByEmailAndPassword($email, $password) {
$result = mysqli_query($con,"SELECT * FROM users WHERE email = '$email'") or die(mysqli_error());
// check for result
$no_of_rows = mysqli_num_rows($result);
if ($no_of_rows > 0) {
$result = mysqli_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 if user exist or not
*/
public function isUserExist($email) {
$result = mysqli_query($con,"SELECT email from users WHERE email = '$email'");
$no_of_rows = mysqli_num_rows($result);
if ($no_of_rows > 0) {
// user exist
return true;
} else {
// user does not exist
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;
}
}
?>
MainActivity代码:
public class MainActivity extends Activity {
ProgressDialog pDialog;
Button btnLogin;
Button btnLinkToRegister;
public EditText inputEmail;
public EditText inputPassword;
TextView loginErrorMsg;
String email;
String password;
// JSON Response node names
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "uid";
private static String KEY_NAME = "name";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Importing all assets like buttons, text fields
inputEmail = (EditText) findViewById(R.id.loginEmail);
inputPassword = (EditText) findViewById(R.id.loginPassword);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
loginErrorMsg = (TextView) findViewById(R.id.login_error);
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
email = inputEmail.getText().toString();
password = inputPassword.getText().toString();
new GoOnline().execute();
}
});
// Link to Register Screen
btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
finish();
}
});
}
class GoOnline extends AsyncTask<String, String, String> {
protected void onPreExecute(){
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading route. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected String doInBackground(String... params) {
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.loginUser(email, password);
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
loginErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully logged in
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
// Clear all previous data in database
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
// Launch Dashboard Screen
Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Login Screen
finish();
}else{
// Error in login
loginErrorMsg.setText("Incorrect username/password");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pDialog.dismiss();
}
}
}
UserFunctions代码:
public class UserFunctions {
private JSONParser jsonParser;
// Testing in localhost using wamp or xampp
// use http://10.0.2.2/ to connect to your localhost ie http://localhost/
private static String loginURL = "http://192.168.1.33/polizerlogin/";
private static String registerURL = "http://192.168.1.33/polizerlogin/";
private static String login_tag = "login";
private static String register_tag = "register";
// constructor
public UserFunctions(){
jsonParser = new JSONParser();
}
/**
* function make Login Request
* @param email
* @param password
* */
public JSONObject loginUser(String email, String password){
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", login_tag));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
JSONObject json = jsonParser.getJSONFromUrl(loginURL, params);
// return json
// Log.e("JSON", json.toString());
return json;
}
/**
* function make Login Request
* @param name
* @param email
* @param password
* */
public JSONObject registerUser(String name, String email, String password){
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", register_tag));
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
// getting JSON Object
JSONObject json = jsonParser.getJSONFromUrl(registerURL, params);
// return json
return json;
}
/**
* Function get Login status
* */
public boolean isUserLoggedIn(Context context){
DatabaseHandler db = new DatabaseHandler(context);
int count = db.getRowCount();
if(count > 0){
// user logged in
return true;
}
return false;
}
/**
* Function to logout user
* Reset Database
* */
public boolean logoutUser(Context context){
DatabaseHandler db = new DatabaseHandler(context);
db.resetTables();
return true;
}
}
logcat的:
02-01 10:00:45.835: E/JSON(28424): <br />
02-01 10:00:45.835: E/JSON(28424): <font size='1'><table class='xdebug-error xe-parse-error' dir='ltr' border='1' cellspacing='0' cellpadding='1'>
02-01 10:00:45.835: E/JSON(28424): <tr><th align='left' bgcolor='#f57900' colspan="5"><span style='background-color: #cc0000; color: #fce94f; font-size: x-large;'>( ! )</span> Parse error: syntax error, unexpected 'include' (T_INCLUDE), expecting function (T_FUNCTION) in C:\wamp\www\polizerlogin\DB_Functions.php on line <i>5</i></th></tr>
02-01 10:00:45.835: E/JSON(28424): <tr><th align='left' bgcolor='#e9b96e' colspan='5'>Call Stack</th></tr>
02-01 10:00:45.835: E/JSON(28424): <tr><th align='center' bgcolor='#eeeeec'>#</th><th align='left' bgcolor='#eeeeec'>Time</th><th align='left' bgcolor='#eeeeec'>Memory</th><th align='left' bgcolor='#eeeeec'>Function</th><th align='left' bgcolor='#eeeeec'>Location</th></tr>
02-01 10:00:45.835: E/JSON(28424): <tr><td bgcolor='#eeeeec' align='center'>1</td><td bgcolor='#eeeeec' align='center'>0.0160</td><td bgcolor='#eeeeec' align='right'>141040</td><td bgcolor='#eeeeec'>{main}( )</td><td title='C:\wamp\www\polizerlogin\index.php' bgcolor='#eeeeec'>..\index.php<b>:</b>0</td></tr>
02-01 10:00:45.835: E/JSON(28424): </table></font>
02-01 10:00:45.839: E/JSON Parser(28424): Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
02-01 10:00:45.847: E/AndroidRuntime(28424): FATAL EXCEPTION: AsyncTask #4
02-01 10:00:45.847: E/AndroidRuntime(28424): Process: com.mumbaipolice.www, PID: 28424
02-01 10:00:45.847: E/AndroidRuntime(28424): java.lang.RuntimeException: An error occured while executing doInBackground()
02-01 10:00:45.847: E/AndroidRuntime(28424): at android.os.AsyncTask$3.done(AsyncTask.java:300)
02-01 10:00:45.847: E/AndroidRuntime(28424): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
02-01 10:00:45.847: E/AndroidRuntime(28424): at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
02-01 10:00:45.847: E/AndroidRuntime(28424): at java.util.concurrent.FutureTask.run(FutureTask.java:242)
02-01 10:00:45.847: E/AndroidRuntime(28424): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
02-01 10:00:45.847: E/AndroidRuntime(28424): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
02-01 10:00:45.847: E/AndroidRuntime(28424): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
02-01 10:00:45.847: E/AndroidRuntime(28424): at java.lang.Thread.run(Thread.java:818)
02-01 10:00:45.847: E/AndroidRuntime(28424): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.getString(java.lang.String)' on a null object reference
02-01 10:00:45.847: E/AndroidRuntime(28424): at com.mumbaipolice.www.MainActivity$GoOnline.doInBackground(MainActivity.java:92)
02-01 10:00:45.847: E/AndroidRuntime(28424): at com.mumbaipolice.www.MainActivity$GoOnline.doInBackground(MainActivity.java:1)
02-01 10:00:45.847: E/AndroidRuntime(28424): at android.os.AsyncTask$2.call(AsyncTask.java:288)
02-01 10:00:45.847: E/AndroidRuntime(28424): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
02-01 10:00:45.847: E/AndroidRuntime(28424): ... 4 more
02-01 10:00:46.478: E/WindowManager(28424): android.view.WindowLeaked: Activity com.mumbaipolice.www.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{26ba7806 V.E..... R......D 0,0-684,232} that was originally added here
02-01 10:00:46.478: E/WindowManager(28424): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:375)
02-01 10:00:46.478: E/WindowManager(28424): at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:261)
02-01 10:00:46.478: E/WindowManager(28424): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
02-01 10:00:46.478: E/WindowManager(28424): at android.app.Dialog.show(Dialog.java:298)
02-01 10:00:46.478: E/WindowManager(28424): at com.mumbaipolice.www.MainActivity$GoOnline.onPreExecute(MainActivity.java:82)
02-01 10:00:46.478: E/WindowManager(28424): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
02-01 10:00:46.478: E/WindowManager(28424): at android.os.AsyncTask.execute(AsyncTask.java:535)
02-01 10:00:46.478: E/WindowManager(28424): at com.mumbaipolice.www.MainActivity$1.onClick(MainActivity.java:58)
02-01 10:00:46.478: E/WindowManager(28424): at android.view.View.performClick(View.java:4761)
02-01 10:00:46.478: E/WindowManager(28424): at android.view.View$PerformClick.run(View.java:19767)
02-01 10:00:46.478: E/WindowManager(28424): at android.os.Handler.handleCallback(Handler.java:739)
02-01 10:00:46.478: E/WindowManager(28424): at android.os.Handler.dispatchMessage(Handler.java:95)
02-01 10:00:46.478: E/WindowManager(28424): at android.os.Looper.loop(Looper.java:135)
02-01 10:00:46.478: E/WindowManager(28424): at android.app.ActivityThread.main(ActivityThread.java:5312)
02-01 10:00:46.478: E/WindowManager(28424): at java.lang.reflect.Method.invoke(Native Method)
02-01 10:00:46.478: E/WindowManager(28424): at java.lang.reflect.Method.invoke(Method.java:372)
02-01 10:00:46.478: E/WindowManager(28424): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
02-01 10:00:46.478: E/WindowManager(28424): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
02-01 10:01:34.850: I/Process(28424): Sending signal. PID: 28424 SIG: 9
每当我尝试登录或注册应用程序时,我的应用程序都会崩溃。在win32位Eclipse ADT上运行Android 5.0.1。有人可以指出我哪里出错了吗?
答案 0 :(得分:2)
我从你的Logcat中假设以下是PHP代码从你的服务器返回的内容......
02-01 10:00:45.835: E/JSON(28424): <br />
02-01 10:00:45.835: E/JSON(28424): <font size='1'><table class='xdebug-error xe-parse-error' dir='ltr' border='1' cellspacing='0' cellpadding='1'>
02-01 10:00:45.835: E/JSON(28424): <tr><th align='left' bgcolor='#f57900' colspan="5"><span style='background-color: #cc0000; color: #fce94f; font-size: x-large;'>( ! )</span> Parse error: syntax error, unexpected 'include' (T_INCLUDE), expecting function (T_FUNCTION) in C:\wamp\www\polizerlogin\DB_Functions.php on line <i>5</i></th></tr>
02-01 10:00:45.835: E/JSON(28424): <tr><th align='left' bgcolor='#e9b96e' colspan='5'>Call Stack</th></tr>
02-01 10:00:45.835: E/JSON(28424): <tr><th align='center' bgcolor='#eeeeec'>#</th><th align='left' bgcolor='#eeeeec'>Time</th><th align='left' bgcolor='#eeeeec'>Memory</th><th align='left' bgcolor='#eeeeec'>Function</th><th align='left' bgcolor='#eeeeec'>Location</th></tr>
02-01 10:00:45.835: E/JSON(28424): <tr><td bgcolor='#eeeeec' align='center'>1</td><td bgcolor='#eeeeec' align='center'>0.0160</td><td bgcolor='#eeeeec' align='right'>141040</td><td bgcolor='#eeeeec'>{main}( )</td><td title='C:\wamp\www\polizerlogin\index.php' bgcolor='#eeeeec'>..\index.php<b>:</b>0</td></tr>
02-01 10:00:45.835: E/JSON(28424): </table></font>
请注意以上第3行的以下内容......
Parse error: syntax error, unexpected 'include' (T_INCLUDE), expecting function (T_FUNCTION) in C:\wamp\www\polizerlogin\DB_Functions.php on line <i>5</i>
我不是一个PHP程序员,但这表明我的PHP第5行存在问题。这是有道理的,因为它有一个include指令...
include 'config.php'
正如我所说,我不会对PHP做很多事情,但是如果你能找到错误的原因并修复它(加上可能会在PHP代码中加入一些错误处理),那么你应该得到有效的结果。< / p>
我可以看到你正在测试......
if (json.getString(KEY_SUCCESS) != null)
...和...
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
在这种情况下,PHP端的正确错误处理应返回有效的JSON,但设置KEY_SUCCESS
表示错误。它是生成HTML响应的服务器,如果你修复它,那么事情应该没问题。
但是,您的代码确实存在另一个严重缺陷。在您doInBackground(...)
AsyncTask
的{{1}}中,您尝试修改TextView
,如下所示......
loginErrorMsg.setText("");
...您无法触及doInBackground(...)
主题中的任何UI元素。最好的办法就是使用doInBackground(...)
来抓住&#39;网络响应,然后将其返回onPostExecute(...)
,以便它可以处理它。