database – How to effectively sperate CRUD operations from the main SQLiteOpenHelper – android studio

I’m conflicting about how I want my database architecture to be built.
First of all, I use a singleton pattern for the database in order to insure one instance of it (so its thread-safe), and also for me to get a workable database reference wherever I have a context.

All across the application I make many different db operations, for example, some activities need to change only the ‘Meals’ table and some need to change ‘Meals’ & ‘MealFoods’ for example.

For each one of this tables I’ve built a helper class in order to separate the CRUD operations of each table apart from the DatabaseManager class (which extends SQLiteOpenHelper). This, of course is for the sake of simplicity and to get a cleaner code.

First approach:

This approach saves all the helper classes inside the DatabaseManager.

DatabaseManager.java:

public class DatabaseManager extends SQLiteOpenHelper {
    private static String dbName = "logs.db";
    private static final int dbVersion = 1;

    private final Context context;
    public MealsDBHelper mealsDBHelper;
    public MealFoodsDBHelper mealFoodsDBHelper;

    private DatabaseManager(@NonNull Context context) {
        super(context, dbName, null, dbVersio);
        this.context = context.getApplicationContext();//Saving as application context to avoid leaks
        mealsDBHelper = new MealsDBHelper(context);
        mealFoodsDBHelper = new MealFoodsDBHelper(context);
    }

    private static DatabaseManager instance;
    public static synchronized DatabaseManager getInstance(Context context) {
        if (instance == null) {
            instance = new DatabaseManager(context);
        }
        return instance;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        //...
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        //...
    }
}

Let’s look at the MealsDBHelper class, which pretty much all it does is to help communicate CRUD operations with the database. (For example a user wants to change his meal name)

public class MealsDBHelper {
    public static final String MEALS_TABLE_NAME = "Meals";
    public static final String MEAL_ID_COLUMN = "Meal_ID";
    public static final String MEAL_NAME_COLUMN = "Meal_Name";
    public static final String MEAL_POS_COLUMN = "Meal_Pos";
    public static final String MEAL_DATE_COLUMN = "Date";


    private Context context; //A context object to pass on to the DatabaseManager.getInstance method in all the different methods inside this class
    public MealsDBHelper(Context context){
        this.context = context;
    }

    //For example one of few methods that do operations on the 'Meals' table in the database.
    public void updateMealName(long mealId, String meal_name) {
        UserDataDB.getInstance(context).getWritableDatabase().execSQL("UPDATE " + MEALS_TABLE_NAME + " SET " + MEAL_NAME_COLUMN + " = '" + meal_name + "' WHERE " + MEAL_ID_COLUMN + " = " + mealId);
    }
}

Now, no matter if the activity is modifying 1 or 2 or even 3 tables, I’m able to update the meal’s name like so:

DatabaseManager.getInstance(context).mealsDBHelper.updateMealName(mealId, mealName);

Thats because the DatabaseManager contains a reference to all the other helper classes.

What I like about this approach is that I can simply access every table and do operations on it according to my needs, & what I don’t like is that the DatabaseManager class holds reference for all the helpers, and I’m not sure if its best to do so..

Second approach:

This approach does not saves all the helper classes inside the DatabaseManager.

DatabaseManager.java:

public class DatabaseManager extends SQLiteOpenHelper {
    private static String dbName = "logs.db";
    private static final int dbVersion = 1;

    private final Context context;

    private DatabaseManager(@NonNull Context context) {
        super(context, dbName, null, dbVersio);
        this.context = context.getApplicationContext();//Saving as application context to avoid leaks
    }

    private static DatabaseManager instance;
    public static synchronized DatabaseManager getInstance(Context context) {
        if (instance == null) {
            instance = new DatabaseManager(context);
        }
        return instance;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        //...
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        //...
    }
}

Now, if my activity needs to modify both ‘Meals’ & ‘MealFoods’ tables I can construct the helpers in onCreate, such as:

public class AddFoodActivity extends AppCompatActivity{

    MealsDBHelper mealsDBHelper;
    MealFoodsDBHelper mealFoodsDBHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(..);

        mealsDBHelper = new MealsDBHelper(this);
        mealFoodsDBHelper = new MealFoodsDBHelper(this);
    }

    //Then whenever I need to modify the table I use:
    mealsDBHelper.updateMealName(mealId, mealName);
}

What I like about this approach is that I can use a simple line to modify a table according to my needs,
& what I don’t like is that I need to define helper references for every activity, and it kind of makes the code inconsistent.

Basically are there any downsides for using one of the methods?

I’ll admit I did leave a big chunk of code out of this post, but its only because I think it won’t add a lot to your understanding of the problem, because its a more general one.

Thank you very much for any kind of help.

Why does my phone stop sending me Chase Android notifications?

I set up my Chase app on my Galaxy S8+ to send me an Android notification whenever money leaves my account. This was working fine up until about 2 or 3 years ago, then it became buggy.

I recently formatted my phone to try to solve this problem so that I’d have a fresh start. The notifications were coming in just fine and I was thrilled! However, just today they’ve stopped coming in when I spend money and I’m not sure why. I don’t remember making any major changes to my phone in the last few days either.

Does anyone have a list of things I could check to figure out why I’m not receiving them anymore? And is anyone else having this problem??

wi fi – How to hide your SSID from apps / keep your Android apps from finding your Wifi SSID?

As far as I know, all android apps are able to scan nearby / available Wifi networks. They can either get a list of nearby SSIDs, or at least they can get the SSID of the Wifi you are currently on. Correct? I remember the “get wifi scan results” unrevokable permission from some time ago (stoppable only if you were rooted and had xposed framework) (Also, exhibit B: Google, SkyHook, and Apple SSID databases).

