Function in Mainactivity waiting for an asynchronous return of a function that is in an Asynctask, there being intermediate classes between both

Asked

Viewed 49 times

1

The application has a Class with functions that perform actions in an internal BD and another Class that does almost the same for a BD by an external API.

I’ve reviewed the case soen in English and others, but they did not serve me well. I also studied the functionality of Wait(), notify() and notifyAll functions(), but I’m not seeing a more suitable way to get the return of the asynchronous function, without putting one function (which depends on a return) inside another (which treats the return) to get the data in the correct time.

The classes are like this:

APIConnect extends AsyncTask //Recebe a informação para enviar à API externa.

APIExternalQuery //Chama APIConnect enviando-lhe a informação adequada para cada função da API externa.

CrudDB //API interna. Contem função para acessar o SQLite e dentro de cada função existe também a opção de acionar a função correspondente em APIExternalQuery

LoginActivity //faz uso da class CrudDB.

Note: in the case of Cruddb, my intention is that, from a function, the internal bank or the external API can be triggered.

I see as the most "difficult" the fact that there are intermediate classes between which contain the asynchronous function and the requisitive class.

I appreciate some feedback. They follow short codes of the classes:

Loginactivity

public class LoginActivity extends AppCompatActivity implements IAPIConnectListener {

//Recebe os dados da API externa através da interface e envia para a função que fez a chamada.
@Override
public void apiReturn(Object returnVals, int internalFunctionCode) {
    try {
        switch (internalFunctionCode) {
            case authValidation:
                if (returnVals instanceof JSONArray) {
                    authValidation(((JSONArray) returnVals).getBoolean(0), false);
                } else if (returnVals instanceof Boolean) {
                    authValidation(((Boolean) returnVals), false);
                }
                break;
        }
    } catch (JSONException j) {
        Log.i(TAG, "apiReturn->JSONException: " + j.getMessage());
    }
}

//"getOrPost" é para indicar de a função dever enviar a query ou tratar o retorno dela.
private void authValidation(boolean isValid, boolean getOrPost) {
    CrudDB dataBase = new CrudDB(LoginActivity.this);

    if (getOrPost) {//Faz a requisição
        String[] columnsId = {COLUMN_ID_MATRIC_USUARIO_PK, COLUMN_SENHA_USUARIO};
        dataBase.existsLine(TABLE_USUARIO, columnsId, new Object[]{mMatricLogin, mPassword}, this, authValidation);

    } else {//Trata a resposta vinda da API externa

        if (isValid) {
            //finish();
            shareUserDataAndReleaseAccess(null, true);//Compartilha os dados do usuário e libera o acesso.


        } else {
            mLoginView.requestFocus();
            mLoginView.setError(getString(R.string.error_incorrect_datas));
        }
    }
}
authValidation(null, true);
}

Cruddb

public class CrudDB {
    ...
    public void existsLine(String table, String[] columnIds, Object[] ids, IAPIConnectListener requesterClass, int requesterFunction) {

        if (externalReturn) {//Se a consulta à API externa está ativada
        APIExternalQuery apiExternalQuery = new APIExternalQuery(requesterClass, requesterFunction);
        apiExternalQuery.existsExtLine(table, columnIds, ids);

        } else {//Se não, requisita o SQlite.
            ...
            requesterClass.apiReturn(true, requesterFunction);
            ... 
            requesterClass.apiReturn(false, requesterFunction);         

        }
    }
}

Apiconnect

public class APIConnect extends AsyncTask<String, String, String> {
    ...

    public APIConnect(String ipAddress, IAPIConnectListener requesterClass, int requesterFunction) {
        this.ipAddressDB = ipAddress;
        this.requesterClass = requesterClass;
        this.requesterFunction = requesterFunction;
    }


    @Override
    protected String doInBackground(String... params) {
        ...
        return (serverReturn.toString());
        ...
    }

    @Override
    protected void onPostExecute(String asyncReturn) {
        ... 
        JSONArray jsonArray = new JSONArray(asyncReturn);
        requesterClass.apiReturn(jsonArray, requesterFunction); 
        ...
    }
}

Apiexternalquery

public class APIExternalQuery {
    ...
    public APIExternalQuery(IAPIConnectListener requesterClass, int requesterFunction) {
       this.requesterClass = requesterClass;
       this.requesterFunction = requesterFunction;
    }

    public void existsExtLine(String table, String[] colId, Object[] id) {
        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("funcType", 7);
            jsonObject.put("tab", table);
            ...
            jsonObject.put("colsId", jsonArraycolumnsId);
            jsonObject.put("ids", jsonArrayinputId);

        } catch (JSONException j) {
            Log.i(TAG, "existsExtLine()->" + j.getMessage());
        }
        new APIConnect(ipAddress, requesterClass, requesterFunction).execute(jsonObject.toString());
    }
}
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.