android-使用codeigniter登录和注册表单

qlzsbp2j  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(370)

大家好!我目前正在使用android和codeigniter(php)开发我的健身馆(web和移动)应用程序。我在注册表中遇到了一个问题,因为当我填写字段时,它没有保存在localhost/phpmyadmin中。我在android中使用asynctask。这些是我的密码:
注册活动.java

public class RegisterActivity extends AppCompatActivity implements RegisterUserTask.OnSignUpListener {
private EditText etUsername;
private EditText etPassword;
private EditText etConfirmPassword;
private EditText etEmail;
private Button btnSignup;
private TextInputLayout tilUsername;
private TextInputLayout tilPassword;
private TextInputLayout tilConfirmPassword;
private TextInputLayout tilEmail;

private int resultCode;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);

    etUsername = (EditText) findViewById(R.id.signup_et_username);
    etPassword = (EditText) findViewById(R.id.signup_et_password);
    etConfirmPassword = (EditText) findViewById(R.id.signup_et_confirm_password);
    etEmail = (EditText) findViewById(R.id.signup_et_email);

    tilUsername = (TextInputLayout) findViewById(R.id.signup_username_container);
    tilPassword = (TextInputLayout) findViewById(R.id.signup_password_container);
    tilConfirmPassword = (TextInputLayout) findViewById(R.id.signup_confirm_password_container);
    tilEmail = (TextInputLayout) findViewById(R.id.signup_email_container);

    btnSignup = (Button) findViewById(R.id.signup_btn_signup);
    btnSignup.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            resultCode = 2;
            if (verifiedInputValues())
                RegisterUserTask.execute(RegisterActivity.this);
        }
    });
}

private boolean verifiedInputValues() {
    String username = etUsername.getText().toString().trim();
    String password = etPassword.getText().toString().trim();
    String confirmPassword = etConfirmPassword.getText().toString().trim();
    String email = etEmail.getText().toString().trim();

    boolean verified = true;

    if (username.isEmpty()) {
        tilUsername.setError(getResources().getString(R.string.snackbar_fail_empty_field));
        verified = false;
    }
    else tilUsername.setError(null);

    if (password.isEmpty()){
        tilPassword.setError(getResources().getString(R.string.snackbar_fail_empty_field));
        verified = false;
    }
    else if (!password.equals(confirmPassword)) {
        tilPassword.setError(getResources().getString(R.string.snackbar_fail_password_mismatch));
        verified = false;
    }
    else tilPassword.setError(null);

    if (confirmPassword.isEmpty()) {
        tilConfirmPassword.setError(getResources().getString(R.string.snackbar_fail_empty_field));
        verified = false;
    }
    else if (!password.equals(confirmPassword)) {
        tilConfirmPassword.setError(getResources().getString(R.string.snackbar_fail_password_mismatch));
        verified = false;
    }
    else tilConfirmPassword.setError(null);

    if (email.isEmpty()) {
        tilEmail.setError(getResources().getString(R.string.snackbar_fail_empty_field));
        verified = false;
    }
    else if (!email.matches("[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+")) {
        tilEmail.setError(getResources().getString(R.string.snackbar_fail_email_invalid));
        verified = false;
    }
    else tilEmail.setError(null);

    return verified;
}

private void checkResultCode() {
    boolean errorDuplicateUsername = resultCode == -1;
    boolean errorDuplicateEmail = resultCode == -2;

    if (errorDuplicateUsername) {
        Toast.makeText(this, R.string.snackbar_fail_signup_duplicate_username, Toast.LENGTH_SHORT).show();
    }
    else if (errorDuplicateEmail) {
        Toast.makeText(this, R.string.snackbar_fail_signup_duplicate_email, Toast.LENGTH_SHORT).show();
    }
    else if (resultCode == 1) {
        Toast.makeText(this, R.string.snackbar_success_signup, Toast.LENGTH_SHORT).show();
        Toast.makeText(this, R.string.snackbar_success_signup_verify_msg, Toast.LENGTH_LONG).show();
        finish();
    }
    else {
        Toast.makeText(this, R.string.snackbar_fail_signup_unable, Toast.LENGTH_SHORT).show();
    }
}

@Override
public void parseJSONString(String jsonString) {
    try {
        JSONObject jsonObject = new JSONObject(jsonString);
        resultCode = jsonObject.getInt("register");
    } catch (JSONException ignored) {}

    checkResultCode();
}

