читать из готовой базы данных в андроид студии - PullRequest
0 голосов
/ 12 октября 2019

привет, пожалуйста, мне нужна ваша помощь. Весь этот месяц я пытался узнать, как читать данные из готовой базы данных (sqlite.db) в проекте

.. Я хочу создать базу данных и заполнить ее до того, какЯ готов это (например, книга), затем я хочу, чтобы показать эти детали в текстовом виде или любой

Я ищу очень много, но все видео-уроки просто скомбинированы сделать внутреннюю базу данных, и обновить отделить и удалитьно я хочу загрузить внешнюю базу данных, которую я заполнил до этого, и я хочу использовать ее в своем приложении. Пожалуйста, помогите мне, как сделать, я работал над этим кодом, но это только для внутренней базы данных

Я использую этоyoutube video tutorial

https://www.youtube.com/watch?v=rziyVBKEU50

Я добавил запрос на чтение внешнего хранилища, которого нет в приложении. Я подумал, что это необходимо

Я попробовал этовидеоурок, но мое приложение не работает, где мои проблемы?

примечание: это приложение, которое мы называем именем в тексте редактирования, оно дает нам адрес этого запроса

пакетcom.sirwansoft.externaldatabase;

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

import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;

public class DatabaseOpenHelper extends SQLiteAssetHelper {
    private static final String DATABASE_NAME="data";
    private static final int DATABASE_VERSION=1;

//constractor

    public DatabaseOpenHelper(Context context){
        super(context,DATABASE_NAME,null,DATABASE_VERSION);

    }

}

и мой файл активов базы данных

package com.sirwansoft.externaldatabase;

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

public class DatabaseAcsess {
    private SQLiteOpenHelper openHelper;
    private SQLiteDatabase db;
    private static  DatabaseAcsess instance;
    Cursor c =null;


    //privite constractor that object creating from outside the class is avoided
    private DatabaseAcsess (Context context){
        this.openHelper=new DatabaseOpenHelper(context);


    }

    //return instance of the class

    public static DatabaseAcsess getInstance(Context context){
        if (instance==null){
            instance=new DatabaseAcsess(context);


        }return instance;

    }
    //to open the database
    public void open(){
        this.db=openHelper.getWritableDatabase();

    }
    //closing the database connection

    public void close(){
        if (db!=null){
            this.db.close();
        }


    }

    //we will query for address by passing name
    public String getAddress(String name){

        c=db.rawQuery("select address form Tabale Where Name = '"+name+"'",new String[]{});
        StringBuffer buffer =new StringBuffer();
        while (c.moveToNext()){
            String address = c.getString(0);
            buffer.append(""+address);

        }return buffer.toString();


    }

}

и мой MainActivity

package com.sirwansoft.externaldatabase;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
EditText edit_name;
Button btn_query;
TextView text_res;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        edit_name=findViewById(R.id.edit_name);
        btn_query=findViewById(R.id.btn_query);
        text_res=findViewById(R.id.text_res);


        ActivityCompat.requestPermissions(MainActivity.this,
                new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                1);

        //setOnClick to button
        btn_query.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                DatabaseAcsess databaseAcsess =DatabaseAcsess.getInstance(getApplicationContext());
                databaseAcsess.open();


                    //getting string value from address

                String name = edit_name.getText().toString();
                String address =databaseAcsess.getAddress(name); //we use the getAddress method to get address


                //setting text to result field
                text_res.setText(address);

                databaseAcsess.close();

                //database connection closed
                //done
            }
        });

    }
    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case 1: {

                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.
                } else {

                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    Toast.makeText(MainActivity.this, "Permission denied to read your External storage", Toast.LENGTH_SHORT).show();
                }
                return;
            }

            // other 'case' lines to check for other
            // permissions this app might request
        }
    }
}

databae is in assets file in databases file

и это аварийный выход из системы

