ОК, это объяснит шаблон MVC для базы данных.
Вот класс модели
public class DatabaseModel {
private String rowid;
private String website;
private String usernane;
private String password;
private String question;
private String answer;
private String notes;
public String getRowid() {
return rowid;
}
public void setRowid(String rowid) {
this.rowid = rowid;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public String getUsernane() {
return usernane;
}
public void setUsernane(String usernane) {
this.usernane = usernane;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getAnswer() {
return answer;
}
public void setAnswer(String answer) {
this.answer = answer;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
}
Вот класс помощника, который создает таблицы
public class DBHelper extends SQLiteOpenHelper{
public static final String DB_NAME = THE_PATH + "PassWord.db";
public static final Integer DB_VERSION = 1;
public static final String TABLE_PW = "masterPW";
public static final String Col_IDI = "IDI";
public static final String Col_MPW = "mpw";
public static final String TABLE_INFO = "webINFO";
public static final String Col_ID = "ID";
public static final String Col_WS = "website";
public static final String Col_UN = "username";
public static final String Col_PW = "password";
public static final String Col_SQ = "question";
public static final String Col_SA = "answer";
public static final String Col_NOTES = "notes";
private static final String MAKE_TABLE_PW = "CREATE TABLE IF NOT EXISTS " + TABLE_PW +
"(" + Col_IDI + " INTEGER PRIMARY KEY," + Col_MPW + " TEXT " + ")";
private static final String MAKE_TABLE = "CREATE TABLE IF NOT EXISTS " + TABLE_INFO +
"(" + Col_ID + " INTEGER PRIMARY KEY," + Col_WS + " TEXT, " + Col_UN + " TEXT, " + Col_PW + " TEXT, " + Col_SQ + " TEXT, " + Col_SA + " TEXT, " + Col_NOTES +" TEXT "+ ")";
static SQLiteDatabase db;
public DBHelper(Context context){
super(context,DB_NAME,null,DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL( MAKE_TABLE_PW );
db.execSQL( MAKE_TABLE );
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PW);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_INFO);
onCreate(db);
}
/*All the CODE above is the design for the Database and its Tables */
/*=================================================================*/
/* Code Below are the Helper CRUD Functions */
/*==========================================*/
public String getCol_MPW(){
db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_PW;
Cursor cursor = db.rawQuery(query,null);
if(cursor.moveToFirst()){
str = cursor.getString(cursor.getColumnIndex(Col_MPW));
}
cursor.close();
db.close();
return str;
// This routine called from MainActivity determine's if a
// password has been entered in the db table named "TABLE_PW"
// See onLoad() method in MainActivity
}
/* Update Record in Database*/
public void updateDBRow(String rowid,String website, String username, String password, String question,String answer, String notes){
db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(Col_WS,website);
cv.put(Col_UN,username);
cv.put(Col_PW,password);
cv.put(Col_SQ,question);
cv.put(Col_SA,answer);
cv.put(Col_NOTES,notes);
/*NOTE WHERE THE quotation MARKS ARE */
db.update(TABLE_INFO,cv, Col_ID + " = ?",new String[] { rowid });
db.close();
}
/* Insert into database table named "TABLE_INFO" */
public void insertIntoDB(String website, String username, String password, String question,String answer, String notes){
// 1. get reference to writable DB
db = this.getWritableDatabase();
// 2. create ContentValues to add key "column"/value
ContentValues cv = new ContentValues();
cv.put(Col_WS,website);
cv.put(Col_UN,username);
cv.put(Col_PW,password);
cv.put(Col_SQ,question);
cv.put(Col_SA,answer);
cv.put(Col_NOTES,notes);
// 3. insert
db.insert(TABLE_INFO, null, cv);
// 4. close
db.close();
}
/* Retrieve ALL data from database table named "TABLE_INFO" */
public List<DatabaseModel> getDataFromDB(){
List<DatabaseModel> dbList = new ArrayList<>();
String query = "SELECT * FROM " + TABLE_INFO;
db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query,null);
if (cursor.moveToFirst()){
do {
DatabaseModel model = new DatabaseModel();
model.setRowid(cursor.getString(0));
model.setWebsite(cursor.getString(1));
model.setUsernane(cursor.getString(2));
model.setPassword(cursor.getString(3));
model.setQuestion(cursor.getString(4));
model.setAnswer(cursor.getString(5));
model.setNotes(cursor.getString(6));
dbList.add(model);
}while (cursor.moveToNext());
}
db.close();
cursor.close();
return dbList;
}
/* Delete a record from database table named "TABLE_INFO" */
/* based on the selected records id in Col_ID*/
public void deleteDBRow(String rowid){
db = this.getWritableDatabase();
db.delete(TABLE_INFO, Col_ID + " = ?", new String[] { rowid });
db.close();
}
И Экран, где вы вводите данные
public class DetailsActivity extends AppCompatActivity {
TextView tvDA;
String tORf;
int position;
String str;
Button btnSave, btnDelete, btnUpdate;
EditText etWebSite, etUN, etPW, etSecQuestion, etSecAnswer, etNotes;
ImageView imageTB;
private DBHelper helper;
private SQLiteDatabase db;
private Context context = this;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
Intent intentSP = getIntent();
Bundle bundle = intentSP.getExtras();
tORf = bundle.getString("FROM_LIST_ACTIVITY");
Intent intentN = getIntent();
Bundle extras = intentN.getExtras();
position = extras.getInt("POSITION");
tORf = extras.getString("FROM_LIST_ACTIVITY");
tvDA = findViewById(R.id.tvDA);
btnSave = findViewById(R.id.btnSave);
btnDelete = findViewById(R.id.btnDelete);
btnUpdate = findViewById(R.id.btnUpdate);
etWebSite = findViewById(R.id.etWebSite);
etUN = findViewById(R.id.etUN);
etPW = findViewById(R.id.etPW);
etSecQuestion = findViewById(R.id.etSecQuestion);
etSecAnswer = findViewById(R.id.etSecAnswer);
etNotes = findViewById(R.id.etNotes);
imageTB = findViewById(R.id.imageTB);
addListenerOnButtonSave();
addListenerOnButtonDelete();
addListenerOnButtonUpdate();
addTextChangedListener();
hint_text_listener();
//Works with METHOD TO PERMIT Notes Editing
//==========================================
imageTB.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
etNotes.setEnabled(true);
etNotes.requestFocus();
etNotes.setFocusableInTouchMode(true);
Toast.makeText(DetailsActivity.this, "Now You Can Edit", Toast.LENGTH_LONG).show();
return false;
}
});
if (tORf.equals("true")) {
tvDA.setText("Add New Data");
} else {
tvDA.setText("Detail View");
btnDelete.setVisibility(View.VISIBLE);
btnUpdate.setVisibility(View.VISIBLE);
if(tvDA.getText().toString().equals("Add New Data")){
etNotes.setHint(R.string.hint_edit);
}else{
etNotes.setHint("");
// This IF statement decides if HINT text is shown or NOT
// DO NOT WANT Hint Text with an EDIT of Data
}
}
setTitle("");
// We do not want a title on DetailActivity toolbar this removes the title
// Title is set in the ABOVE if statements based on what was selected on List View
//=================================================================================
Toolbar topToolBar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(topToolBar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
helper = new DBHelper(this);
dbList = new ArrayList<>();
dbList = helper.getDataFromDB();
if (dbList.size() > 0 && tORf.equalsIgnoreCase("false")) {
btnSave.setVisibility(View.INVISIBLE);
String Nwhat = dbList.get(position).getRowid();
String Nwebsite = dbList.get(position).getWebsite();
String Nusername = dbList.get(position).getUsernane();
String Npassword = dbList.get(position).getPassword();
String Nquestion = dbList.get(position).getQuestion();
String Nanswer = dbList.get(position).getAnswer();
String Nnotes = dbList.get(position).getNotes();
etWebSite.setText(Nwebsite);
etUN.setText(Nusername);
etPW.setText(Npassword);
etSecQuestion.setText(Nquestion);
etSecAnswer.setText(Nanswer);
etNotes.setText(Nnotes);
}
}// END onCreate Bundle
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
public void hint_text_listener() {
/*
This listener is set in the onCreate Bundle section of the program
It fires when the EditText field etSecAnswer gains focus WHY ?
etSecAnswer is a required field when SAVEING where as etNotes is not required
*/
etSecAnswer.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
if (hasFocus) {
etNotes.setHint(null);
}
}
});
}
/* CODE below manages the etNotes by limiting the etNotes to 3 lines */
/* and it removes the 4th line when the ENTER key is pressed it also renders */
/* the etNotes DISABLED hence the need for the OnLongClickListener on the Image Keys */
private void addTextChangedListener() {
etNotes.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
int L = etNotes.getLineCount();
if (L > 3) {
etNotes.getText().delete(etNotes.getSelectionEnd() - 1, etNotes.getSelectionStart());
//etNotes.append("\b"); Used for TESTING line of code above
etNotes.setEnabled(false);
Toast.makeText(DetailsActivity.this, "Only 3 Lines Permitted\n\nLong Press on the Keys to Edit", Toast.LENGTH_LONG).show();
}
}
});
}
private void addListenerOnButtonDelete() {
btnDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Calls the Method deleteDBRow in DatabaseHelper
// which acts on the TABLE_INFO to remove a record by getting the record ID
helper.deleteDBRow(String.valueOf(dbList.get(position).getRowid()));
ListActivity.removeListRow(position);
// Code line above calls Method in ListActivity to notify recycler view of changes
// NOTICE the List keeps items by position not record ID <== READ
etWebSite.setText("");
etUN.setText("");
etPW.setText("");
etSecQuestion.setText("");
etSecAnswer.setText("");
etNotes.setText("");
Intent intent = new Intent(DetailsActivity.this, ListActivity.class);
startActivity(intent);
}
});
}
private void addListenerOnButtonUpdate() {
btnUpdate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String website = etWebSite.getText().toString();
String username = etUN.getText().toString();
String password = etPW.getText().toString();
String question = etSecQuestion.getText().toString();
String answer = etSecAnswer.getText().toString();
String notes = etNotes.getText().toString();
if (etWebSite.length() == 0) {
Toast.makeText(DetailsActivity.this, "Enter Web-Site Name", Toast.LENGTH_LONG).show();
etWebSite.requestFocus();
return;
}
if (etUN.length() == 0) {
Toast.makeText(DetailsActivity.this, "Enter Username", Toast.LENGTH_LONG).show();
etUN.requestFocus();
return;
}
if (etPW.length() == 0) {
Toast.makeText(DetailsActivity.this, "Enter Password", Toast.LENGTH_LONG).show();
etPW.requestFocus();
return;
}
if (etSecQuestion.length() == 0) {
Toast.makeText(DetailsActivity.this, "Enter Security Question", Toast.LENGTH_LONG).show();
etSecQuestion.requestFocus();
return;
}
if (etSecAnswer.length() == 0) {
Toast.makeText(DetailsActivity.this, "Enter Security Answer", Toast.LENGTH_LONG).show();
etSecAnswer.requestFocus();
return;
}
String rowid = dbList.get(position).getRowid();
helper.updateDBRow(rowid, website, username, password, question, answer, notes);
etWebSite.setText("");
etUN.setText("");
etPW.setText("");
etSecQuestion.setText("");
etSecAnswer.setText("");
etNotes.setText("");
Intent intentTO = new Intent(DetailsActivity.this, ListActivity.class);
startActivity(intentTO);
Toast.makeText(DetailsActivity.this, "Record Updated", Toast.LENGTH_LONG).show();
}
});
}
private void addListenerOnButtonSave() {
btnSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String website = etWebSite.getText().toString();
String username = etUN.getText().toString();
String password = etPW.getText().toString();
String question = etSecQuestion.getText().toString();
String answer = etSecAnswer.getText().toString();
String notes = etNotes.getText().toString();
if (etWebSite.length() == 0) {
Toast.makeText(DetailsActivity.this, "Enter Web-Site Name", Toast.LENGTH_LONG).show();
etWebSite.requestFocus();
return;
}
if (etUN.length() == 0) {
Toast.makeText(DetailsActivity.this, "Enter Username", Toast.LENGTH_LONG).show();
etUN.requestFocus();
return;
}
if (etPW.length() == 0) {
Toast.makeText(DetailsActivity.this, "Enter Password", Toast.LENGTH_LONG).show();
etPW.requestFocus();
return;
}
if (etSecQuestion.length() == 0) {
Toast.makeText(DetailsActivity.this, "Enter Security Question", Toast.LENGTH_LONG).show();
etSecQuestion.requestFocus();
return;
}
if (etSecAnswer.length() == 0) {
Toast.makeText(DetailsActivity.this, "Enter Security Answer", Toast.LENGTH_LONG).show();
etSecAnswer.requestFocus();
return;
}
helper.insertIntoDB(website, username, password, question, answer, notes);
etWebSite.setText("");
etUN.setText("");
etPW.setText("");
etSecQuestion.setText("");
etSecAnswer.setText("");
etNotes.setText("");
Intent intentTO = new Intent(DetailsActivity.this, ListActivity.class);
startActivity(intentTO);
Toast.makeText(DetailsActivity.this, "Record Added", Toast.LENGTH_LONG).show();
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {// Little BACK <== arrow key on ToolBar
Intent intent = new Intent(DetailsActivity.this, ListActivity.class);
startActivity(intent);
return true;
}
if (id == R.id.action_ReSetPW) {
// This is the menu ReSetPW button for Master Password
// It lives in the menu_main.xml file
doCustom();
}
return super.onOptionsItemSelected(item);
}
private void doCustom(){
/* This method uses the custom_dialog.xml file created for greater control over
the styling of the Custom Alert Dialog for various screen sizes and to be
able to set the text size of the dialog message text
*/
final Dialog openDialog = new Dialog(context);
openDialog.setContentView(R.layout.custom_dialog);
Button btnYES = openDialog.findViewById(R.id.btnYES);
Button btnNO = openDialog.findViewById(R.id.btnNO);
openDialog.setCancelable(false);
// if YES delete Master Password from TABLE_MPW
btnYES.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences pref = getSharedPreferences("MyPref", MODE_PRIVATE);
pref.edit().remove("nameKey").apply();
db = helper.getReadableDatabase();
String q = "SELECT * FROM "+ TABLE_PW;
Cursor cursor = db.rawQuery(q,null);
// Above query gets TABLE_PW data from Col_IDI
// TABLE_PW will only ever have one row of data
int rowID = 99;
if(cursor.moveToFirst()){
rowID = cursor.getInt(cursor.getColumnIndex(Col_IDI));
str = cursor.getString(cursor.getColumnIndex(Col_MPW));
}
cursor.close();
// Line of code below WORKS deletes entire TABLE <=====
// Not a recommended way to re-set the master password
// db.delete(TABLE_PW, null, null);
String num = Integer.toString(rowID);
db.delete(TABLE_PW, Col_IDI + " = ?", new String[] { num });
db.close();
openDialog.dismiss();
Intent intentYY = new Intent(DetailsActivity.this, MainActivity.class );
startActivity( intentYY );
Toast.makeText(getApplicationContext(), "Changed the Password", Toast.LENGTH_SHORT).show();
}
});
btnNO.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openDialog.dismiss();
Intent intent = new Intent( DetailsActivity.this, ListActivity.class );
startActivity( intent );
Toast.makeText(getApplicationContext(), "Password NOT Changed", Toast.LENGTH_SHORT).show();
}
});
openDialog.show();
}
public void onBackPressed(){
Intent intent = new Intent( DetailsActivity.this, ListActivity.class );
startActivity( intent );
}
}