This means that even if you are on a VPN, even if you turn off wifi scanning, even if you turn off location services and take out your sim card, even if you stop broadcasting your router’s wifi SSID, your apps will be able to know what wifi SSID you are currently on.

This means that an attacker (read: the surveillance capitalism 🙂 ), can figure out if/when I am home, and which other devices that are/were online have used the same SSID. E.g. all my family’s (mandatory) banking apps will know where my family members congregate, and could change my insurance score, or other “insert dystopian scenario here”.

Considering what I described, I don’t think there is any wiggle room for you to ever hide your real location from a bad (state, corp, hacker) actor. Am I wrong? Can I hide my SSID from the apps that are on my phone?

I can’t believe there aren’t any hits on this subject on the internet.

(PS: obviously, the point of the question is not whether or not I am paranoid, the question is whether this is technically solvable)

Which Virtual machine is used in Android 11?

Every android application runs in a virtual machine. We know that Dalvik virtual machine is the one that is used by android. Next, They have changed to ART(Android Runtime machine). Just correct me if I am wrong. Android 11 uses which virtual machine? Dalvik or ART?

Viewing files on Android phone from computer, only showing DCIM and Pictures folders, in internal shared storage

I have phones running Android..

When I connect either one to my computer, and click “internal shared storage”, I only see DCIM and Pictures..

But if I go to any decent file manager app on the phone then it shows far more folders within “internal shared storage” e.g. Download, and other folders.

One of my phones, comes with what looks like a nice app for backing up, and it creates a folder with the backup, and I want to copy that folder to my computer. But I cant see how to access that folder to copy it onto my computer!

I’d be a little bit surprised if this is a situation where the phone has to be rooted to do it.. I do plan to, but this is an app that the phone comes with. So some may backup the phone before unlocking the bootloader.

windows 10 – Android in Virtual Box: Is it safe to use online Banking apps etc.?

Stack Exchange Network


Stack Exchange network consists of 176 Q&A communities including Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Visit Stack Exchange

For video playback from cloud, would a properly written native mobile app be faster than a web app run on Android?

I want to develop a backend cloud service that delivers full color compressed videos (as high def as possible) to Android smart phones for streaming playback. Would I get better playback if I properly develop a native mobile app or if I simply use the browser, maybe with some scripting, to access and play the video? I want the highest bandwidth playback I can get. Thanks!

How long does a HiddenEye keylogger script last in an Android browser?

I recently clicked on a phishing link and entered my credentials but then I changed the password. I believe the phisher used HiddenEye with a keylogger script in the webpage so how long can he capture my keystrokes for, after clicking the link I immediately closed the browser and cleared the cookies and seemed to find no malware when I did an antivirus scan but what if he enabled the keylogger script in my browser when I clicked the link, how do I find out?

android – ¿guardar en una BBDD phpmyadmin el ID de lo que selecciono en un spinner?

<por favor su ayuda, los datos que obtengo de una tabla los muestro en el spinner, de ahí quiero guardar el id del item seleccionado pero no lose, he visto que se debe de crear un metodo para obtener primero el id y luego enviar a guardar. Estoy creando un metodo que esta en la parte de abajo que s de guardar porque estoy enviando datos adicionales a la misma tabla que quiero guardar lo del spinner por favor su ayuda. Gracias>

private void llenarSpinner(){ //se encarga de llamar al cargarspinner
        String url="obtener.php";
        cliente.post(url, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header() headers, byte() responseBody) {//evalua la pagina si e que cumple on la condicion
                if (statusCode == 200){
                    cargarSpinner (new String(responseBody));
                }

            }

            @Override
            public void onFailure(int statusCode, Header() headers, byte() responseBody, Throwable error) {

            }
        });
    }

    private void cargarSpinner(String respuesta){
        ArrayList <Barrio> lista = new ArrayList<Barrio>();

        try {
            JSONArray jsonArreglo = new JSONArray(respuesta);
            for(int i=0; i < jsonArreglo.length(); i++){
                Barrio b = new Barrio();
                b.setNombrebarrio(jsonArreglo.getJSONObject(i).getString("nombre_circuito"));
                lista.add(b);
            }
            ArrayAdapter <Barrio> a = new ArrayAdapter <Barrio> ( this, android.R.layout.simple_dropdown_item_1line, lista);
            spnbarrio.setAdapter(a);

        }catch (Exception e){
            e.printStackTrace();

        }
    }
}


y tengo el metodo agregar cliente y boton guardar-----

lo que hago en el metodo guardar es validar q los campos no esten vacios y si es qalguno esta envia un mensaje, y ahi llamo al agregar cliente

    private void agregarCliente(Cliente c){
        String url = "/agregarcliente.php?";
        String parametros = "cedula="+c.getCedula()+"&nombreclientes="+c.getNombres()+"&apellidoclientes="+c.getApellidos()+"&telefonoclientes="+c.getTelefono()+"&correoclientes="+c.getCorreo()+"&direccionclientes="+c.getDireccion()+"&distritoclientes="+c.getBarrio()+"&rucclientes"+c.getRuc();
        cliente.post(url + parametros, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header() headers, byte() responseBody) {
                if(statusCode == 200){
                    Toast.makeText(ingresoclientes.this, "Cliente agregado correctamente", Toast.LENGTH_SHORT).show();
                    

                }
            }

            @Override
            public void onFailure(int statusCode, Header() headers, byte() responseBody, Throwable error) {

            }
        });
    }