android中的Edittext null值验证

时间:2016-07-26 08:37:42

标签: android

您好我想在登录界面进行验证。我有两个edittext,当它们的某些空值比代码显示错误时请在登录按钮上输入用户名和密码点击。

这是我的第一堂课activity_login.java

package com.ad_blinds.ad_bliends.ad_bliends;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

/**
 * Created by jignesh on 20-07-2016.
 */
public class activity_login extends AppCompatActivity implements View.OnClickListener {

    public static final String USER_NAME ="";
    public static final String PASSWORD="";
    private static final String LOGIN_URL = "http://www.techonlab.com/AdMobileApp/login.php";

    private EditText editTextUserName;
    private EditText editTextPassword;

    private Button buttonLogin;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        editTextUserName = (EditText) findViewById(R.id.Username);
        editTextPassword = (EditText) findViewById(R.id.Password);

        buttonLogin = (Button)findViewById(R.id.btnLogin);
        buttonLogin.setOnClickListener(this);

    }


    private void login() {

        String username = editTextUserName.getText().toString().trim();
        String password = editTextPassword.getText().toString().trim();
        userLogin(username, password);

    }

    private void userLogin(String username, String password) {
        class UserLoginClass extends AsyncTask<String, Void, String> {

            ProgressDialog loading;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                    loading = ProgressDialog.show(activity_login.this,"Please Wait",null,true,true);
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                loading.dismiss();
                String jsonValue=s;

                try {
                    JSONObject jsonReplay = new JSONObject(jsonValue);
                    JSONObject userDetail = jsonReplay.getJSONObject("user_details");

                    String USER_ID = userDetail.getString("user_id");
                    String USER_NAME = userDetail.getString("user_name");
                    String SUCCESS = userDetail.getString("Success");

                    if(SUCCESS=="1")
                    {
                        SharedPreferences sp=getSharedPreferences("Login",0);
                        SharedPreferences.Editor Ed=sp.edit();
                        Ed.putString("USER_ID",USER_ID);
                        Ed.putString("USER_NAME",USER_NAME);
                        Ed.putString("LOGIN",SUCCESS);
                        Ed.commit();

                        Toast.makeText(activity_login.this, "Wel-come "+USER_NAME, Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(activity_login.this,activity_home.class);
                        startActivity(intent);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected String doInBackground(String... params) {
                HashMap<String, String> data = new HashMap<>();
                data.put("username", params[0]);
                data.put("password", params[1]);

                RegisterUserClass ruc = new RegisterUserClass();
                String result = ruc.sendPostRequest(LOGIN_URL, data);
                return result;
            }

        }
        UserLoginClass ulc = new UserLoginClass();
        ulc.execute(username,password);
    }


    @Override
    public void onClick(View v) {
        if(v == buttonLogin) {
            login();
        }
    }
}

这是我的第二个名字是regsteruserclass.java

package com.ad_blinds.ad_bliends.ad_bliends;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;

/**
 * Created by Belal on 8/6/2015.
 */
public class RegisterUserClass {

    public String sendPostRequest(String requestURL,
                                  HashMap<String, String> postDataParams) {

        URL url;
        String response = "";
        try {
            url = new URL(requestURL);

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(15000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);


            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(getPostDataString(postDataParams));

            writer.flush();
            writer.close();
            os.close();
            int responseCode=conn.getResponseCode();

            if (responseCode == HttpsURLConnection.HTTP_OK) {
                BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));

              response = br.readLine();
            }
            else {
                response="Error";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return response;
    }

    private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
        StringBuilder result = new StringBuilder();
        boolean first = true;
        for(Map.Entry<String, String> entry : params.entrySet()){
            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
        }

        return result.toString();
    }
}

1 个答案:

答案 0 :(得分:0)

将您的代码更改为以下以显示验证:

private void login() {

    String username = editTextUserName.getText().toString().trim();
    String password = editTextPassword.getText().toString().trim();

   if (username.equals("")) {
        Toast.makeText(this, "Please enter username",             Toast.LENGTH_SHORT).show();
    }
    else if (password.equals("")) {
        Toast.makeText(this, "Please enter password", Toast.LENGTH_SHORT).show();
    }
    else{
    userLogin(username, password);
 }

}