-1

hello please I need your help All of this month I tryed to know how to read data from ready database (sqlite.db) in project

.. I want to make a database and I full it befor I ready it (for example a book) then i want to show this detales in a text view or any

I search very mutch but all of video tutorials just fucosed on make an internal database , and update detale and delete but I want to load an external database that I full it befor and I want to use it inside my app pleas help me how to do that I worked on this code but it is just for internal database

I use this youtube video tutorial

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

I added ask for read external storage that is not in app I thinked it's mabe necessary

I tryed this video tutorial but my App is crashed where is my problams?

note : this app we inter a name inside a Edittext it give us the address of this query

package 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);

    }

}

and my database assets file

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();


    }

}

and my 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

and this is crash logout

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

it cannot find database file but why?

com.readystatesoftware.sqliteasset.SQLiteAssetHelper$SQLiteAssetException: Missing databases/data file (or .zip, .gz archive) in assets, or target folder not writable

line error 34

enter image description here

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • Are you on line and do you know how to use MVC pattern to interact with a database – Vector Oct 12 '19 at 20:59
  • OK take a look at this link https://www.devglan.com/android/android-sqlite-database-example it is one of the better examples on how to manage a sqlite DB if you respond I will send you full code or post it here for a Android app that uses SQLite DB – Vector Oct 12 '19 at 21:14
  • @Grendel no , do you mean that I have learn MVC ? – Sirwan Rahimi Oct 12 '19 at 21:46
  • MVC is not a language it is Model View Controller pattern or design that makes managing a DB very simple – Vector Oct 12 '19 at 21:47
  • I have a some what large Android project that I can zip up and try to put the code in my GitHub and you can download it Posting it here is a bit of a pain based on the fact that it as a number or res folders YOUR CALL – Vector Oct 12 '19 at 21:50
  • I will post the Model Class and the Helper Class you can get an idea. Also are you wanting to add the data or have some mock data added before you work on the DB if that is the case adding data before programmaticly this is not a good idea – Vector Oct 12 '19 at 21:51

1 Answers1

1

OK this will explain the MVC pattern for a database
Here is the Model Class

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;
}

}

Here is the Helper Class that creates the tables

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();
}

And the Screen where you enter data

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 );
}

}

Vector
  • 3,066
  • 5
  • 27
  • 54
  • please check again my code and detale I give more information and tryed a new code @Grendel – Sirwan Rahimi Oct 12 '19 at 22:23
  • @Sirwan Rahimi No this code is for an embedded DB the setup to link to a external DB is very different you need to tell your app how to connect to the server that is housing your DB I only do this with Firebase from Google and this whole process evolves a little more learning I would suggest you learn to manage a DB on the device then move on to a DB in the cloud Hosting is also a question certain Hosting sites only support various DB so you need to know who will be hosting Cost might be a factor that is why I used Google Firebase it is FREE The MVC pattern is a must if you want to use Cloud – Vector Oct 12 '19 at 22:28
  • thank you I am trynig your code now , can u help if I need for this code that u give me? – Sirwan Rahimi Oct 12 '19 at 22:34
  • @Sirwan Rahimi The Video is good but this is not the ideal way to create a DB and the corresponding tables. I use DBBrowser to test SQL statements and to look at a DB that is from other Apps If you want a job in IT you need to know how to crate a DB and teh tables from SCRATCH – Vector Oct 12 '19 at 22:34
  • @Sirwan Rahimi this is only partial code and you will do a lot of work to fit it in your project look at the link Isent you and search GitHub for a repo that has code for a Cloud DB – Vector Oct 12 '19 at 22:37
  • if I want to build a book app that use the database that I fill it by (DB browser sqlite .exe) you say I have to learn about database in firebase ? can you show me an tutorial about it in any site or video to I try to learn it – Sirwan Rahimi Oct 12 '19 at 22:38
  • @Sirwan Rahimi you need to focus on Android and SQLite embeded then think about a Firebase App Google Firebase and they have example apps I have code some where Really write a new app following the MVC pattern like the one in the link we sent you FIRST – Vector Oct 12 '19 at 22:44