温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Android Studio如何连接SQLite数据库?

发布时间:2020-06-23 15:29:47 来源:亿速云 阅读:1351 作者:清晨 栏目:移动开发

不懂Android Studio如何连接SQLite数据库??其实想解决这个问题也不难,下面让小编带着大家一起学习怎么去解决,希望大家阅读完这篇文章后大所收获。

1、先看一下项目目录:

Android Studio如何连接SQLite数据库?

2、新建一个AS项目,创建如上图所示的目录结构,然后添加内容:

(1)修改添加布局文件:

activity_main.xml:

<&#63;xml version="1.0" encoding="utf-8"&#63;>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  tools:context=".LoginActivity">

<LinearLayout
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical">
  <TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:gravity="center"
    android:text="欢迎进入登录界面!"
    android:textSize="30dp"
    android:textStyle="bold" />

  <TableLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:stretchColumns="1" >

    <TableRow>

      <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="用户名:" />

      <EditText
        android:id="@+id/username"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="请输入用户名!!!" />
    </TableRow>

    <TableRow>

      <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="密码:" />

      <EditText
        android:id="@+id/password"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="请输入密码!!!" />
    </TableRow>

    <TableRow>

      <TextView />

      <LinearLayout>

        <Button
          android:id="@+id/login"
          android:layout_width="100dp"
          android:layout_height="wrap_content"
          android:text="登录" />

        <Button
          android:id="@+id/register"
          android:layout_width="100dp"
          android:layout_height="wrap_content"
          android:text="注册" />
      </LinearLayout>
    </TableRow>
  </TableLayout>
</LinearLayout>
</android.support.constraint.ConstraintLayout>

activity_register.xml:

<&#63;xml version="1.0" encoding="utf-8"&#63;>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  tools:context=".RegisterActivity">
<LinearLayout
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical">
  <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:gravity="center"
    android:text="欢迎进入注册界面!"
    android:textSize="30dp"
    android:textStyle="bold" />

  <TableLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:stretchColumns="1" >

    <TableRow >

      <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="用户名:" />

      <EditText
        android:id="@+id/usernameRegister"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="请输入用户名!!!" />
    </TableRow>

    <TableRow >

      <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="密码:" />

      <EditText
        android:id="@+id/passwordRegister"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="请输入密码!!!" />
    </TableRow>

    <TableRow >

      <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="年龄:" />

      <EditText
        android:id="@+id/ageRegister"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="请输入年龄!!!" />
    </TableRow>

    <TableRow >

      <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="性别:"
        android:textSize="20dp" />

      <RadioGroup
        android:id="@+id/sexRegister"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:checkedButton="@+id/woman"
        android:orientation="horizontal" >

        <RadioButton
          android:id="@+id/nan"
          android:text="男"
          android:layout_height="wrap_content"
          android:layout_width="wrap_content" />

        <RadioButton
          android:id="@id/woman"
          android:text="女"
          android:layout_height="wrap_content"
          android:layout_width="wrap_content"/>
      </RadioGroup>
    </TableRow>

    <TableRow >

      <TextView />

      <LinearLayout >
        <Button
          android:id="@+id/Register"
          android:layout_width="150dp"
          android:layout_height="wrap_content"
          android:text="注册" />
      </LinearLayout>
    </TableRow>
  </TableLayout>

</LinearLayout>
</android.support.constraint.ConstraintLayout>

(2)在service包DatabaseHelper中添加链接AS自带数据库以及创建表的语句:

package com.example.sqlitelogin.service;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper {
	static String name="user.db";
	static int dbVersion=1;
	public DatabaseHelper(Context context) {
		super(context, name, null, dbVersion);
	}

	public void onCreate(SQLiteDatabase db) {
		String sql="create table user(id integer primary key autoincrement,username varchar(20),password varchar(20),age integer,sex varchar(2))";
		db.execSQL(sql);
	}
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

	}

}

(3)在service包UserService中用sql语句写登录注册功能的实现:

package com.example.sqlitelogin.service;

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

import com.example.sqlitelogin.User;


public class UserService {
	private DatabaseHelper dbHelper;
	public UserService(Context context){
		dbHelper=new DatabaseHelper(context);
	}

	public boolean login(String username,String password){
		SQLiteDatabase sdb=dbHelper.getReadableDatabase();
		String sql="select * from user where username=&#63; and password=&#63;";
		Cursor cursor=sdb.rawQuery(sql, new String[]{username,password});		
		if(cursor.moveToFirst()==true){
			cursor.close();
			return true;
		}
		return false;
	}
	public boolean register(User user){
		SQLiteDatabase sdb=dbHelper.getReadableDatabase();
		String sql="insert into user(username,password,age,sex) values(&#63;,&#63;,&#63;,&#63;)";
		Object obj[]={user.getUsername(),user.getPassword(),user.getAge(),user.getSex()};
		sdb.execSQL(sql, obj);	
		return true;
	}
}

(4)在User文件中声明要用到的表列名的变量,并对其添加get&&set方法:

