Android calls existing sqlite database login account

I am going to create a login account using the existing SQLite database. In this case, I have to create a database myself and then move the database. I have seen many methods to realize the login registration function by first creating the database and then opening the database and then querying. However, our project requires only logging in. Not registering, and creating the database first and then opening the database will show the account and password, which is too unprofessional. In order to show my professional level, I had to do it myself.

The first problem encountered is how to move the database created by sqlite studio (a sqlite visualization software, there are many tutorials online) to the project. First, you must move the created database to the res/raw folder, and then create a MyDatabaseHelper class, in which the File class is used to implement file movement. The detailed process is as shown in the following code:

 

public class MyDatabaseHelper {
    private final int BUFFER_SIZE = 400000;
    public static final String DB_NAME = "mydatabase.db"; //保存的数据库文件名
    public static final String PACKAGE_NAME = "com.example.expert6";//包名
    public static final String DB_PATH = "/data"
            + Environment.getDataDirectory().getAbsolutePath() + "/"
            + PACKAGE_NAME + "/databases";  //存放数据库的位置
    private SQLiteDatabase database;
    private Context context;
    MyDatabaseHelper(Context context){
        this.context = context;
    }

    public void openDatabase() {
        File dFile=new File(DB_PATH);//判断路径是否存在,不存在则创建路径
        if (!dFile.exists()) {
            dFile.mkdir();
        }
        this.database = this.openDatabase(DB_PATH + "/" + DB_NAME);
    }
    private SQLiteDatabase openDatabase(String dbfile) {
        try {
            if (!(new File(dbfile).exists())) {
                InputStream is = this.context.getResources().openRawResource(
                        R.raw.mydatabase); //欲导入的数据库
                FileOutputStream fos = new FileOutputStream(dbfile);
                byte[] buffer = new byte[BUFFER_SIZE];
                int count = 0;
                while ((count = is.read(buffer)) > 0) {
                    fos.write(buffer, 0, count);
                }
                fos.close();
                is.close();
            }
            SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbfile,
                    null);
            return db;
        }catch (FileNotFoundException e) {
            Log.e("Database", "File not found");
            e.printStackTrace();
        } catch (IOException e) {
            Log.e("Database", "IO exception");
            e.printStackTrace();
        }
        return null;
    }

    public String QuerySQL(String str1,String str2) {

        String result = "";
        try{
            Cursor cursor = database.rawQuery("select username from users  where passwd=? " +
                    "and  username=? ", new String[]{str2,str1 });
            if (cursor.moveToNext())
            {
                result= "1" ;
            }
            cursor.close();
            database.close();

        }
        catch (SQLException e)
        {
            e.printStackTrace();
            result += "查询数据异常!" + e.getMessage();
        }
        return result;
    }
    public void closeDatabase()
    {
        this.database.close();
    }
}

 

 This is only the first step. You must also create a MainActivity class to implement the function of logging in to the account. First instantiate the MyDatabaseHelper object in OnCreate and then call databaseHelper.openDatabase() in this class to open the database. Finally, the click event of the first button is triggered. The main program code is as follows:

/**
 * 主Activity为控制类,用于控制界面的显示
 */
public class MainActivity extends Activity {
    private static final String TAG = "LifeCycleActivity";
    private Context context = this;
    private int param = 1;
    MyDatabaseHelper databaseHelper;
    private EditText username;  //接收用户输入的用户名
    private EditText passwd;    //接收用户输入的密码
    //Activity创建时被调用
    @Override
    public void onCreate(Bundle savedInstanceState) {
        databaseHelper=new MyDatabaseHelper(this);//实例化MyDatabaseHelper
        databaseHelper.openDatabase();//打开数据库
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        username = (EditText) findViewById(R.id.username);
        passwd = (EditText) findViewById(R.id.passwd);
        Button btn = (Button) findViewById(R.id.but_login);
        Button btn1 = (Button) findViewById(R.id.but_clear);
        SQLiteStudioService.instance().start(this);
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                username.setText("");
                passwd.setText("");
            }
        });
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, MassegeActivity.class);
                //绑定数据
                String str1=username.getText().toString();//获取帐号
                String str2=passwd.getText().toString();//获取密码

                String ret = databaseHelper.QuerySQL(str1,str2);
                if(ret.equals("1")) {
                    startActivity(intent);
                    finish();
                    //下面跳转问卷界面
                }
                else {
                    Toast.makeText(MainActivity.this,"用户名或密码错误",
                            Toast.LENGTH_SHORT).show();//事件触发,显示登录失败
                }
            }
        });

    }

    protected void onDestroy() {
        // TODO Auto-generated method stub
        SQLiteStudioService.instance().stop();
        super.onDestroy();
    }

}

If you copy directly online, first create the database and then open it, and then call MyDatabaseHelper in the main program, an QuerySQL方法empty object will appear. The main reason is that the object is confused and the object is called randomly. There is no reference to the method of creating the database at all. It is just instantiation. Of course, if the database is not opened, there will be empty objects. I have been stuck here. I always thought that as long as I copied the code, it would be fine. It seems that I need to analyze it more in the future.

I spent a lot of time on this, so I recorded it today to remind myself, I hope it will be helpful to you.

If you need the source code, you can download it yourself.

Source code

 

Guess you like

Origin blog.csdn.net/qq_45098495/article/details/107074461