java - Android限制一个用户的注册

标签 java android sqlite limit

我开发了一个 android 应用程序......这是一个应用程序首页......它有两个按钮......注册和登录..当用户第一次输入时他需要注册并且当注册被按下时注册进程将开始...用户必须提供用户名、密码和手机号码..一旦他提供所有这些,将生成密码并将发送到手机号码,前提是用户必须输入与用户名一起收到的密码和密码注册...一旦他得到注册..他可以用用户名和密码登录。 所有这些部分工作正常......我的要求是限制仅注册 1 个用户名......所以对于一次下载允许一个用户名......在一次注册后必须停用注册选项......所以我必须为此..我正在给出代码..下面...

主要 Activity

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;

public class MainActivity extends Activity {


     Button btnSignIn,btnSignUp;
    LoginDataBaseAdapter loginDataBaseAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);



        loginDataBaseAdapter=new LoginDataBaseAdapter(this);
        loginDataBaseAdapter=loginDataBaseAdapter.open();


        btnSignIn=(Button)findViewById(R.id.buttonSignIn);
        btnSignUp=(Button)findViewById(R.id.buttonSignUP);



        btnSignUp.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                Intent intentSignUP=new Intent(getApplicationContext(),SignUPActivity.class);
                startActivity(intentSignUP);

            }
        });
    }

    public void signIn(View V)
    {
         final Dialog dialog = new Dialog(MainActivity.this);
         dialog.setContentView(R.layout.login);
         dialog.setTitle("Login");

         // get the References of views
         final  EditText editTextUserName=(EditText)dialog.findViewById(R.id.editTextUserNameToLogin);
         final  EditText editTextPassword=(EditText)dialog.findViewById(R.id.editTextPasswordToLogin);
         final  EditText editTextMobileNumber = (EditText)dialog.findViewById(R.id.editText1);


         Button btnSignIn=(Button)dialog.findViewById(R.id.buttonSignIn);


         btnSignIn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                String userName=editTextUserName.getText().toString();
                String password=editTextPassword.getText().toString();
                String mobileNumber = editTextMobileNumber.getText().toString();

                // fetch the Password form database for respective user name
                String storedPassword=loginDataBaseAdapter.getSinlgeEntry(userName);



                String sd = getIntent().getStringExtra("number"); 




                // check if the Stored password matches with  Password entered by user
                if(password.equals(storedPassword) && (mobileNumber.equals(sd))) 
                {
                    Toast.makeText(MainActivity.this, "Congrats: Login Successfull", Toast.LENGTH_LONG).show();
                    dialog.dismiss();
                }
                else
                {
                    Toast.makeText(MainActivity.this, "User Name or Password does not match", Toast.LENGTH_LONG).show();
                }

            }
        });


         dialog.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // Close The Database
        loginDataBaseAdapter.close();
}
}

注册 Activity

import java.util.Random;
import java.util.StringTokenizer;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SignUPActivity extends Activity

{
    EditText editTextUserName,editTextPassword,editTextConfirmPassword, editMobileNumber;
    Button btnCreateAccount;


    Random r = new Random();
    int number =r.nextInt(9999 - 1000) + 1000;



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

        // get Instance  of Database Adapter
        loginDataBaseAdapter=new LoginDataBaseAdapter(this);
        loginDataBaseAdapter=loginDataBaseAdapter.open();

        // Get References of Views


        editTextUserName=(EditText)findViewById(R.id.editTextUserName);
        editTextPassword=(EditText)findViewById(R.id.editTextPassword);
        editTextConfirmPassword=(EditText)findViewById(R.id.editTextConfirmPassword);
        editMobileNumber = (EditText)findViewById(R.id.mobileNumber);




        btnCreateAccount=(Button)findViewById(R.id.buttonCreateAccount);
        btnCreateAccount.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub



            String userName=editTextUserName.getText().toString();
            String password=editTextPassword.getText().toString();
            String confirmPassword=editTextConfirmPassword.getText().toString();

            String phoneNo = editMobileNumber.getText().toString();
            String sms = Integer.toString(number);


            Intent intent = new Intent(SignUPActivity.this, MainActivity.class);

            intent.putExtra("number", sms + "");
            startActivity(intent);



            StringTokenizer st=new StringTokenizer(phoneNo,",");
            while (st.hasMoreElements())

            {

                String tempMobileNumber = (String)st.nextElement();
                if(tempMobileNumber.length()>0 && sms.trim().length()>0) {
                    sendSMS(tempMobileNumber, sms);

                }


                else 

                {

                    Toast.makeText(getBaseContext(), 
                            "Please enter both phone number and message.", 
                            Toast.LENGTH_SHORT).show();
                }

            }








            // check if any of the fields are vacant
            if(userName.equals("")||password.equals("")||confirmPassword.equals(""))
            {
                    Toast.makeText(getApplicationContext(), "Field Vaccant", Toast.LENGTH_LONG).show();
                    return;
            }
            // check if both password matches
            if(!password.equals(confirmPassword))
            {
                Toast.makeText(getApplicationContext(), "Password does not match", Toast.LENGTH_LONG).show();
                return;
            }
            else
            {
                // Save the Data in Database
                loginDataBaseAdapter.insertEntry(userName, password);
                Toast.makeText(getApplicationContext(), "Account Successfully Created and the passcode is sent to the mobile number you provided. ", Toast.LENGTH_LONG).show();






            }
        }
    });
}










    private void sendSMS(String phoneNumber, String message)
    {
        String SENT = "SMS_SENT";
        String DELIVERED = "SMS_DELIVERED";

        PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
            new Intent(SENT), 0);

        PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
            new Intent(DELIVERED), 0);

      //---when the SMS has been sent---
        registerReceiver(new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode())
                {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "SMS sent", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                        Toast.makeText(getBaseContext(), "Generic failure", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NO_SERVICE:
                        Toast.makeText(getBaseContext(), "No service", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NULL_PDU:
                        Toast.makeText(getBaseContext(), "Null PDU", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_RADIO_OFF:
                        Toast.makeText(getBaseContext(), "Radio off", 
                                Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        },new IntentFilter(SENT));

        //---when the SMS has been delivered---
        registerReceiver(new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode())
                {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "SMS delivered", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case Activity.RESULT_CANCELED:
                        Toast.makeText(getBaseContext(), "SMS not delivered", 
                                Toast.LENGTH_SHORT).show();
                        break;                        
                }
            }
        }, new IntentFilter(DELIVERED));        

        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);       


    }









    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();

        loginDataBaseAdapter.close();
    }



}

