Android:unable to get data from webservice using kSoap

∥☆過路亽.° 提交于 2020-01-07 02:56:07

问题


hi in my app i am trying to check the username and password in database from webservice and if its true will show success message or failed message, but unable to show the status message

public class AndroidLoginExampleActivity extends Activity {
    private final String NAMESPACE = "http://ws.userlogin.com";
    private final String URL = "http://localhost:8080/Androidlogin/services/Login?wsdl";
    private final String SOAP_ACTION = "http://ws.userlogin.com/authentication";
    private final String METHOD_NAME = "authentication";
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button login = (Button) findViewById(R.id.btn_login);
        login.setOnClickListener(new View.OnClickListener() {

            public void onClick(View arg0) {
                loginAction();

            }
        });
    }

    @SuppressLint("NewApi") private void loginAction(){
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
         StrictMode.setThreadPolicy(policy); 
        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

        EditText userName = (EditText) findViewById(R.id.tf_userName);
        String user_Name = userName.getText().toString();
        EditText userPassword = (EditText) findViewById(R.id.tf_password);
        String user_Password = userPassword.getText().toString();

      //Pass value for userName variable of the web service
        PropertyInfo unameProp =new PropertyInfo();
        unameProp.setName("userName");//Define the variable name in the web service method
        unameProp.setValue(user_Name);//set value for userName variable
        unameProp.setType(String.class);//Define the type of the variable
        request.addProperty(unameProp);//Pass properties to the variable

      //Pass value for Password variable of the web service
        PropertyInfo passwordProp =new PropertyInfo();
        passwordProp.setName("password");
        passwordProp.setValue(user_Password);
        passwordProp.setType(String.class);
        request.addProperty(passwordProp);

        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.setOutputSoapObject(request);
        HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

        try{
            androidHttpTransport.call(SOAP_ACTION, envelope);
               SoapPrimitive response = (SoapPrimitive)envelope.getResponse();

               TextView result = (TextView) findViewById(R.id.tv_status);
               result.setText(response.toString());
          Log.d("resp:",response.toString() );
        }
        catch(Exception e){

        }
       }

below is my webservice call

public class Login {
 public String authentication(String userName,String password){

  String retrievedUserName = "";
  String retrievedPassword = "";
  String status = "";
  try{

   Class.forName("com.mysql.jdbc.Driver");
   Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","root","root");
   PreparedStatement statement =  con.prepareStatement("SELECT * FROM user WHERE username = '"+userName+"'");
   ResultSet result = statement.executeQuery();

   while(result.next()){
    retrievedUserName = result.getString("username");
    retrievedPassword = result.getString("password");
    }

   if(retrievedUserName.equals(userName)&&retrievedPassword.equals(password)){
    status = "Success!";
   }

   else{
    status = "Login fail!!!";
   }

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

 }

}

not sure were iam doing wrong.Any help is appreciated.


回答1:


You should do network realted operation on a thread. You can use a thread or AsyncTask.

Move your loginAction() inside a thread or inside doInbackground of AsyncTask.

Remember not to update ui from the back ground thread.

   new TheTask().execute();

AsyncTask

public class TheTask extends AsyncTask <Void,Void,Void>
{


