SQLite is a opensource SQL database that stores data to a text file on a device. Android comes in with built in SQLite database implementation.
SQLite supports all the relational database features. In order to access this database, you don't need to establish any kind of connections for it like JDBC,ODBC e.t.c
Database - Package
The main package is android.database.sqlite that contains the classes to manage your own databases
Database - Creation
In order to create a database you just need to call this method openOrCreateDatabase with your database name and mode as a parameter. It returns an instance of SQLite database which you have to receive in your own object.Its syntax is given below
Home The application will consist of an activity and a database handler class (MyDBHandler class). The database handler will be a subclass of SQLiteOpenHelper and will provide an abstract layer between the underlying SQLite database and the activity class. A third class (Student class) will need to be implemented to hold the database entry data as it is passed between the activity and the handler.public class Home extends AppCompatActivity { private Button login, reg;
private EditText uname, pass;
private DBHelper dbHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
dbHelper = new DBHelper(this);
login = findViewById(R.id.btnLogin);
reg = findViewById(R.id.btnReg);
uname = findViewById(R.id.uname);
pass = findViewById(R.id.pass);
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ArrayList<User> list = dbHelper.readAllInfo();
for (User u : list){
if(u.getUserName().equals(uname.getText().toString())){
if(u.getPassword().equals(pass.getText().toString())){
Intent intent = new Intent(Home.this, ProfileManagement.class);
intent.putExtra("id", u.getUserId());
startActivity(intent); }
}
}
}
});
reg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String user = uname.getText().toString();
String passwrd = pass.getText().toString();
dbHelper.addInfo(user, passwrd);
Toast.makeText(Home.this, "User Registered!", Toast.LENGTH_SHORT).show(); }
}); }
}
Database - Fetching
We can retrieve anything from database using an object of the Cursor class. We will call a method of this class called rawQuery and it will return a resultset with the cursor pointing to the table. We can move the cursor forward and retrieve the data.
Cursor resultSet = mydatbase.rawQuery("Select * from TutorialsPoint",null); resultSet.moveToFirst(); String username = resultSet.getString(0); String password = resultSet.getString(1);
There are other functions available in the Cursor class that allows us to effectively retrieve the data. That includes DB helper
public class DBHelper extends SQLiteOpenHelper { private final static String DATABASE_NAME = "UserInfo.db"; public DBHelper(Context context) { super(context, DATABASE_NAME, null, 1); } @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { String CREATE_TABLE = "CREATE TABLE " + UserProfile.Users.TABLE_NAME + " (" + UserProfile.Users._ID + " INTEGER PRIMARY KEY," + UserProfile.Users.COLUMN_USERNAME + " TEXT," + UserProfile.Users.COLUMN_DOB + " TEXT," + UserProfile.Users.COLUMN_GENDER + " TEXT," + UserProfile.Users.COLUMN_PASSWORD + " TEXT )"; sqLiteDatabase.execSQL(CREATE_TABLE); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { } public long addInfo(String username, String password){ SQLiteDatabase sqLiteDatabase = getWritableDatabase();ContentValues contentValues = new ContentValues();contentValues.put(UserProfile.Users.COLUMN_USERNAME, username);contentValues.put(UserProfile.Users.COLUMN_PASSWORD, password); long rowId = sqLiteDatabase.insert(UserProfile.Users.TABLE_NAME, null, contentValues); return rowId;}
public int updateInfo(String userId, String userName, String password, String dob,String gender){ SQLiteDatabase sqLiteDatabase = getWritableDatabase(); ContentValues values = new ContentValues();values.put(UserProfile.Users.COLUMN_USERNAME, userName);values.put(UserProfile.Users.COLUMN_PASSWORD, password);values.put(UserProfile.Users.COLUMN_GENDER, gender);values.put(UserProfile.Users.COLUMN_DOB, dob);String selection = UserProfile.Users._ID + " = ?";String args[] = {userId};int count = sqLiteDatabase.update(UserProfile.Users.TABLE_NAME, values, selection, args); return count;} public ArrayList readAllInfo(){ SQLiteDatabase sqLiteDatabase = getReadableDatabase(); String[] projection = { UserProfile.Users._ID,UserProfile.Users.COLUMN_USERNAME,UserProfile.Users.COLUMN_DOB,UserProfile.Users.COLUMN_GENDER,
UserProfile.Users.COLUMN_PASSWORD
};
String sortOrder = UserProfile.Users._ID + " DESC"; Cursor cursor = sqLiteDatabase.query( UserProfile.Users.TABLE_NAME, projection,null,null,null,null,sortOrder ); ArrayList<User> list = new ArrayList<>(); if (cursor.getCount() > 0){ while(cursor.moveToNext()){ User newUser = new User(); int id = cursor.getInt(cursor.getColumnIndexOrThrow(UserProfile.Users._ID)); String user = cursor.getString(cursor.getColumnIndexOrThrow(UserProfile.Users.COLUMN_USERNAME)); String date = cursor.getString(cursor.getColumnIndexOrThrow(UserProfile.Users.COLUMN_DOB)); String gen = cursor.getString(cursor.getColumnIndexOrThrow(UserProfile.Users.COLUMN_GENDER)); String pass = cursor.getString(cursor.getColumnIndexOrThrow(UserProfile.Users.COLUMN_PASSWORD)); newUser.setUserId(id+"");
newUser.setUserName(user);
newUser.setDateOfBirth(date);
newUser.setGender(gen);
newUser.setPassword(pass); list.add(newUser);
} } return list;
} public ArrayList readAllInfo(String userId, String userName){ String selection;
String[] args = {""};
if(userId == null){ selection = UserProfile.Users.COLUMN_USERNAME + " LIKE ?";
args[0] = userName;
} else { selection = UserProfile.Users._ID + " = ?";
args[0] = userId;
} SQLiteDatabase sqLiteDatabase = getReadableDatabase(); String[] projection = { UserProfile.Users._ID,
UserProfile.Users.COLUMN_USERNAME,
UserProfile.Users.COLUMN_DOB,
UserProfile.Users.COLUMN_GENDER,
UserProfile.Users.COLUMN_PASSWORD }; String sortOrder = UserProfile.Users._ID + " DESC"; Cursor cursor = sqLiteDatabase.query( UserProfile.Users.TABLE_NAME, projection, selection,args,null,null, sortOrder ); ArrayList<User> list = new ArrayList<>(); if (cursor.getCount() > 0){ while(cursor.moveToNext()){ User newUser = new User(); int id = cursor.getInt(cursor.getColumnIndexOrThrow(UserProfile.Users._ID)); String user = cursor.getString(cursor.getColumnIndexOrThrow(UserProfile.Users.COLUMN_USERNAME)); String date = cursor.getString(cursor.getColumnIndexOrThrow(UserProfile.Users.COLUMN_DOB)); String gen = cursor.getString(cursor.getColumnIndexOrThrow(UserProfile.Users.COLUMN_GENDER)); String pass = cursor.getString(cursor.getColumnIndexOrThrow(UserProfile.Users.COLUMN_PASSWORD)); newUser.setUserId(id+"");
newUser.setUserName(user);newUser.setDateOfBirth(date);
newUser.setGender(gen);
newUser.setPassword(pass);
list.add(newUser);
} } return list; } public int deleteInfo(String username){ SQLiteDatabase sqLiteDatabase = getReadableDatabase(); String selection = UserProfile.Users._ID + " = ?";
String[] args = {username};
int deletedRows = sqLiteDatabase.delete(UserProfile.Users.TABLE_NAME, selection, args); return deletedRows;
} }
n software applications, it is mostly required to save information for some internal use
or off course to provide user to great features depending on the data. And when we talk
about android so SQLite is that default feature which is used as a database and also
used as a local database for any application. This tutorial shows a very simple example
which is to just store important data like Profile Management shops address or contacts using
SQLite Database in the android studio.
public class ProfileManagement extends AppCompatActivity { private Button update;private EditText uname, dob, pass;private RadioButton male, female;private DBHelper dbHelper;private String userId;@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);setContentView(R.layout.activity_profile_management);
dbHelper = new DBHelper(this);Intent intent = getIntent();userId = intent.getStringExtra("id");uname = findViewById(R.id.user);dob = findViewById(R.id.date);pass = findViewById(R.id.word);update = findViewById(R.id.btnUpdate);male = findViewById(R.id.radioMale);female = findViewById(R.id.radioFe);
ArrayList<User> list = dbHelper.readAllInfo(userId, null); for (User u : list){ uname.setText(u.getUserName());pass.setText(u.getPassword());dob.setText(u.getDateOfBirth());if(u.getGender() != null){ if(u.getGender().equals("Male")){ male.setChecked(true);
} else{ female.setChecked(true);
} } } update.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(ProfileManagement.this, EditProfile.class); intent.putExtra("id", userId); startActivity(intent); } }); } }
User First, start with insert, we add a method addShop() which take Shop as a parameter
and map our shop values with table’s column using ContentValues object.
getWritableDatabase is used for creating and/or opening database.
package com.example.prabuddhaabisheka.mock; public class User { private String userId;private String userName;private String dateOfBirth;private String gender;private String password;public User() { } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getDateOfBirth() { return dateOfBirth; } public void setDateOfBirth(String dateOfBirth) { this.dateOfBirth = dateOfBirth; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
User profile Android Studio is the official[7] integrated development environment (IDE) for
Google's Android operating system, built on JetBrains' IntelliJ IDEA software and designed specifically
for Android development.[8] It is available for download on Windows, macOS and Linux based
operating systems.[9][10] It is a replacement for the Eclipse Android Development Tools (ADT) as
primary IDE for native Android application development.
package com.example.prabuddhaabisheka.mock; import android.provider.BaseColumns; public final class UserProfile { private UserProfile() { } public static class Users implements BaseColumns { public final static String TABLE_NAME = "userInfo";public final static String COLUMN_USERNAME = "userName";public final static String COLUMN_PASSWORD = "password";public final static String COLUMN_GENDER = "gender";public final static String COLUMN_DOB = "dateOfBirth";} }
Edit profile Today, Android Studio 3.2 is available for download. Android
Studio 3.2 is the best way for app developers to cut into the latest Android 9 Pierelease
and build the new Android App bundle. Since announcing this update of Android Studio
at Google I/O '18, we have refined and polished 20+ new features and focused our efforts
on improving the quality for this stable release of Android Studio 3.2.
public class EditProfile extends AppCompatActivity { private Button edit,delete,search;private EditText uname, dob, pass;private RadioGroup radioGroup;private RadioButton male, female;private String gender;private DBHelper dbHelper;private String userId;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);setContentView(R.layout.activity_edit_profile);dbHelper = new DBHelper(this);
Intent intent = getIntent();userId = intent.getStringExtra("id");Toast.makeText(EditProfile.this, userId, Toast.LENGTH_SHORT).show();uname = findViewById(R.id.userName);dob = findViewById(R.id.dateOfB);pass = findViewById(R.id.psswrd);edit = findViewById(R.id.btnEdit);delete = findViewById(R.id.btnDelete);search = findViewById(R.id.btnSearch);radioGroup = findViewById(R.id.radio);male = findViewById(R.id.maleR);female = findViewById(R.id.femaleR);
ArrayList<User> list = dbHelper.readAllInfo(userId, null); if(!list.isEmpty()){ for (User u : list){ uname.setText(u.getUserName());pass.setText(u.getPassword());
dob.setText(u.getDateOfBirth());if(u.getGender() != null){ if(u.getGender().equals("Male")){ male.setChecked(true);} else{ female.setChecked(true);} } } } radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup radioGroup, int view) { if(view == R.id.femaleR){ gender = "Female";} else{ gender = "Male";} } }); search.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ArrayList<User> urs = dbHelper.readAllInfo(null, uname.getText().toString()); for (User u : urs){ userId = u.getUserId();uname.setText(u.getUserName());pass.setText(u.getPassword());dob.setText(u.getDateOfBirth());if(u.getGender() != null){ if(u.getGender().equals("Male")){ male.setChecked(true);} else{ female.setChecked(true);} } } } }); edit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String userName = uname.getText().toString();String date = dob.getText().toString();String pwrd = pass.getText().toString();
if(female.isChecked()){ gender = "Female";} else{ gender = "Male";} int count = dbHelper.updateInfo(userId, userName, pwrd, date, gender); if(count > 0){ Toast.makeText(EditProfile.this, "Updated!", Toast.LENGTH_SHORT).show(); } else{ Toast.makeText(EditProfile.this, "Something went wrong!", Toast.LENGTH_SHORT).show(); } } }); delete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { int count = dbHelper.deleteInfo(userId); if(count > 0){ Toast.makeText(EditProfile.this, "Deleted!", Toast.LENGTH_SHORT).show(); } else{Toast.makeText(EditProfile.this, "Something went wrong!", Toast.LENGTH_SHORT).show(); } } }); } }
insert - return value = long
if long = -1 ---> false
else ----> true
db.insert(tablename,null,contentValues)
Update - return value = long
if long = -1 ---> false
else ----> true
db.update(tablename,contentValue,_ID+"=?",new String[]{id});
Delete - return value = integer (no of rows deleted)
db.delete(tablename,_ID+"=?",new String[]{id});
0 comments:
Post a Comment
Thank you for reading this article. Please share this information with your friends. Comment any suggestions on this comment box.