登录数据库适配器.java

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class LoginDataBaseAdapter {

    static final String DATABASE_NAME = "login.db";
    static final int DATABASE_VERSION = 1;
    public static final int NAME_COLUMN = 1;
    // TODO: Create public field for each column in your table.
    // SQL Statement to create a new database.
    static final String DATABASE_CREATE = "create table "+"LOGIN"+
                                 "( " +"ID"+" integer primary key autoincrement,"+ "USERNAME  text,PASSWORD text); ";
    // Variable to hold the database instance
    public  SQLiteDatabase db;
    // Context of the application using the database.
    private final Context context;
    // Database open/upgrade helper
    private DataBaseHelper dbHelper;
    public  LoginDataBaseAdapter(Context _context) 
    {
        context = _context;
        dbHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
    public  LoginDataBaseAdapter open() throws SQLException 
    {
        db = dbHelper.getWritableDatabase();
        return this;
    }
    public void close() 
    {
        db.close();
    }

    public  SQLiteDatabase getDatabaseInstance()
    {
        return db;
    }

    public void insertEntry(String userName,String password)
    {
       ContentValues newValues = new ContentValues();
        // Assign values for each row.
        newValues.put("USERNAME", userName);
        newValues.put("PASSWORD",password);

        // Insert the row into your table
        db.insert("LOGIN", null, newValues);
        ///Toast.makeText(context, "Reminder Is Successfully Saved", Toast.LENGTH_LONG).show();
    }
    public int deleteEntry(String UserName)
    {
        //String id=String.valueOf(ID);
        String where="USERNAME=?";
        int numberOFEntriesDeleted= db.delete("LOGIN", where, new String[]{UserName}) ;
       // Toast.makeText(context, "Number for Entry Deleted Successfully : "+numberOFEntriesDeleted, Toast.LENGTH_LONG).show();
        return numberOFEntriesDeleted;
    }    
    public String getSinlgeEntry(String userName)
    {
        Cursor cursor=db.query("LOGIN", null, " USERNAME=?", new String[]{userName}, null, null, null);
        if(cursor.getCount()<1) // UserName Not Exist
        {
            cursor.close();
            return "NOT EXIST";
        }
        cursor.moveToFirst();
        String password= cursor.getString(cursor.getColumnIndex("PASSWORD"));
        cursor.close();
        return password;                
    }
    public void  updateEntry(String userName,String password)
    {
        // Define the updated row content.
        ContentValues updatedValues = new ContentValues();
        // Assign values for each row.
        updatedValues.put("USERNAME", userName);
        updatedValues.put("PASSWORD",password);

        String where="USERNAME = ?";
        db.update("LOGIN",updatedValues, where, new String[]{userName});               
    }        

}

最佳答案

为了简单

只需获取LOGIN 表的计数。如果返回 1,则隐藏 SignUp 按钮,否则显示 SignUP 按钮。使用以下代码行获取表的总数。

Activity 中

 if(loginDataBaseAdapter.getUsercount()==1){
          btnSignUp.setVisibility(View.INVISIBLE);
 }

在数据库中

   public long getUsercount() { 
        return DatabaseUtils.queryNumEntries(db, "LOGIN");
    } 

它应该可以工作。

关于java - Android限制一个用户的注册,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19152998/

相关文章:

java - 如何修复 '' 创建名称在类路径资源中定义的 bean 时出错”?

android - 监听WIFI状态

java - SQLite数据库创建openOrCreateDatabase,什么是应用程序数据库的正确路径

android - 如何有效地执行嵌套 SQL 查询

Android:在显示之前对Cursor中的SQL返回值进行算术

java - JConnect 错误代码列表是什么?

java - 部署客户端/服务器 Java 应用程序

java - 如何隐藏/删除/避免系统应用程序(非 UI)在 Android 应用程序抽屉中列出/显示?

android - 在 LinearLayout 中设置 View 的属性

java - 在 Axiom Safe Request 中使用数据库资源