    @Override
    protected void onPreExecute() {
        super.onPreExecute();
            // display a dialog
    }
    @Override
    protected Void doInBackground(Void... params) {
              // your login authentcation 
              // remove updation of textview.
              // do not update ui here 
    return null;
    }
    @Override
    protected void onPostExecute(Void result) {
    super.onPostExecute(result);
           // dismiss the dialog
           // update textview
          }
    }

AsyncTask docs

http://developer.android.com/reference/android/os/AsyncTask.html

Edit:

public class MainActivity extends Activity {
    private final String NAMESPACE = "http://ws.userlogin.com";
    private final String URL = "http://localhost:8080/Androidlogin/services/Login?wsdl";
    private final String SOAP_ACTION = "http://ws.userlogin.com/authentication";
    private final String METHOD_NAME = "authentication";
    /** Called when the activity is first created. */
    EditText ed1,ed2;
    TextView tv;
    String user_Name,user_Password;
    SoapPrimitive response ;
    ProgressDialog pd;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ed1 = (EditText) findViewById(R.id.editText1);
        ed2 = (EditText) findViewById(R.id.editText2);
        tv = (TextView) findViewById(R.id.textView1);
        user_Name = ed1.getText().toString();
       user_Password = ed2.getText().toString();
       pd = new ProgressDialog(this);
        Button login = (Button) findViewById(R.id.button1);
        login.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                new TheTask().execute();
            }
        });
    }
     class TheTask extends AsyncTask<Void,Void,SoapPrimitive>
     {



        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            pd.show();
        }

        @Override
        protected SoapPrimitive doInBackground(Void... params) {
               SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
                    PropertyInfo unameProp =new PropertyInfo();
                    unameProp.setName("userName");//Define the variable name in the web service method
                    unameProp.setValue(user_Name);//set value for userName variable
                    unameProp.setType(String.class);//Define the type of the variable
                    request.addProperty(unameProp);//Pass properties to the variable
                    PropertyInfo passwordProp =new PropertyInfo();
                    passwordProp.setName("password");
                    passwordProp.setValue(user_Password);
                    passwordProp.setType(String.class);
                    request.addProperty(passwordProp);

                    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
                    envelope.setOutputSoapObject(request);
                    HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

                    try{
                        androidHttpTransport.call(SOAP_ACTION, envelope);
                        response = (SoapPrimitive) envelope.bodyIn;
                        Log.i("Response",""+response);
                       // response = (SoapPrimitive)envelope.getResponse();
                    }
                    catch(Exception e){

                    }
            return response;
        }

        @Override
        protected void onPostExecute(SoapPrimitive result) {
            super.onPostExecute(result);
            pd.dismiss();
            if(result!=null)
            tv.setText(result.toString());
        }

     }

}



回答2:


        public static String ValidateSalesOfficerLogin(Context c, String userName,
                    String passWord) throws IOException, XmlPullParserException {
                String METHOD_NAME = "ValidateSalesOfficerLogin";
                String SOAP_ACTION = "http://tempuri.org/authentication/";
                SOAP_ACTION = SOAP_ACTION + METHOD_NAME;
                SoapObject request = new SoapObject(CommonVariable.NAMESPACE,
                        METHOD_NAME);
                // Use this to add parameters
                request.addProperty("Username", userName);
                request.addProperty("Password", passWord);

                // Declare the version of the SOAP request
                return WebCalls.call(c, request, CommonVariable.NAMESPACE, METHOD_NAME,
                        SOAP_ACTION);
            }



    //////////////////////////////////////////////////////////////////////////////
    public static String call(Context c,SoapObject request ,String NAMESPACE,String METHOD_NAME,String SOAP_ACTION) throws IOException, XmlPullParserException{
            Log.i(WebCalls,"URL: "+ CommonVariable.URL);
            Log.i(WebCalls,"Method Name: "+ METHOD_NAME);
            Log.i(WebCalls,"Parameters: "+request.toString());
            String SoapResult = null;
            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                    SoapEnvelope.VER11);

            envelope.setOutputSoapObject(request);

            envelope.dotNet = true;

                HttpTransportSE androidHttpTransport = new HttpTransportSE(CommonVariable.URL);

                // this is the actual part that will call the webservice
                androidHttpTransport.call(SOAP_ACTION, envelope);

                // Get the SoapResult from the envelope body.
                if (envelope.bodyIn instanceof SoapFault) {
                    SoapResult = ((SoapFault) envelope.bodyIn).faultstring;
                } else {
                    SoapObject resultsRequestSOAP = (SoapObject) envelope.bodyIn;
                    SoapResult = resultsRequestSOAP.getProperty(0).toString();
                }


                Log.i(WebCalls,"Response: "+ SoapResult);
            return SoapResult;
        }


call above method....

    public static void Setusernamepassword(Context context, String user ,string pass)
            throws JSONException, IOException, XmlPullParserException {

        String Response = SoaplCalls.ValidateSalesOfficerLogin(context, user,pass);
        Log.i("SetTokenId", Response);

    }




/////////////////////////////////////////////////////////////////////////////////////
new Thread(new Runnable() {

            @Override
            public void run() {

                try {
                    Setusernamepassword(viewCompetitor,user,pass);
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();

                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();

                } catch (XmlPullParserException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();

                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();

                } finally {
                    mHandler.post(new Runnable() {

                        @Override
                        public void run() {

                        }
                    });
                }

            }

        }).start();
    }


来源:https://stackoverflow.com/questions/18288128/androidunable-to-get-data-from-webservice-using-ksoap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!