纠结了好几天,终于成功实现了android端从服务端获取数据,走了很多弯路,所以在这儿分享出来,供新手学习一下。
实现过程很简单:打开vs2010 创建一个webservice 项目,实现方法,发布到iis上面,测试服务,然后建立android项目,实现android访问服务端,实现登陆注册功能。
先上传效果图:
开发环境:vs2010 ,sqlserver2008, android:eclipse
数据库:
打开sql server
新建数据库 :WcfTest(我这儿使用的以前的数据库,所以名字就没有改)
新建表:Login
字段就三个:id, UName, UPassword ,
OK,数据库就这么简单,搞定,下面来看看webservice。
-
服务端:
打开 vs2010 新建空的解决方案->添加->新建项->web服务(具体的创建webservice可以百度学习一下),
然后修改代码如下:
[WebMethod]
public string HelloWorld(string askStr)
{
//{"UName":"1","action":"login2","UPassword":"123"}
string _retStr = new JsonData("{ \"success\": \"false\", \"msg\":\"错误\"}").ToString();
try
{
JsonData jd = JsonMapper.ToObject(askStr);
int ss = jd.Count;
string _action = jd["action"].ToString();
switch (_action)
{
case "login":
_retStr = login(askStr);
break;
case "Register":
_retStr = Register(askStr);
break;
}
}
catch (Exception ex)
{
_retStr = new JsonData("{ \"success\": \"false\", \"msg\":\"" + ex.Message + "\"}").ToString();
}
return _retStr;
}
private string Register(string askStr)
{
JsonData jd = JsonMapper.ToObject(askStr);
int ss = jd.Count;
string UName = jd["UName"].ToString();
string UPassword = jd["UPassword"].ToString();
string sql = "select * from Login where UName='" + UName + "'";
DataTable dt = SqlDBHelper.ExecuteTable(DBConfig.getSqlserverDBConnString(), CommandType.Text, sql, null);
if (dt.Rows.Count > 0)
{
return "用户名已存在!";
}
else
{
string sql2 = "insert into Login values('" + UName + "','" + UPassword + "')";
SqlDBHelper.ExecuteTable(DBConfig.getSqlserverDBConnString(), CommandType.Text, sql2, null);
return "注册成功";
}
}
private string login(string askStr)
{
JsonData jd = JsonMapper.ToObject(askStr);
int ss = jd.Count;
string UName = jd["UName"].ToString();
string UPassword = jd["UPassword"].ToString();
string sql = "select * from Login where UName='" + UName + "'";
DataTable dt = SqlDBHelper.ExecuteTable(DBConfig.getSqlserverDBConnString(), CommandType.Text, sql, null);
List<Hashtable> data = new List<Hashtable>();
if (dt.Rows.Count > 0)
{
if (dt.Rows[0]["UPassword"].ToString().Equals(UPassword))
return "登陆成功";//
else
return "密码错误";
}
else
return "用户名不存在";
}
修改web.config 文件 :
<connectionStrings>
<add name="SqlDB" connectionString="server=DADI--20130924R;uid=sa;pwd=sasasa;database=WcfTest;" />
</connectionStrings>
到这里 webservice 项目已经创建完成了,然后搭到iis上面测试一下
-
Android 端:
新建一个android 项目
activity_main.xml代码:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:text="账号:" />
<EditText
android:id="@+id/account"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入账号" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:text="密码:" />
<EditText
android:id="@+id/pwd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入账号" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/reg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20sp"
android:hint="注册" />
<Button
android:id="@+id/login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100sp"
android:hint="登陆" />
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="@+id/layout"/>
</LinearLayout>
MainActivity 代码如下:
package com.example.webservicetest;
import org.json.JSONException;
import org.json.JSONStringer;
import com.example.webservicetest.R.layout;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private TextView accoun;//账户
private TextView pwd;//密码
private Button reg;//注册
private Button login;//登陆
private TextView layout;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
accoun=(TextView) findViewById(R.id.account);
pwd=(TextView) findViewById(R.id.pwd);
reg=(Button) findViewById(R.id.reg);
login=(Button) findViewById(R.id.login);
layout=(TextView) findViewById(R.id.layout);
reg.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
//{"UName":"1","action":"Register","UPassword":"1"} 组装成JSON
JSONStringer myString;
try {
myString = new JSONStringer().object();
myString.key("UName");
myString.value(accoun.getText().toString());
myString.key("UPassword");
myString.value(pwd.getText().toString());
myString.key("action");
myString.value("Register");
myString.endObject();
String l=myString.toString();
Log.d("myString", myString.toString());
String Retstr = WebserviceHelper.GetWebService("http://tempuri.org/",
"HelloWorld", "askStr", "http://192.168.140.1:7755/Service1.asmx?wsdl", l);
Log.d("this", Retstr);
// Looper.prepare();
//
// Toast.makeText(getApplicationContext(), Retstr, Toast.LENGTH_LONG).show();
//Looper.loop();
Intent intent = new Intent();
//在Intent对象当中添加一个键值对
intent.putExtra("testIntent", Retstr);
//设置Intent对象要启动的Activity
intent.setClass(MainActivity.this, Result.class);
//通过Intent对象启动另外一个Activity
startActivity(intent);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
});
login.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//new Thread(WCFTest).start();
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
/*String Retstr = WebserviceHelper.GetWebService("http://tempuri.org/",
"login", "UName","UPassword", "http://192.168.140.1:7755/Service1.asmx?wsdl", accoun.getText().toString(),pwd.getText().toString());
Log.d("this", Retstr);*/
JSONStringer myString;
try {
myString = new JSONStringer().object();
myString.key("UName");
myString.value(accoun.getText().toString());
myString.key("UPassword");
myString.value(pwd.getText().toString());
myString.key("action");
myString.value("login");
myString.endObject();
String l=myString.toString();
Log.d("myString", myString.toString());
String Retstr = WebserviceHelper.GetWebService("http://tempuri.org/",
"HelloWorld", "askStr", "http://192.168.140.1:7755/Service1.asmx?wsdl", l);
Log.d("this", Retstr);
// Looper.prepare();
//
// Toast.makeText(getApplicationContext(), Retstr, Toast.LENGTH_LONG).show();
//Looper.loop();
Intent intent = new Intent();
//在Intent对象当中添加一个键值对
intent.putExtra("testIntent", Retstr);
//设置Intent对象要启动的Activity
intent.setClass(MainActivity.this, Result.class);
//通过Intent对象启动另外一个Activity
startActivity(intent);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
});
}
}
新建一个WebserviceHelper类,(需要下载ksoap2-android-assembly-2.5.2-jar-with-dependencies.jar并添加包)
代码如下:
package com.example.webservicetest;
import java.io.IOException;
import java.net.ConnectException;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;
public class WebserviceHelper {
/**
*
* @param nameSpace
* @param methodName
* @param parameter
* @param url
* @param action
* @return
*/
/* public static String GetWebService(String nameSpace, String methodName, String parameter,
String parameter2,String url, String action,String action2) {
*/
public static String GetWebService(String nameSpace, String methodName, String parameter,
String url, String action) {
SoapObject soapObj = new SoapObject(nameSpace, methodName);
soapObj.addProperty(parameter, action);
//soapObj.addProperty(parameter2, action2);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.bodyOut = soapObj;
envelope.dotNet = true;
HttpTransportSE transport = new HttpTransportSE(url);
try {
/**
* 连接网络获取数据
*/
transport.call(nameSpace + methodName, envelope);
SoapObject soapReault = (SoapObject) envelope.bodyIn;
String result = soapReault.getProperty(0).toString();
return result;
} catch (SoapFault e) {
return e.getMessage();
} catch (ConnectException e) {
/**
* 无网络连接
*/
return "ConnectException";
} catch (IOException e) {
return e.getMessage();
} catch (XmlPullParserException e) {
return e.getMessage();
} catch (Exception e) {
return e.getMessage();
}
}
}
登陆注册成功后会调到另外一个活动,所以我再新建一个activity Result.java
activity_result.xml布局文件如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.webservicetest.Result" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView1"
/>
</RelativeLayout>
Result.java
代码如下
package com.example.webservicetest;
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class Result extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
Intent intent = getIntent();
//从Intent当中根据key取得value
String value = intent.getStringExtra("testIntent");
//根据控件的ID得到响应的控件对象
TextView myTextView = (TextView)findViewById(R.id.textView1);
//为控件设置Text值
myTextView.setText(value);
}
}