我一直在尝试向数据库添加列。我开始使用this tutorial,但需要在名为'network'的数据库表中添加另一个字段。我在几个地方编辑了代码。注册工作,但登录没有。
我不断收到标题中描述的错误以及其他一些错误:
我一直在查看StackOverflow上的一些答案,并尝试了尽可能多的答案。我删除了我的数据库和我的表并重新创建了它。我正在使用WAMP,所以要从头重新启动,我卸载并重新安装了WAMP。我也再次卸载WAMP并切换到XAMPP,但问题仍然存在。错误不会消失。还有什么呢? (为了清楚起见,我现在再次使用WAMP。)
如果您需要更多代码,请与我们联系。非常感谢您的帮助。
以下是我的taxi_login_api文件夹中WAMP的'www'文件夹中的php文件:
<?php
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, "success" => 0, "error" => 0);
// check for tag type
if ($tag == 'login') {
// Request type is check Login
$email = $_POST['email'];
$password = $_POST['password'];
// check for user
$user = $db->getUserByEmailAndPassword($email, $password);
if ($user != false) {
// user found
// echo json with success = 1
$response["success"] = 1;
$response["uid"] = $user["unique_id"];
$response["user"]["name"] = $user["name"];
$response["user"]["email"] = $user["email"];
$response["user"]["network"] = $user["network"];
$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"] = 1;
$response["error_msg"] = "Incorrect email or password!";
echo json_encode($response);
}
} else if ($tag == 'register') {
// Request type is Register new user
$name = $_POST['name'];
$email = $_POST['email'];
$network = $_POST['network'];
$password = $_POST['password'];
// check if user is already existed
if ($db->isUserExisted($email)) {
// user is already existed - error response
$response["error"] = 2;
$response["error_msg"] = "User already existed";
echo json_encode($response);
} else {
// store user
$user = $db->storeUser($name, $email, $network, $password);
if ($user) {
// user stored successfully
$response["success"] = 1;
$response["uid"] = $user["unique_id"];
$response["user"]["name"] = $user["name"];
$response["user"]["email"] = $user["email"];
$response["user"]["network"] = $user["network"];
$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"] = 1;
$response["error_msg"] = "Error occured in Registartion";
echo json_encode($response);
}
}
} else {
echo "Invalid Request";
}
} else {
echo "Access Denied";
}
?>
WWW / taxi_login_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, $network, $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, network, encrypted_password, salt, created_at) VALUES('$uuid', '$name', '$email', '$network', '$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 email and password
*/
public function getUserByEmailAndPassword($email, $password) {
$result = mysql_query("SELECT * FROM users WHERE email = '$email'") 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($email) {
$result = mysql_query("SELECT email from users WHERE email = '$email'");
$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;
}
}
?>
DB_Connect:
<?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();
}
}
?>
LoginActivity:
public class LoginActivity extends ActionBarActivity
{
private String email;
private String password;
private ActionBar actionBar;
// 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_NETWORK = "network";
private static String KEY_CREATED_AT = "created_at";
TextView loginErrorMsg;
public void submitLoginFields(View view)
{
Log.v("Testing", "submitLoginFields method");
final EditText emailField = (EditText) findViewById(R.id.emailEditTextLogin);
final EditText passwordField = (EditText) findViewById(R.id.passEditTextLogin);
loginErrorMsg = (TextView) findViewById(R.id.login_error);
email = emailField.getText().toString();
password = passwordField.getText().toString();
Log.v("Testing", "Login email: " + email);
Log.v("Testing", "Login Password: " + password);
new MyAsyncTask().execute(email, password);
}
private class MyAsyncTask extends AsyncTask<String, Void, JSONObject>
{
protected JSONObject doInBackground(String ... params)
{
UserFunctions userFunction = new UserFunctions();
if (params.length != 2)
return null;
JSONObject json = userFunction.loginUser(params[0], params[1]);
return json;
}
protected void onPostExecute(JSONObject json)
{
try
{
Log.v("Testing", "b");
if (json != null && json.getString(KEY_SUCCESS) != null)
{
Log.v("Testing", "c");
loginErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1)
{
Log.v("Testing", "b");
// user successfully logged in
// Store user details in SQLite Database
UserDatabaseHandler db = new UserDatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
// Clear all previous data in database
UserFunctions userFunction = new UserFunctions();
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json_user.getString(KEY_NETWORK),
json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT)); //TODO
// 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);
finish(); // Close login screen
}
else
{
// Error in login
loginErrorMsg.setText(R.string.error_message_login);
}
}
}
catch (JSONException e)
{
loginErrorMsg.setText("Server error. Please try again later.");
e.printStackTrace();
}
}
}
}
UserFunctions.java:
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://10.0.2.2/taxi_login_api/";
private static String registerURL = "http://10.0.2.2/taxi_login_api/";
private static String login_tag = "login";
private static String register_tag = "register";
// constructor
public UserFunctions()
{
Log.v("Testing", "Calling UserFunctions constructor");
jsonParser = new JSONParser();
}
/**
* Method to make a 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;
}
/**
* Method to make a registration request.
* @param name
* @param email
* @param password
* */
public JSONObject registerUser(String name, String email, String network, String password) // TODO
{
// 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("network", network)); // TODO
params.add(new BasicNameValuePair("password", password));
// getting JSON Object
JSONObject json = jsonParser.getJSONFromUrl(registerURL, params);
return json; // return json
}
/**
* Method to get login status. Returns true if logged in, false if not.
* */
public boolean isUserLoggedIn(Context context)
{
UserDatabaseHandler db = new UserDatabaseHandler(context);
int count = db.getRowCount();
if(count > 0) // user logged in
{
return true;
}
return false;
}
/**
* Method to logout user and reset database.
* */
public boolean logoutUser(Context context)
{
UserDatabaseHandler db = new UserDatabaseHandler(context);
db.resetTables();
return true;
}
}
UserDatabaseHandler:
public class UserDatabaseHandler extends SQLiteOpenHelper
{
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "user_db";
private static final String TABLE_LOGIN = "login";
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_EMAIL = "email";
private static final String KEY_NETWORK = "network"; // TODO
private static final String KEY_UID = "uid";
private static final String KEY_CREATED_AT = "created_at";
public UserDatabaseHandler(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db)
{
String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_LOGIN + "("
+ KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_NAME + " TEXT,"
+ KEY_EMAIL + " TEXT UNIQUE,"
+ KEY_NETWORK + " TEXT,"
+ KEY_UID + " TEXT,"
+ KEY_CREATED_AT + " TEXT" + ");"; // TODO
db.execSQL(CREATE_LOGIN_TABLE);
}
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOGIN);
// Create tables again
onCreate(db);
}
/**
* Storing user details in database
* */
public void addUser(String name, String email, String network, String uid, String created_at)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, name); // Name
values.put(KEY_EMAIL, email); // Email
values.put(KEY_NETWORK, network); // TODO
values.put(KEY_UID, uid); // Email
values.put(KEY_CREATED_AT, created_at); // Created at
// Inserting Row
db.insert(TABLE_LOGIN, null, values);
db.close(); // Closing database connection
}
/**
* Getting user data from database
* */
public HashMap<String, String> getUserDetails()
{
HashMap<String,String> user = new HashMap<String,String>();
String selectQuery = "SELECT * FROM " + TABLE_LOGIN;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
if(cursor.getCount() > 0)
{
user.put("name", cursor.getString(1));
user.put("email", cursor.getString(2));
user.put("network", cursor.getString(3)); // TODO
user.put("uid", cursor.getString(4));
user.put("created_at", cursor.getString(5));
}
cursor.close();
db.close();
return user;
}
/**
* Getting user login status
* return true if rows are there in table
* */
public int getRowCount()
{
String countQuery = "SELECT * FROM " + TABLE_LOGIN;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int rowCount = cursor.getCount();
db.close();
cursor.close();
return rowCount;
}
/**
* Re crate database
* Delete all tables and create them again
* */
public void resetTables()
{
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_LOGIN, null, null); // Delete all rows
db.close();
}
}
JSONParser.java:
public class JSONParser
{
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params)
{
Log.v("Testing", "JSONParser class, getJSONFromUrl method");
// Making HTTP request
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new
InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
is.close();
json = sb.toString();
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jObj; // return JSON String
}
}
我希望我没有粘贴太多;我认为太多比太少好。再次谢谢你;我现在已经被困在这两天了,并且没有想法尝试。我不知道如何进一步重新启动数据库,即使这似乎解决了其他一些关于此错误的问题。
答案 0 :(得分:1)
SQLiteOpenHelper
才会调用onCreate()
。如果修改数据库帮助程序中的表模式,则必须确保还更新任何现有数据库文件。
在开发过程中,最简单的方法是通过删除数据库文件来强制创建数据库。这可以通过卸载应用程序或清除应用程序管理器中的应用程序数据来完成。