package com.example.sqlitelogin;

import java.io.Serializable;

public class User implements Serializable{
  private int id;
  private String username;
  private String password;
  private int age;
  private String sex;
  public User() {
    super();
    // TODO Auto-generated constructor stub
  }
  public User(String username, String password, int age, String sex) {
    super();
    this.username = username;
    this.password = password;
    this.age = age;
    this.sex = sex;
  }
  public int getId() {
    return id;
  }
  public void setId(int id) {
    this.id = id;
  }
  public String getUsername() {
    return username;
  }
  public void setUsername(String username) {
    this.username = username;
  }
  public String getPassword() {
    return password;
  }
  public void setPassword(String password) {
    this.password = password;
  }
  public int getAge() {
    return age;
  }
  public void setAge(int age) {
    this.age = age;
  }
  public String getSex() {
    return sex;
  }
  public void setSex(String sex) {
    this.sex = sex;
  }
  @Override
  public String toString() {
    return "User [id=" + id + ", username=" + username + ", password="
        + password + ", age=" + age + ", sex=" + sex + "]";
  }

}

(5)为注册功能添加activity组件:

package com.example.sqlitelogin;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.example.sqlitelogin.service.UserService;

public class RegisterActivity extends AppCompatActivity {

  EditText username;
  EditText password;
  EditText age;
  RadioGroup sex;
  Button register;
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);
    findViews();
    register.setOnClickListener(new View.OnClickListener() {
      public void onClick(View v) {
        String name=username.getText().toString().trim();
        String pass=password.getText().toString().trim();
        String agestr=age.getText().toString().trim();
        String sexstr=((RadioButton)RegisterActivity.this.findViewById(sex.getCheckedRadioButtonId())).getText().toString();
        Log.i("TAG",name+"_"+pass+"_"+agestr+"_"+sexstr);
        UserService uService=new UserService(RegisterActivity.this);
        User user=new User();
        user.setUsername(name);
        user.setPassword(pass);
        user.setAge(Integer.parseInt(agestr));
        user.setSex(sexstr);
        uService.register(user);
        Toast.makeText(RegisterActivity.this, "注册成功", Toast.LENGTH_LONG).show();
      }
    });
  }
  private void findViews() {
    username=(EditText) findViewById(R.id.usernameRegister);
    password=(EditText) findViewById(R.id.passwordRegister);
    age=(EditText) findViewById(R.id.ageRegister);
    sex=(RadioGroup) findViewById(R.id.sexRegister);
    register=(Button) findViewById(R.id.Register);
  }

}

(6)为登录功能添加activity组件:

package com.example.sqlitelogin;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.sqlitelogin.service.UserService;

public class LoginActivity extends AppCompatActivity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);//即activity_login.xml
    findViews();
  }
  private EditText username;
  private EditText password;
  private Button login;
  private Button register;

  private void findViews() {
    username=(EditText) findViewById(R.id.username);
    password=(EditText) findViewById(R.id.password);
    login=(Button) findViewById(R.id.login);
    register=(Button) findViewById(R.id.register);

    login.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        String name=username.getText().toString();
        System.out.println(name);
        String pass=password.getText().toString();
        System.out.println(pass);
        
        Log.i("TAG",name+"_"+pass);
        UserService uService=new UserService(LoginActivity.this);
        boolean flag=uService.login(name, pass);

        if(flag){
          Log.i("TAG","登录成功");
          Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_LONG).show();
          Intent intent = new Intent(LoginActivity.this,RegisterActivity.class);
          startActivity(intent);
        }else{
          Log.i("TAG","登录失败");
          Toast.makeText(LoginActivity.this, "登录失败", Toast.LENGTH_LONG).show();
        }
      }
    });
    register.setOnClickListener(new View.OnClickListener() {
      public void onClick(View v) {
        Intent intent=new Intent(LoginActivity.this,RegisterActivity.class);
        startActivity(intent);
      }
    });
  }
}

3、Androidmanifest.xml清单文件中,程序运行必备的内容一般都已经自动完成添加了。也可以进行修改:

<&#63;xml version="1.0" encoding="utf-8"&#63;>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.example.sqlitelogin">


  <application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".RegisterActivity">
      <!--<intent-filter>-->
        <!--<action android:name="android.intent.action.MAIN" />-->

        <!--<category android:name="android.intent.category.LAUNCHER" />-->
      <!--</intent-filter>-->
    </activity>

    <activity android:name=".LoginActivity">
      <intent-filter>
        <action android:name="android.intent.action.MAIN"/>
        <category android:name="android.intent.category.LAUNCHER"/>
      </intent-filter>
    </activity>
    <!--<uses-library android:name="android.test.runner"/>-->
  </application>

</manifest>

4、在模拟器或者真机运行程序,即可!一个连接数据库的登录注册功能已经实现,效果如下:

Android Studio如何连接SQLite数据库?

感谢你能够认真阅读完这篇文章,希望小编分享Android Studio如何连接SQLite数据库?内容对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,遇到问题就找亿速云,详细的解决方法等着你来学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI