我正在尝试创建一个新闻应用程序,我需要注册新闻并获取当前登录用户的 id 作为我的 PHP 文件的参数。
我已经有了登录/注销系统,并将其保存在我的共享首选项文件中。
我这么问是因为我对如何使用 PHP 和 Android Studio 实现这一目标没有足够的了解。
这是我的文件,我只需要一个正确的方向,说明在这个问题上最好的方法是什么,甚至供将来引用?
如果您愿意提供帮助,请提前致谢。
常数
public class Constants {
private static final String ROOT_URL = "http://localhost/android/v1/";
public static final String URL_REGISTER = ROOT_URL+"registerUser.php";
public static final String URL_LOGIN = ROOT_URL+"userLogin.php";
}
数据库操作
<?php
class DBOperations{
private $con;
private $res;
function __construct(){
require_once dirname(__FILE__).'/DBConnect.php';
$db = new DBConnect();
$this->con = $db->connect();
}
/*CRUD -> C -> CREATE */
public function createUser($username, $password, $email){
if($this->isUserRegistered($username,$email)){
return 0;
}else{
$stmt = $this->con->prepare("INSERT INTO `users` (`id`, `username`, `password`, `email`) VALUES (NULL, ?, ?, ?);");
$stmt->bind_param("sss",$username,$password,$email);
if($stmt->execute()){
return 1;
}else{
return 2;
}
}
}
public function registerNews($news_post, $user_FK){
$stmt = $this->con->prepare("INSERT INTO `news` (`id`, `news_post`, `user_FK`) VALUES (NULL, ?, ?);");
$stmt->bind_param("sss",$news_post,$user_FK);
if($stmt->execute()){
return 1;
}else{
return 2;
}
}
}
数据库注册用户
<?php
require_once '../includes/DBOperations.php';
$response = array();
if($_SERVER['REQUEST_METHOD']=='POST'){
if(
isset($_POST['username']) and
isset($_POST['email']) and
isset($_POST['password']))
{
//operate the data further
$db = new DBOperations();
$result = $db->createUser( $_POST['username'],
$_POST['password'],
$_POST['email']
);
if($result == 1){
$response['error'] = false;
$response['message'] = "User registered successfully";
}elseif($result == 2){
$response['error'] = true;
$response['message'] = "Some error occurred please try again";
}elseif($result == 0){
$response['error'] = true;
$response['message'] = "It seems you are already registered, please choose a different email and username";
}
}else{
$response['error'] = true;
$response['message'] = "Required fields are missing";
}
}else{
$response['error'] = true;
$response['message'] = "Invalid Request";
}
echo json_encode($response);
DBRegisterNews(不知道如何更改)
<?php
require_once '../includes/DBOperations.php';
$response = array();
if($_SERVER['REQUEST_METHOD']=='POST'){
if(
isset($_POST['userid']) and
isset($_POST['email']) and
isset($_POST['password']))
{
//operate the data further
$db = new DBOperations();
$result = $db->registerNews($_POST['userid'],
$_POST['password'],
$_POST['email']
);
if($result == 1){
$response['error'] = false;
$response['message'] = "News registered successfully";
}elseif($result == 2){
$response['error'] = true;
$response['message'] = "Some error occurred please try again";
}
}else{
$response['error'] = true;
$response['message'] = "Required fields are missing";
}
}else{
$response['error'] = true;
$response['message'] = "Invalid Request";
}
echo json_encode($response);
注册(供引用,工作)
public class SignUpActivity extends AppCompatActivity {
private TextInputEditText editTextUsername, editTextEmail, editTextPassword, editTextConfirmPassword;
private ProgressBar bar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
editTextUsername = findViewById(R.id.editTextLoginUsername);
editTextEmail = findViewById(R.id.editTextEmail);
editTextPassword = findViewById(R.id.editTextLoginPassword);
editTextConfirmPassword = findViewById(R.id.editTextConfirmPassword);
bar = findViewById(R.id.progressBar);
bar.setVisibility(View.GONE);
}
public void registerUser(View view) {
final String username = editTextUsername.getText().toString();
final String email = editTextEmail.getText().toString();
final String password = editTextPassword.getText().toString();
final String confirmPassword = editTextConfirmPassword.getText().toString();
if (password.equals(confirmPassword) || confirmPassword.equals(password)) {
bar.setVisibility(View.VISIBLE);
StringRequest stringRequest = new StringRequest(Request.Method.POST,
Constants.URL_REGISTER,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
bar.setVisibility(View.GONE);
try {
JSONObject jsonObject = new JSONObject(response);
Toast.makeText(getApplicationContext(), jsonObject.getString("message"),
Toast.LENGTH_LONG).show();
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
bar.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), "Erro: " + error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("username", username);
params.put("email", email);
params.put("password", password);
return params;
}
};
RequestHandler.getInstance(getApplicationContext()).addToRequestQueue(stringRequest);
} else {
Toast.makeText(getApplicationContext(), "Senhas não conferem, tente novamente", Toast.LENGTH_LONG).show();
}
}
}
PostNews(我需要在这里做一些更改)
public class PostNews extends AppCompatActivity {
private Button btnpostar;
private EditText editTextNewsPost, editTextUserFK;
private ProgressBar bar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post_news);
editTextNewsPost = findViewById(R.id.EditTextNewsPost);
btnpostar = findViewById(R.id.btnPostar);
}
public void salvarNoticia(View view) {
final String post = editTextNewsPost.getText().toString();
if (!post.equals("")) {
bar.setVisibility(View.VISIBLE);
StringRequest stringRequest = new StringRequest(Request.Method.POST,
Constants.URL_REGISTER,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
bar.setVisibility(View.GONE);
try {
JSONObject jsonObject = new JSONObject(response);
Toast.makeText(getApplicationContext(), jsonObject.getString("message"),
Toast.LENGTH_LONG).show();
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
bar.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), "Erro: " + error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
return params;
}
};
RequestHandler.getInstance(getApplicationContext()).addToRequestQueue(stringRequest);
} else {
Toast.makeText(getApplicationContext(), "Por favor, não poste nada em branco", Toast.LENGTH_LONG).show();
}
}
}
共享首选项
public class SharedPrefManager {
private static SharedPrefManager mInstance;
private static Context mCtext;
private static final String SHARED_PREF_NAME = "myname";
private static final String KEY_USERNAME = "username";
private static final String KEY_USER_EMAIL = "useremail";
private static final String KEY_USER_ID = "userid";
private SharedPrefManager(android.content.Context context){
mCtext = context;
}
public static synchronized SharedPrefManager getInstance(Context context){
if (mInstance == null) {
mInstance = new SharedPrefManager(context);
}
return mInstance;
}
public boolean userLogin(int id, String username, String email){
SharedPreferences sharedPreferences = mCtext.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(KEY_USER_ID, id);
editor.putString(KEY_USER_EMAIL, email);
editor.putString(KEY_USERNAME, username);
editor.apply();
return true;
}
public boolean isLoggedin(){
SharedPreferences sharedPreferences = mCtext.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
if (sharedPreferences.getString(KEY_USERNAME,null) != null){
return true;
}
return false;
}
public boolean logout(){
SharedPreferences sharedPreferences = mCtext.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.apply();
return true;
}
public String getUsername(){
SharedPreferences sharedPreferences = mCtext.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(KEY_USERNAME, null);
}
public String getUserEmail(){
SharedPreferences sharedPreferences = mCtext.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(KEY_USER_EMAIL, null);
}
}
最佳答案
如果用户已经注册,您可以在此处返回用户 ID:
public function createUser($username, $password, $email){
if($this->isUserRegistered($username,$email)){
//return 0; <-- do not return 0
$userID = ...//get user id from db using $username and $email
return $userID;
}else{
如果您操作返回值,您可以将代码更改为类似以下内容并将 userID 添加到您的响应中:
$result = $db->createUser( $_POST['username'],
$_POST['password'],
$_POST['email']
);
if($result == -1){
$response['error'] = false;
$response['message'] = "User registered successfully";
}elseif($result == -2){
$response['error'] = true;
$response['message'] = "Some error occurred please try again";
}elseif($result > 0){
$response['error'] = true;
$response['message'] = "It seems you are already registered, please choose a different email and username";
$response['userID'] = $result;
}
关于PHP/AndroidStudio - 通过让当前用户作为外键登录来发帖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49258749/