10-13 01:33:21.579 22724-22724/? I/art: Not late-enabling -Xcheck:jni (already on)
10-13 01:33:21.694 22724-22724/com.sirwansoft.externaldatabase W/System: ClassLoader referenced unknown path: /data/app/com.sirwansoft.externaldatabase-1/lib/x86
10-13 01:33:21.815 22724-22724/com.sirwansoft.externaldatabase W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter androidx.vectordrawable.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
10-13 01:33:22.212 22724-22724/com.sirwansoft.externaldatabase I/art: Rejecting re-init on previously-failed class java.lang.Class<androidx.core.view.ViewCompat$2>
10-13 01:33:22.212 22724-22724/com.sirwansoft.externaldatabase I/art: Rejecting re-init on previously-failed class java.lang.Class<androidx.core.view.ViewCompat$2>
10-13 01:33:22.516 22724-22766/com.sirwansoft.externaldatabase D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
10-13 01:33:22.687 22724-22766/com.sirwansoft.externaldatabase I/OpenGLRenderer: Initialized EGL, version 1.4
10-13 01:33:22.688 22724-22766/com.sirwansoft.externaldatabase W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
10-13 01:33:22.717 22724-22766/com.sirwansoft.externaldatabase D/EGL_emulation: eglCreateContext: 0xae4a4480: maj 2 min 0 rcv 2
10-13 01:33:22.721 22724-22766/com.sirwansoft.externaldatabase D/EGL_emulation: eglMakeCurrent: 0xae4a4480: ver 2 0 (tinfo 0xae492ee0)
10-13 01:33:22.785 22724-22766/com.sirwansoft.externaldatabase D/EGL_emulation: eglMakeCurrent: 0xae4a4480: ver 2 0 (tinfo 0xae492ee0)
10-13 01:33:23.293 22724-22766/com.sirwansoft.externaldatabase D/EGL_emulation: eglMakeCurrent: 0xae4a4480: ver 2 0 (tinfo 0xae492ee0)
10-13 01:33:23.299 22724-22766/com.sirwansoft.externaldatabase E/Surface: getSlotFromBufferLocked: unknown buffer: 0xaab0aa00
10-13 01:33:31.669 22724-22766/com.sirwansoft.externaldatabase D/EGL_emulation: eglMakeCurrent: 0xae4a4480: ver 2 0 (tinfo 0xae492ee0)
10-13 01:33:37.558 22724-22724/com.sirwansoft.externaldatabase W/SQLiteAssetHelper: copying database from assets...
10-13 01:33:37.558 22724-22724/com.sirwansoft.externaldatabase D/AndroidRuntime: Shutting down VM
10-13 01:33:37.559 22724-22724/com.sirwansoft.externaldatabase E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.sirwansoft.externaldatabase, PID: 22724
    com.readystatesoftware.sqliteasset.SQLiteAssetHelper$SQLiteAssetException: Missing databases/data file (or .zip, .gz archive) in assets, or target folder not writable
        at android.content.res.AssetManager.openAsset(Native Method)
        at android.content.res.AssetManager.open(AssetManager.java:313)
        at android.content.res.AssetManager.open(AssetManager.java:287)
        at com.readystatesoftware.sqliteasset.SQLiteAssetHelper.copyDatabaseFromAssets(SQLiteAssetHelper.java:436)
        at com.readystatesoftware.sqliteasset.SQLiteAssetHelper.createOrOpenDatabase(SQLiteAssetHelper.java:400)
        at com.readystatesoftware.sqliteasset.SQLiteAssetHelper.getWritableDatabase(SQLiteAssetHelper.java:176)
        at com.sirwansoft.externaldatabase.DatabaseAcsess.open(DatabaseAcsess.java:34)
        at com.sirwansoft.externaldatabase.MainActivity$1.onClick(MainActivity.java:40)
        at android.view.View.performClick(View.java:5198)
        at android.view.View$PerformClick.run(View.java:21147)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5417)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
10-13 01:38:37.636 22724-22724/com.sirwansoft.externaldatabase I/Process: Sending signal. PID: 22724 SIG: 9

он не может найти файл базы данных, но почему?

com.readystatesoftware.sqliteasset.SQLiteAssetHelper $ SQLiteAssetException: отсутствует база данных / файл данных (или. zip, архив .gz) в активах или целевой папке недоступны для записи

line error 34

enter image description here

1 Ответ

1 голос
/ 13 октября 2019

ОК, это объяснит шаблон 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 );
}

}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...