Java 如何将参数传递给webservice并在listview中获取json数据
嗨(安道尔岛的新生) 我正在开发一个android应用程序,它将使用webservice,它应该从用户那里接受1个参数,并基于该参数值从DB(sql server 2008)获取数据,并将其绑定到android:LISTVIEW 如果不使用参数,我的android应用程序工作正常。但是当我更改webserservice以接受参数并在android中调用它时,它不会显示基于给定值的结果,而是显示所有值 这是我的Web服务代码Java 如何将参数传递给webservice并在listview中获取json数据,java,android,web-services,Java,Android,Web Services,嗨(安道尔岛的新生) 我正在开发一个android应用程序,它将使用webservice,它应该从用户那里接受1个参数,并基于该参数值从DB(sql server 2008)获取数据,并将其绑定到android:LISTVIEW 如果不使用参数,我的android应用程序工作正常。但是当我更改webserservice以接受参数并在android中调用它时,它不会显示基于给定值的结果,而是显示所有值 这是我的Web服务代码 using System; using System.Collectio
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.ComponentModel;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[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 JService : System.Web.Services.WebService
{
public JService () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public void Cargonet(string jobno)
{
try
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["NSConstr"].ToString());
SqlCommand cmd = new SqlCommand();
//cmd.CommandText = "SELECT id,name,salary,country,city FROM EMaster where age = '" + jobno + "'";
cmd.CommandText = "SELECT [Id] as Id,[Status] as status ,[DateTime] as DateTime FROM [Attendance].[dbo].[cargo] WHERE JobNo= '" + jobno + "' ";
DataSet ds = new DataSet();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.SelectCommand.Connection = con;
da.Fill(dt);
con.Close();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row = null;
foreach (DataRow rs in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, rs[col].ToString().Trim());
}
rows.Add(row);
}
this.Context.Response.ContentType = "application/json; charset=utf-8";
this.Context.Response.Write(serializer.Serialize(new { Cargo = rows }));
}
catch (Exception ex)
{
//return errmsg(ex);
}
}
}
以下是我的android代码(Main.java):
package com.example.cargotracking;
导入java.util.ArrayList;
导入java.util.HashMap;
导入java.util.List;
导入org.apache.http.message.BasicNameValuePair;
导入org.json.JSONArray;
导入org.json.JSONException;
导入org.json.JSONObject;
导入android.app.Activity;
导入android.app.ProgressDialog;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.view.view;
导入android.widget.AdapterView;
导入android.widget.Button;
导入android.widget.EditText;
导入android.widget.ListAdapter;
导入android.widget.ListView;
导入android.widget.simpledapter;
导入android.widget.TextView;
导入android.widget.Toast;
公共类MainActivity扩展了活动{
列表视图列表;
文本视图Id;
文本视图状态;
文本视图日期时间;
按钮Btngetdata;
字符串JobNo;
编辑文本编辑文本1;
ArrayList CargoTracklist=新建ArrayList();
//获取JSON数组的URL
专用静态字符串url=”http://ip/testing/TrackId.asmx/Cargonet";
//JSON节点名称
专用静态最终字符串标记\u CargoTrack=“Cargo”;
私有静态最终字符串标记\u Id=“Id”;
私有静态最终字符串标记_Status=“Status”;
私有静态最终字符串标记_DateTime=“DateTime”;
JSONArray Cargo=null;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CargoTracklist=新的ArrayList();
Btngetdata=(按钮)findViewById(R.id.button1);
Btngetdata.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图){
新建JSONParse().execute();
}
});
}
私有类JSONParse扩展了异步任务{
私人对话;
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
状态=(TextView)findViewById(R.id.textView2);
Id=(TextView)findViewById(R.Id.textView1);
DateTime=(TextView)findViewById(R.id.textView3);
pDialog=新建进度对话框(MainActivity.this);
setMessage(“获取数据…”);
pDialog.setUndeterminate(假);
pDialog.setCancelable(真);
pDialog.show();
}
@凌驾
受保护的JSONObject doInBackground(字符串…args){
JSONParser jParser=新的JSONParser();
List params=new ArrayList();
//List params=new ArrayList();
参数添加(新的BasicNameValuePair(“JobNo”、“01”);
//从URL获取JSON
JSONObject json=jParser.getJSONFromUrl(url,参数);
返回json;
}
@凌驾
受保护的void onPostExecute(JSONObject json){
pDialog.disclose();
试一试{
//从URL获取JSON数组
Cargo=json.getJSONArray(TAG_CargoTrack);
对于(int i=0;ivalue
HashMap=newHashMap();
地图放置(标签状态、状态);
地图放置(标签标识,标识);
map.put(TAG_DateTime,DateTime);
货物跟踪列表。添加(地图);
列表=(ListView)findViewById(R.id.listView1);
ListAdapter=new SimpleAdapter(MainActivity.this、CargoTracklist、,
R.layout.listview,
新字符串[]{TAG_Status,TAG_Id,TAG_DateTime},new int[]{
R.id.textView2、R.id.textView1、R.id.textView3});
list.setAdapter(适配器);
list.setOnItemClickListener(新的AdapterView.OnItemClickListener(){
@凌驾
public void onItemClick(AdapterView父级、视图、,
内部位置,长id){
Toast.makeText(MainActivity.this,“您在“+CargoTracklist.get(+position.get”(“Id”)、Toast.LENGTH_SHORT.show()处单击过”;
}
});
}
}捕获(JSONException e){
e、 printStackTrace();
}
}
}
}
以下是我的json解析器代码:
package com.example.cargotracking;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
//public JSONObject getJSONFromUrl(String url, List params) {
public JSONObject getJSONFromUrl(String url, List<BasicNameValuePair> params) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
package com.example.cargotracking;
导入java.io.BufferedReader;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.InputStreamReader;
导入java.io.UnsupportedEncodingException;
导入java.util.List;
导入org.apache.http.HttpEntity;
导入org.apache.http.HttpResponse;
导入org.apache.http.client.ClientProtocolException;
导入org.apache.http.client.entity.UrlEncodedFormEntity;
导入org.apache.http.client.methods.HttpPost;
导入org.apache.http.impl.client.DefaultHttpClient;
导入org.apache.http.message.BasicNameValuePair;
导入org.json.JSONException;
导入组织
package com.example.cargotracking;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
//public JSONObject getJSONFromUrl(String url, List params) {
public JSONObject getJSONFromUrl(String url, List<BasicNameValuePair> params) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}