如何从用户实际键入的EditText小部件中获取文本,我不断在我的数据库中获取此文本:" android.support.v7.widget.AppCompatEditText {e67388"。
我得到了这样的答复: 注册响应:{"错误":false," uid":" 56807035b02430.42354570","用户":{" first_name& #34;:"汤姆""姓氏":"黑""电子邮件":" tom@tom.com 34;,的" pets_race":" {android.support.v7.widget.AppCompatEditText e67388" ," pets_name&#34 ;: " {android.support.v7.widget.AppCompatEditText 2c8d71" 下," created_at":" 2015年12月28日""&的updated_at #34;:空}}
我正在使用wamp服务器。以下是与DB有关的所有文件:
RegistrationPage.java
package com.adicili.petdetective;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import com.adicili.petdetective.R;
import com.adicili.petdetective.AppConfig;
import com.adicili.petdetective.AppController;
import com.adicili.petdetective.SQLiteHandler;
import com.adicili.petdetective.SessionManager;
public class RegistrationPage extends AppCompatActivity {
private static final String TAG = RegistrationPage.class.getSimpleName();
private Button btnRegister;
private Button btnBackToLogin;
private EditText inputFirstName;
private EditText inputLastName;
private EditText inputEmail;
private EditText inputPassword;
private EditText inputPetsRace;
private EditText inputPetsName;
private ProgressDialog pDialog;
private SessionManager session;
private SQLiteHandler db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration_page);
inputFirstName = (EditText) findViewById(R.id.inputFirstName);
inputLastName = (EditText) findViewById(R.id.inputLastName);
inputEmail = (EditText) findViewById(R.id.inputEmailReg);
inputPassword = (EditText) findViewById(R.id.inputPasswordReg);
inputPetsRace = (EditText) findViewById(R.id.inputPetsRace);
inputPetsName = (EditText) findViewById(R.id.inputPetsName);
btnRegister = (Button) findViewById(R.id.btnRegister);
btnBackToLogin = (Button) findViewById(R.id.btnBackToLogin);
//PRogress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
//Session manager
session = new SessionManager(getApplicationContext());
//SQLite database handler
db = new SQLiteHandler(getApplicationContext());
//Check if user is already logged in or not
if (session.isLoggedIn()){
//User is alreday logged in. Take him to main activity
Intent intent = new Intent(RegistrationPage.this, HomePage.class);
startActivity(intent);
finish();
}
//Register Button Click event
btnRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view){
String first_name = inputFirstName.getText().toString().trim();
String last_name = inputLastName.getText().toString().trim();
String email = inputEmail.getText().toString().trim();
String password = inputPassword.toString().trim();
String pets_race = inputPetsRace.toString();
String pets_name = inputPetsName.toString();
if(!first_name.isEmpty() && !last_name.isEmpty() && !password.isEmpty() && !email.isEmpty()){
registerUser(first_name, last_name, email, password, pets_race, pets_name);
}else{
Toast.makeText(getApplicationContext(),"Please enter your details!", Toast.LENGTH_LONG).show();
}
}
});
//Link to Login Screen
btnBackToLogin.setOnClickListener(new View.OnClickListener(){
public void onClick(View view){
Intent intent = new Intent(getApplicationContext(),LoginPage.class);
startActivity(intent);
finish();
}
});
}
/*
*Function to store user in MySQL dataase will post params to *register url
*/
private void registerUser(final String first_name, final String last_name, final String email, final String password, final String pets_race, final String pets_name){
//Tag used to cacel request
String tag_string_req = "req_register";
pDialog.setMessage("Registering...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST, AppConfig.URL_REGISTER, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
//User successfully stored in DB
//Now store user in SQL lite
String uid = jObj.getString("uid");
JSONObject user = jObj.getJSONObject("user");
String first_name = user.getString("first_name");
String last_name = user.getString("last_name");
String email = user.getString("email");
String pets_race = user.getString("pets_race");
String pets_name = user.getString("pets_name");
String created_at = user.getString("created_at");
//Inserting row in DB
db.addUser(first_name, last_name, email, pets_race, pets_name, uid, created_at);
Intent intent = new Intent(RegistrationPage.this, LoginPage.class);
startActivity(intent);
finish();
Toast.makeText(getApplicationContext(), "User successfully registered. Try Login now!", Toast.LENGTH_LONG).show();
} else {
//Error occured in registration. Get the error
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(), errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}){
@Override
protected Map<String,String> getParams(){
//Postinf params to register url
Map<String,String> params = new HashMap<String, String>();
params.put("first_name", first_name);
params.put("last_name", last_name);
params.put("email", email);
params.put("password", password);
params.put("pets_race", pets_race);
params.put("pets_name", pets_name);
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();
}
}
SQLiteHandler.java
package com.adicili.petdetective;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.HashMap;
public class SQLiteHandler extends SQLiteOpenHelper {
public static final String TAG = SQLiteHandler.class.getSimpleName();
//All static variables
//Database Version
private static final int DATABASE_VERSION = 1;
//Database Name
private static final String DATABASE_NAME = "android_api";
//Login table name
private static final String TABLE_USER = "user";
//Login Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_FIRST_NAME = "first_name";
private static final String KEY_LAST_NAME = "last_name";
private static final String KEY_EMAIL = "email";
private static final String KEY_PETS_RACE = "pets_race";
private static final String KEY_PETS_NAME = "pets_name";
private static final String KEY_UID = "uid";
private static final String KEY_CREATED_AT = "created_at";
public SQLiteHandler(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
//Creating tables
@Override
public void onCreate(SQLiteDatabase db){
String CREATE_LOGIN_TABLE = "Create table " + TABLE_USER + "(" + KEY_ID + " Integer primary key," + KEY_FIRST_NAME + " Text," + KEY_LAST_NAME + " Text," + KEY_EMAIL + " Text unique," + KEY_PETS_RACE + " Text," + KEY_PETS_NAME + " Text," + KEY_UID + " Text," + KEY_CREATED_AT + " Text" + ")";
db.execSQL(CREATE_LOGIN_TABLE);
Log.d(TAG, "DATABASE tables created");
}
//Upgrading daabase
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
//Drop older table if existed
db.execSQL("Drop table if exists " + TABLE_USER);
//Create tables again
onCreate(db);
}
/**
* Storing user details in database
*/
public void addUser(String first_name, String last_name, String email, String pets_race, String pets_name, String uid, String created_at){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_FIRST_NAME, first_name);
values.put(KEY_LAST_NAME, last_name);
values.put(KEY_EMAIL, email);
values.put(KEY_PETS_RACE, pets_race);
values.put(KEY_PETS_NAME, pets_name);
values.put(KEY_UID, uid);
values.put(KEY_CREATED_AT, created_at);
//Inserting row
long id = db.insert(TABLE_USER,null,values);
db.close();//closing db connection
Log.d(TAG, "New user inserted into sqlite: " + id);
}
/*
*Getting user data from database
*/
public HashMap<String, String> getUserDetails(){
HashMap<String,String> user = new HashMap<String, String>();
String selectQuery = "Select * from " + TABLE_USER;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
//Move to first row
cursor.moveToFirst();
if(cursor.getCount()>0){
user.put("first_name", cursor.getString(1));
user.put("last_name", cursor.getString(2));
user.put("email", cursor.getString(3));
user.put("pets_race", cursor.getString(4));
user.put("pets_name", cursor.getString(5));
user.put("uid", cursor.getString(6));
user.put("created_at", cursor.getString(7));
}
cursor.close();
db.close();
//return user
Log.d(TAG,"Fetching user from sqlite: " +user.toString());
return user;
}
/*
*Re create database Delete all tables and create them again
*/
public void deleteUsers(){
SQLiteDatabase db = this.getWritableDatabase();
//Delete all rows
db.delete(TABLE_USER,null,null);
db.close();
Log.d(TAG,"Delete all user info from sqlite");
}
}
register.php
<?php
require_once 'DB_Functions.php';
$db = new DB_Functions();
//json response array
$responce = array("error" => FALSE);
if(isset($_POST['first_name']) && isset($_POST['last_name']) && isset($_POST['email']) && isset($_POST['password'])){
//recieving the post params
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
$password = $_POST['password'];
$pets_race = $_POST['pets_race'];
$pets_name = $_POST['pets_name'];
//check if user already existrd with same email
if($db->isUserExisted($email)){
//user already existed
$responce["error"] = TRUE;
$responce["error_msg"] = "User already existed with " . $email;
echo json_encode($responce);
}else{
//create new user
$user = $db->storeUser($first_name,$last_name,$email,$password,$pets_race,$pets_name);
if($user){
//user stored successfully
$responce["error"] = FALSE;
$responce["uid"] = $user["unique_id"];
$responce["user"]["first_name"] = $user["first_name"];
$responce["user"]["last_name"] = $user["last_name"];
$responce["user"]["email"] = $user["email"];
$responce["user"]["pets_race"] = $user["pets_race"];
$responce["user"]["pets_name"] = $user["pets_name"];
$responce["user"]["created_at"] = $user["created_at"];
$responce["user"]["updated_at"] = $user["updated_at"];
echo json_encode($responce);
}else{
//user failed to store
$responce["error"] = TRUE;
$responce["error_msg"]= "Unknown error occured in registration!";
echo json_encode($responce);
}
}
}else{
$responce["error"]=TRUE;
$responce["error_msg"] = "Required parameters (First Name, Last Name, email or password) is missing!";
echo json_encode($responce);
}
?>
来自DB_Functions.php的storeUser方法:
<?php
class DB_Functions{
private $conn;
//constructor
Function __construct(){
require_once 'DB_Connect.php';
//connecting to db
$db = new Db_connect();
$this->conn = $db->connect();
}
//destructir
function __destruct(){
}
/**
*Storing new user
*returns user details
*/
public function storeUser($first_name, $last_name, $email, $password, $pets_race, $pets_name){
$uuid = uniqid('',true);
$hash = $this->hashSSHA($password);
$encrypted_password = $hash["encrypted"];
$salt = $hash["salt"];
$stmt = $this->conn->prepare("Insert INTO users(unique_id, first_name, last_name, email, encrypted_password, pets_race,pets_name,salt,created_at) values (?,?,?,?,?,?,?,?,NOW())");
$stmt->bind_param("ssssssss",$uuid,$first_name,$last_name, $email,$encrypted_password,$pets_race,$pets_name,$salt);
$result = $stmt->execute();
$stmt->close();
//check for successfull store
if($result){
$stmt = $this->conn->prepare("select * from users where email = ?");
$stmt->bind_param("s",$email);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();
return $user;
}else{
return false;
}
}
如果您还有其他需要,请告诉我。感谢
答案 0 :(得分:10)
要从EditText
检索纯文字,请使用getText().toString()
,而不只是toString()
。