登录表单在android中调用soap webservices

时间:2012-07-17 06:01:21

标签: android mysql android-intent

您好我开发了一个登录表单,调用soap webservices.it成功完全为我工作...但现在我实现了一部分。当我的登录详细信息成功意味着它将进入下一个活动。 怎么办......面临一些困难。 编码部分如下。

dis是我的webservices java项目:

package com.userlogin.ws;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

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/androidlogin","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;

  }

  }

dis是我的android端编码部分:

package com.androidlogin.ws;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.content.Intent;

public class AndroidLoginExampleActivity extends Activity {
private final String NAMESPACE = "http://ws.userlogin.com";
private final String URL = "http://192.168.1.168:8085/Login/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();

   }
  });
   }

private void loginAction(){
 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());

    }
    catch(Exception e){

    }

    Button registerScreen = (Button) findViewById(R.id.btn_login);

    // Listening to register new account link
    registerScreen.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // Switching to Register screen
            Intent i = new Intent(getApplicationContext(), RegisterActivity.class);
            startActivity(i);
        }
      });
   }

   }

这里当点击按钮意味着它被重定向到下一个活动..但我希望如果成功登录意味着它转到下一个活动....请在哪里放置意图编码或告诉我该怎么做...请指导我。

3 个答案:

答案 0 :(得分:1)

据我了解您的问题,您必须检查您的登录网络服务电话的响应,并在此基础上制定条件。

如果您的回复包含成功!状态,请启动 NewActivity ,否则显示登录失败DialogToast

例如:

你的逻辑应该在这里开始新的活动,

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

        TextView result = (TextView) findViewById(R.id.tv_status);
        result.setText(response.toString());

    if(status.equals("Success!"))
     {
       Intent i = new Intent(getApplicationContext(), NextActivity.class);
       startActivity(i);    
     }
    else
     {
         // Code for Login failure 
     }
   }
    catch(Exception e){
   }

答案 1 :(得分:0)

我更喜欢从AsynTask类内部而不是从onCreate()内部进行Web服务调用,因为后台操作不应该影响UI线程。

什么是AsyncTask

AsyncTask可以正确,轻松地使用UI线程。该类允许执行后台操作并在UI线程上发布结果,而无需操纵线程和/或处理程序。

从AsyncTask创建一个类,并为主Activity类中的onPreExecute,onPostExecute,onProgressUpdate和doInBackground方法提供定义:

private class AsyncCallWS extends AsyncTask {
    @Override
    protected Void doInBackground(String... params) {
        //Call Web Method
        loginStatus = WebService.invokeLoginWS(editTextUsername,editTextPassword,"authenticateUser");
        return null;
    }

    @Override
    //Once WebService returns response
    protected void onPostExecute(Void result) {
        //Make Progress Bar invisible
        webservicePG.setVisibility(View.INVISIBLE);
        Intent intObj = new Intent(CheckLoginActivity.this,HomeActivity.class);
        //Error status is false
        if(!errored){
            //Based on Boolean value returned from WebService
            if(loginStatus){
                //Navigate to Home Screen
                startActivity(intObj);
            }else{
                //Set Error message
                statusTV.setText("Login Failed, try again");
            }
        //Error status is true  
        }else{
            statusTV.setText("Error occured in invoking webservice");
        }
        //Re-initialize Error Status to False
        }

    @Override
    //Make Progress Bar visible
    protected void onPreExecute() {
        webservicePG.setVisibility(View.VISIBLE);
    }

    @Override
    protected void onProgressUpdate(Void... values) {
    }
}   

}

调用AsyncTask的execute方法启动Web Service调用。

//Create instance for AsyncCallWS
AsyncCallWS task = new AsyncCallWS();
//Call execute 
task.execute();

答案 2 :(得分:0)

 This code is Beneficial for you
   btnsub.setOnClickListener(new View.OnClickListener() {
     public void onClick(View v) {
            // TODO Auto-generated method stub

            SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME1);        
             //Use this to add parameters
             request.addProperty("username",Username.getText().toString());
             request.addProperty("Password",password.getText().toString());

            //Declare the version of the SOAP request
            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
            envelope.setOutputSoapObject(request);
            envelope.dotNet = true;
            try {
                HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
                //this is the actual part that will call the webservice
                androidHttpTransport.call(SOAP_ACTION1, envelope);
                // Get the SoapResult from the envelope body.
                SoapObject result = (SoapObject)envelope.getResponse(); 
                Log.e("result", "responce"+result);
                SoapObject root = (SoapObject) result.getProperty(0);
                Log.e("root", "responce"+root);
                System.out.println("********Count : "+ root.getPropertyCount());
                //value=new ArrayList<Detailinfo>();
                 for (int i = 0; i < root.getPropertyCount(); i++) 
                  {
                  SoapObject root1 = (SoapObject) root.getProperty(i);
                  Log.e("root1", "responce"+root1);
                     Detailinfo info=new Detailinfo();

                     info.setResponseCode(root1.getProperty("ResponseCode").toString());
                     Log.e("code", ""+root1.getProperty("ResponseCode").toString());
                     info.setResponseMessage( root1.getProperty("ResponseMessage").toString());
                     Log.e("msg", ""+root1.getProperty("ResponseCode").toString());

                 if(st1==Integer.parseInt(root1.getProperty("ResponseCode").toString()))
                     {
                     SoapObject root2 = (SoapObject) root1.getProperty(2); 
                     info.setCustomerID( root2.getProperty("CustomerID").toString());
                     info.setCustomerNumber( root2.getProperty("CustomerNumber").toString());
                     info.setLoginID( root2.getProperty("LoginID").toString());
                     info.setName(root2.getProperty("Name").toString());
                     info.setProfileImage( root2.getProperty("ProfileImage").toString());
                     info.setMobile( root2.getProperty("MobileNo").toString());
                     info.setEmailID( root2.getProperty("EmailID").toString());
                     info.setAccountType( root2.getProperty("AccountType").toString());
                     Log.e("AccountType", "responce"+root2.getProperty("AccountType").toString());
                      //for maintain session 
                   session.createUserLoginSession(info.getCustomerID(),info.getName(),info.getMobile(),info.getEmailID(),info.getAccountType());
                    // value.add(info);
                   Log.e("session"," "+session.toString());
                     Intent inten=new Intent(getApplicationContext(),AccordionActivity.class);
                      startActivity(inten);
                  }
                 else
                 {

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