如何将参数传递给webservice并在listview中获取json数据 [英] How do I pass parameter to webservice and get json datas in listview

查看:76
本文介绍了如何将参数传递给webservice并在listview中获取json数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨(更新鲜到andorid)



我正在开发一个Android应用程序,它将使用webservice,它应该接受来自用户的1个参数并基于从DB(sql server 2008)获取值并将其绑定到android:LISTVIEW。



不使用参数我的android应用程序工作正常。但是当我改变我的webserservice接受参数并在android中调用它不显示。



这是我的网络服务代码;



Hi (fresher to andorid)

I'm developing an android application which will use the webservice which should accept 1 parameter from the user and based on that the value is fetched from DB(sql server 2008) and bind that to android:LISTVIEW.

Without using the parameter my android application is working fine.But when i altered my webserservice to accept parameter and call it in android it is not displaying.

Here is my webservice code;

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代码:



Here is my android code:

package com.example.cargotracking;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;






public class MainActivity extends Activity {
	ListView list;
	
	TextView Id;
	TextView Status;
	TextView DateTime;
	Button Btngetdata;
	String JobNo;
	EditText editText1;
	ArrayList<HashMap<String, String>> CargoTracklist = new ArrayList<HashMap<String, String>>();
	
	//URL to get JSON Array
	private static String url = "http://ip/testing/TrackId.asmx/Cargonet";
	
	//JSON Node Names 
	private static final String TAG_CargoTrack = "Cargo";
	private static final String TAG_Id = "Id";
	private static final String TAG_Status = "Status";
	
	private static final String TAG_DateTime = "DateTime";
	
	JSONArray Cargo = null;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
      
        setContentView(R.layout.activity_main);
        CargoTracklist = new ArrayList<HashMap<String, String>>();

        
        
        Btngetdata = (Button)findViewById(R.id.button1);
        Btngetdata.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View view) {
		         new JSONParse().execute();

				
			}
		});
        
        
    }


    
    private class JSONParse extends AsyncTask<String, String, JSONObject> {
    	 private ProgressDialog pDialog;
    	@Override
        protected void onPreExecute() {
            super.onPreExecute();
             Status = (TextView)findViewById(R.id.textView2);
			 Id= (TextView)findViewById(R.id.textView1);
			 DateTime = (TextView)findViewById(R.id.textView3);
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Getting Data ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
            
            
            
    	}
    	
    	@Override
        protected JSONObject doInBackground(String... args) {
    		
    		JSONParser jParser = new JSONParser();
    		
    		 List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
    		// List params = new ArrayList();
    		  params.add(new BasicNameValuePair("JobNo","01"));

    		// Getting JSON from URL
    		JSONObject json = jParser.getJSONFromUrl(url,params);
    		return json;
    	}
    	 @Override
         protected void onPostExecute(JSONObject json) {
    		 pDialog.dismiss();
    		 try {
    				// Getting JSON Array from URL
    				Cargo = json.getJSONArray(TAG_CargoTrack);
    				for(int i = 0; i < Cargo.length(); i++){
    				JSONObject c = Cargo.getJSONObject(i);
    				
    				// Storing  JSON item in a Variable
    				String Status = c.getString(TAG_Status);
    				String Id = c.getString(TAG_Id);
    				String DateTime = c.getString(TAG_DateTime);
    				
    			
    				
    				
    				// Adding value HashMap key => value
    				

    				HashMap<String, String> map = new HashMap<String, String>();

    				map.put(TAG_Status, Status);
    				map.put(TAG_Id, Id);
    				map.put(TAG_DateTime, DateTime);
    				
    				CargoTracklist.add(map);
    				list=(ListView)findViewById(R.id.listView1);
    				
    				
    				
    		        
    				
    				ListAdapter adapter = new SimpleAdapter(MainActivity.this, CargoTracklist,
    						R.layout.listview,
    						new String[] { TAG_Status,TAG_Id, TAG_DateTime }, new int[] {
    								R.id.textView2,R.id.textView1, R.id.textView3});

    				list.setAdapter(adapter);
    				list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

    		            @Override
    		            public void onItemClick(AdapterView<?> parent, View view,
    		                                    int position, long id) {
    		                Toast.makeText(MainActivity.this, "You Clicked at "+CargoTracklist.get(+position).get("Id"), Toast.LENGTH_SHORT).show();

    		            }
    		        });

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

    		 
    	 }
    }
    
}





这里是我的JsonParser代码:





here is my JsonParser code:

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;

	}
}









请帮我解决这个问题。



提前致谢





please help me to resolve this.

Thanks in advance

推荐答案

这篇关于如何将参数传递给webservice并在listview中获取json数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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