简体   繁体   English

在android中创建用户时检查用户名是否可用

[英]Check for username availability when creating users in android

I am creating my first android which will take data from a signup form and send it to a php backend. 我正在创建我的第一个android,它将从注册表单获取数据并将其发送到php后端。

The php backend will take the data and save in a database and give a jason encoded message telling if it is success or not. php后端将获取数据并将其保存在数据库中,并给出一个jason编码消息,告诉您是否成功。

Now I want to eliminate the possibility of dupilicate usernames so when the android app sends data to the php backend I will first check and if it is duplicate I will throw an error message like this 现在,我想消除重复用户名的可能性,因此当android应用将数据发送到php后端时,我将首先检查,如果重复则将抛出类似这样的错误消息

$response["error"] = true;
$response["message"] = "Username Already taken";
echoRespnse(400,$response);

On Success the backend will send something like this 成功后,后端将发送类似的内容

$response["error"] = false;
$response["message"] = "Successfuly Registered";
echoRespnse(201,$response);

How do I enable the android app to read this info and understand if the user was created or an error occured. 如何启用android应用程序以读取此信息并了解是否已创建用户或发生错误。

My current Android signup.java code looks like this 我当前的Android signup.java代码如下所示

public void post() throws UnsupportedEncodingException
    {
        // Get user defined values
        uname = username.getText().toString();
        email   = mail.getText().toString();
        password   = pass.getText().toString();
        confirmpass   = cpass.getText().toString();
        phone = phn.getText().toString();

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://www.rgbpallete.in/led/api/signup");
        if (password.equals(confirmpass)) {
            try {
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
                nameValuePairs.add(new BasicNameValuePair("uname", uname));
                nameValuePairs.add(new BasicNameValuePair("pass", password));
                nameValuePairs.add(new BasicNameValuePair("email", email));
                nameValuePairs.add(new BasicNameValuePair("phone", phone));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                httpclient.execute(httppost);
                //Code to check if user was successfully created
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        else
        {
            Toast.makeText(getBaseContext(), "Password mismatch", Toast.LENGTH_SHORT).show();
            //Reset password fields
            pass.setText("");
            cpass.setText("");
        }

    }

You could make your "error" an int instead of a boolean, and have your php backend return specific error codes. 您可以将“错误”设置为int而不是布尔值,并让您的php后端返回特定的错误代码。 This would allow your android application to understand the specific error. 这将允许您的android应用程序了解具体错误。 Without this kind of modification, checking the value of message for a specific string is another option. 如果不进行这种修改,则检查特定字符串的message值是另一种选择。

For example, you could return 0 if there was no error, 1 if the username was already taken, 2 if .. etc. 例如,如果没有错误,则可以返回0,如果已经使用了用户名,则返回1,如果..等,则返回2。

I think you want help to get and read the JSON data provided by your service, right? 我认为您需要帮助来获取和读取服务提供的JSON数据,对吗? In your SignUp Activity create an AsyncTask because you can not perform this on the main thread. 在您的注册活动中创建一个AsyncTask,因为您无法在主线程上执行此操作。

private class DownloadOperation extends AsyncTask<Void, Void, String> {
    String uname = "";
    String email   = "";
    String password   = "";
    String confirmpass   = "";
    String phone = "";

     @Override
protected void onPreExecute() {
    super.onPreExecute();
    // Get user defined values
    uname = username.getText().toString();
    email   = mail.getText().toString();
    password   = pass.getText().toString();
    confirmpass   = cpass.getText().toString();
    phone = phn.getText().toString();
}

@Override
protected String doInBackground(Void... params) {
        String response = "";
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://www.rgbpallete.in/led/api/signup");
        HttpEntity httpEntity = null;
        HttpResponse httpResponse = null;
        try {
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
            nameValuePairs.add(new BasicNameValuePair("uname", uname));
            nameValuePairs.add(new BasicNameValuePair("pass", password));
            nameValuePairs.add(new BasicNameValuePair("email", email));
            nameValuePairs.add(new BasicNameValuePair("phone", phone));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            httpclient.execute(httppost);
            httpResponse = httpClient.execute(httpPost);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            } catch (IOException e) {
            e.printStackTrace();
        }
        httpEntity = httpResponse.getEntity();
        response = EntityUtils.toString(httpEntity);
        return response;
}

@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);
    Log.d("tag", "Result:\n" + result);
}}

And then call 然后打电话

// Calling async task to get json
new DownloadOperation().execute();

And you will see the json string printed on your Console :) 然后您将看到在控制台上打印的json字符串:)

To get an JSONObject using the response String: 要使用响应字符串获取JSONObject:

JSONObject jsonObj = new JSONObject(STRING);

Hope that helps. 希望能有所帮助。

BEFORE registering the user and inserting into database ,check the query for username in database..and if user name found then encode json value as error 在注册用户并插入数据库之前,请在数据库中检查查询的用户名。如果找到了用户名,则将json值编码为错误

$query=mysql_query("select id from yourtable where username ='$username'"); $ query = mysql_query(“从您的表中选择ID,其中username ='$ username'”); If(mysql_numnum_rows($query)>0) 如果(mysql_numnum_rows($查询)> 0)

 // example for response //responses from server for success response["success"]=1; response["message"]='No error code' //responses from server for duplicate username response["success"]==0 response["message"]='Username exists'; // java code // after getting string from server parse in into json object JSONObject jsonObj = new JSONObject(STRING); int success = jsonObj.getInt("success"); message = jsonObj.getString("message"); if (success == 1) { // register successfully } else { // username already exist } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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