@Override
public String createSignUpPostString(ContentValues contentValues) throws UnsupportedEncodingException {
    String username = etUsername.getText().toString().trim();
    String password = etPassword.getText().toString().trim();
    String email = etEmail.getText().toString().trim();

    contentValues.put("register", true);
    contentValues.put("username", username);
    contentValues.put("password", password);
    contentValues.put("email", email);

    return RequestStringCreator.create(contentValues);
}
}

registerusertask.java文件

public class RegisterUserTask extends AsyncTask<Void, Void, String> {
public static void execute(Context context) {
    new RegisterUserTask(context).execute();
}

public interface OnSignUpListener {
    void parseJSONString(String jsonString);
    String createSignUpPostString(ContentValues contentValues) throws UnsupportedEncodingException;
}

private final Context context;
private final ProgressDialog progressDialog;

public RegisterUserTask(Context context) {
    this.context = context;
    progressDialog = new ProgressDialog(context);
}

@Override
protected String doInBackground(Void... params) {
    try {
        URL url = new URL(TaskConfig.ADD_USER_URL);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setDoInput(true);
        httpURLConnection.setDoOutput(true);

        OutputStream outputStream = new BufferedOutputStream(httpURLConnection.getOutputStream());
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));

        String postString = ((OnSignUpListener)context).createSignUpPostString(new ContentValues());
        bufferedWriter.write(postString);

        bufferedWriter.flush();
        bufferedWriter.close();
        outputStream.close();

        InputStream inputStream = new BufferedInputStream(httpURLConnection.getInputStream());
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

        StringBuilder stringBuilder = new StringBuilder();
        String line = "";

        while ((line = bufferedReader.readLine()) != null)
            stringBuilder.append(line);

        bufferedReader.close();
        inputStream.close();

        httpURLConnection.disconnect();

        return stringBuilder.toString();
    } catch (Exception e) {}
    return null;
}

@Override
protected void onPreExecute() {
    super.onPreExecute();
    progressDialog.setTitle(R.string.progress_signup_title);
    progressDialog.setMessage(context.getResources().getString(R.string.progress_signup_msg));
    progressDialog.setIndeterminate(false);
    progressDialog.setCancelable(true);
    progressDialog.show();
}

@Override
protected void onPostExecute(String jsonString) {
    super.onPostExecute(jsonString);
    progressDialog.dismiss();
    try {
        ((OnSignUpListener)context).parseJSONString(jsonString);
    } catch (Exception e) {}
}
}

任务配置.java

public final class TaskConfig {
public static final String HTTP_HOST = "http://172.16.0.173/";
public static final String DIR_URL = "workoutgym/";
public static final String DIR_ACTION_URL = DIR_URL + "mobile/";
public static final String LOGIN_URL = HTTP_HOST + DIR_ACTION_URL + "login";
public static final String ADD_USER_URL = HTTP_HOST + DIR_ACTION_URL + "check_user";}

控制器:
移动电话.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Mobile extends CI_Controller {
    public function __construct() {
        parent::__construct();
        $this->load->model('Mobile_model');
        if (!$this->input->post('android', TRUE)) {
            show_404();
        }
    }

    public function index() {
        show_404();
    }

    public function check_user() {
        $table = 'users';
        $register = $this->input->post('register', TRUE);
        if ($register == 1) {
            $data = array(
                'username' => input_filter($this->input->post('username', TRUE)),
                'password' => input_filter($this->input->post('password', TRUE)),
                'email' => input_filter($this->input->post('email', TRUE)),
            );

            if ($this->Mobile_model->insert_user($table, $data)) {
                $userdata = $this->Mobile_model->read(
                    $table, array('id' => $data['id'])
                );;
                echo json_encode(array('register' => $userdata[0]->id));
            }
        }
    }
}

型号:
移动设备模型.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Mobile_model extends CI_Model {
    public function __construct() {
        parent::__construct();
    }

    public function insert_user($table, $data, $where = NULL) {
        if (!empty($where)) {
            $this->db->where($where);
        }
        $this->db->insert($table, $data);
        return $this->db->affected_rows();
    }

    public function read($table, $where = NULL) {
        if (!empty($where)) {
            $this->db->where($where);
        }
        $query = $this->db->get($table);
        return ($query->num_rows() > 0) ? $query->result() : FALSE;
    }
}
?>

我使用xampp,visualcodestudio作为我的codeigniter(php),androidstudio作为我的android。

ulydmbyx

ulydmbyx1#

您应该改装:http://square.github.io/retrofit/ 或快速android网络:https://github.com/amitshekhariitbhu/fast-android-networking 或android异步http:http://loopj.com/android-async-http/
若要发布,请将数据获取到服务器并进行调试。

相关问题