我正在尝试在 android 中创建一个应用程序,以通过 Web 服务将数据插入 sql server. [英] I am trying to create an app in android to insert data into sql server through a web service.

查看:21
本文介绍了我正在尝试在 android 中创建一个应用程序,以通过 Web 服务将数据插入 sql server.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我是 android 新手,我正在尝试通过 web 服务从 android 保存一些数据到 sql server 中.我在 android 和 webservice 中创建了一个示例应用程序.我收到一个异常,但我无法解决 java 中的异常.这是我正在使用的代码.

Hi guys I am new in android here m trying to save some data in sql server from android through a webservice. I have created a sample app in android and a webservice. I am getting an exception but i am not able to resolve the exception in java. Here is the code which i am using.

这是我正在使用的网络服务.它工作正常.

This is the webservice which i am using. Its working fine.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data.SqlClient;
using System.Runtime.Serialization;

namespace Common.Services
{
    /// <summary>
    /// Summary description for AndroidService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class AndroidService : System.Web.Services.WebService
    {

        [WebMethod]
        public string InsertUserDetails(UserDetails userInfo)
        {
            string strMessage;
            SqlConnection con = new SqlConnection("Data Source=106.205.11.220;Initial Catalog=mydb;User ID=usernm;Password=passwd");
            con.Open();
            SqlCommand cmd = new SqlCommand("insert INTO android_Sample (SampleName,SampleValue,AddDate) VALUES(@Name,@Value,dateadd(minute,330,getdate()))", con);
            cmd.Parameters.AddWithValue("@Name", userInfo.UserName);
            cmd.Parameters.AddWithValue("@Value", userInfo.UserAge);
            int result = cmd.ExecuteNonQuery();
            if (result == 1)
            {
                strMessage = userInfo.UserName + " Details inserted successfully";
            }
            else
            {
                strMessage = userInfo.UserName + " Details not inserted successfully";
            }
            con.Close();
            return strMessage;
        }

        public class UserDetails
        {
            string name = string.Empty;
            string age = string.Empty;

            [DataMember]
            public string UserName
            {
                get { return name; }
                set { name = value; }
            }

            [DataMember]
            public string UserAge
            {
                get { return age; }
                set { age = value; }
            }

        }
    }
}

这是 MainActivity.java 文件.在这里我得到一个例外

This is the MainActivity.java file. here i am getting an exception

    package tecs.example.wsd;

    import android.os.Bundle;
    import android.app.Activity;
    import android.view.Menu;
    import org.ksoap2.SoapEnvelope;
    import org.ksoap2.SoapFault;
    import org.ksoap2.serialization.PropertyInfo;
    import org.ksoap2.serialization.SoapObject;
    import org.ksoap2.serialization.SoapSerializationEnvelope;
    import org.ksoap2.transport.HttpTransportSE;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;

    public class MainActivity extends Activity 
    {
         /** Called when the activity is first created. */
            private static String SOAP_ACTION = "http://tempuri.org/InsertUserDetails";
            private static String NAMESPACE = "http://tempuri.org/";
            private static String METHOD_NAME = "InsertUserDetails";

            private static String URL = "http://192.168.1.137/common.ui/Services/AndroidService.asmx";

            Button btnSend;
            EditText txtName, txtVal;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            btnSend=(Button)findViewById(R.id.btnSend);
            txtName=(EditText)findViewById(R.id.txtText);
            txtVal=(EditText)findViewById(R.id.txtValue);

            btnSend.setOnClickListener(new View.OnClickListener() 
            {

                @Override
                public void onClick(View v) 
                {
                    //Initialize soap request + add parameters
                    SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);        
                    PropertyInfo pi=new PropertyInfo();
                    pi.setName("UserName");
                    pi.setValue(txtName.getText().toString());
                    pi.setType(String.class);
                    request.addProperty(pi);
                    pi=new PropertyInfo();
                    pi.setName("UserAge");
                    pi.setValue(txtVal.getText().toString());
                    pi.setType(String.class);
                    request.addProperty(pi);
                    //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_ACTION, envelope);
// Get the SoapResult from the envelope body.
                            SoapObject result = (SoapObject)envelope.bodyIn;



                            if(result != null)
                            {


                                Toast.makeText(getBaseContext(), result.getProperty(0).toString(), Toast.LENGTH_SHORT).show();
                                txtName.setText("");
                                txtVal.setText("");

                            }
                            else
                            {
                                Toast.makeText(getApplicationContext(), "No Response",Toast.LENGTH_LONG).show();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            }

            @Override
            public boolean onCreateOptionsMenu(Menu menu) {
                // Inflate the menu; this adds items to the action bar if it is present.
                getMenuInflater().inflate(R.menu.main, menu);
                return true;
            }

        }

我收到此异常

java.lang.ClassCastException: org.ksoap2.SoapFault

java.lang.ClassCastException: org.ksoap2.SoapFault

在这条线上

// Get the SoapResult from the envelope body.
SoapObject result = (SoapObject)envelope.bodyIn;

这是我的清单文件代码

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="tecs.example.wsd"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="10"
        android:targetSdkVersion="17" />
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="tecs.example.wsd.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

这是我的布局文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >



    <EditText
        android:id="@+id/txtText"
        android:layout_width="fill_parent"
        android:layout_height="150dp"
        android:gravity="top"
        android:inputType="textMultiLine"
        android:hint="@string/Text_Hint" />

    <EditText 
        android:id="@+id/txtValue"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="number"
        android:hint="@string/Value_Hint" />

    <Button
        android:id="@+id/btnSend"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/btnSend_text" />

</LinearLayout>

这是我的字符串值文件

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">WSD</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string name="Text_Hint">Enter Text</string>
    <string name="Value_Hint">Enter Value</string>
    <string name="btnSend_text">Send</string>
</resources>

谁能帮我解决这个问题.怎么了?哪个是正确的方法?如何解决此错误?

Can anyone help me with this. what is wrong? which is the right method for it? How to resolve this error?

推荐答案

我用于 .Net Web Service 的示例代码

Sample code Which I used for .Net Web Service

    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    envelope.dotNet = true;
    envelope.setOutputSoapObject(webRequest);
    HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);


    androidHttpTransport.call(SOAP_ACTION + METHOD_NAME, envelope);
    Log.d("CheckLogin-SOAP ACTION", SOAP_ACTION + METHOD_NAME);
    SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
    Log.d("CheckLogin - Response", response.toString());

    status= Boolean.valueOf(response.toString());

这篇关于我正在尝试在 android 中创建一个应用程序,以通过 Web 服务将数据插入 sql server.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