Android - выбор метода для запуска в потоке - PullRequest
1 голос
/ 09 апреля 2020

Я создаю приложение Android, которое взаимодействует с веб-сервисом.

У меня есть класс SOAP, который содержит различные методы, которые выполняют функции веб-службы, и класс SOAPCaller, который запускает поток для вызова методы в классе SOAP.

Чтобы выбрать, какой метод вызывается потоком в SOAPCaller, я устанавливаю строку с именем метода, откуда бы в моем приложении не использовался мой метод run () затем есть оператор switch, который просматривает строку, чтобы решить, какой метод из SOAP должен быть вызван.

Это работает нормально, но просто кажется очень хакерским ... есть ли лучший способ сделать это? Могу ли я просто вызвать нужный метод в моем классе SOAPCaller, когда поток каким-то образом запускается?

Любая помощь или совет приветствуются. Спасибо!

HomeFragment

public void Addition()
    {
        try {

            //get values from ui
            int valueA = Integer.parseInt(etIntA.getText().toString());
            int valueB = Integer.parseInt(etIntB.getText().toString());

            //new soap caller
            SOAPCaller soapCaller = new SOAPCaller();
            //set method (this is how I tell the thread which method to run)
            soapCaller.setMethod("Addition");
            //set the values to be used by the addition method
            soapCaller.setAdditionValues(valueA, valueB);
            //start the thread
            soapCaller.setStartThread(true);
            //start soap caller thread
            soapCaller.join();
            soapCaller.start();

            //loop until result is updated
            while (soapCaller.getStartThread()) {

                try {
                    Thread.sleep(10);
                }
                catch(Exception ex) {

                }
            }

            //show the result on screen
            tvResult.setText(soapCaller.getResult());

        }
        catch(Exception ex) {

            //show error on screen
            Toast.makeText(getActivity(), "Error: " + ex.toString(),Toast.LENGTH_SHORT).show();
        }
    }

SOAPCaller:

private String method;
private String result;

public void run() {

    try {

        //new soap actions class
        soap = new SOAP();

        switch (method) {

            case "Addition":
                //call addition action, pass given values and get the result
                result = soap.Addition(additionA, additionB);
                startThread = false;
                break;

            case "InsertEmployee":
                //pass values and insert new employee into database
                result = soap.InsertEmployee(insertName, insertDob, insertRole);
                startThread = false;
                break;

            case "SelectEmployee":
                //pass values and insert new employee into database
                result = soap.SelectEmployee(selectEmployeeName);
                startThread = false;
                break;

            case "ConnectionTest":
                //test the webservice connection
                result = soap.ConnectionTest();
                startThread = false;
                break;

        }
    }
    catch (Exception ex)
    {
        //error occurred
        result = ex.toString();
    }
}

SOAP

 public String Addition(int a, int b) {

     //new request and property
     SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE, OPERATION_NAME_ADDITION);
     PropertyInfo propertyInfo;

     //add integer a into property info
     propertyInfo = new PropertyInfo();
     propertyInfo.setName("valueA");
     propertyInfo.setValue(a);
     propertyInfo.setType(Integer.class);
     request.addProperty(propertyInfo);

     //add integer b into property info
     propertyInfo = new PropertyInfo();
     propertyInfo.setName("valueB");
     propertyInfo.setValue(b);
     propertyInfo.setType(Integer.class);
     request.addProperty(propertyInfo);

     //new soap serialisation envelope
     SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
     envelope.setOutputSoapObject(request);
     envelope.dotNet = true;

     //set http transport as webservice address
     HttpTransportSE httpTransportSE = new HttpTransportSE(SOAP_ADDRESS);

     //object to hold result
     Object response = null;

     try {

         //call SOAP action and get response
         httpTransportSE.call(SOAP_ACTION_ADDITION, envelope);
         response = envelope.getResponse();
     }
     catch (Exception ex) {

         //get error
         response = ex.toString();
     }

     //return result
     return response.toString();
 }
...