简体   繁体   中英

PHP/AndroidStudio - Make a post by getting the current user logged in as foreign key

I'm trying to make a news application and I need to register the news and get the id of the current logged in user as a parameter to my PHP file.

I already have the login/logout system and I'm saving it at my Shared Preferences file.

I'm asking because I don't have enough knowledge on how to achieve this with PHP and Android Studio.

Here are my files, I just need a point in the right direction on what should be the best approach on this matter, even for future references?

Thank you in advance if you are willing to help.

Constants

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";
}

DBOperations

<?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; 
            }
    }

}

DBRegisterUser

<?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(Don't know how to change this)

    <?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);

SignUp (for reference, working)

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 (I need to do some changes here)

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();
        }

    }
}

SharedPreferences

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);
    }
}

In case user is already registered, you can return user id here:

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{

If you manipulate returned values, you can change your code to something like this and add userID to your response:

       $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;                   
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM