Click here to Skip to main content
15,881,600 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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);
        }
    }
}


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();
    		}

    		 
    	 }
    }
    
}


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
Posted
Updated 8-Apr-14 20:39pm
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900