Click here to Skip to main content
15,880,796 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
This is my asmx.service

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.Runtime.Serialization.Json;
using System.Web.Script.Services;
using System.Web.Script.Serialization;
using System.ComponentModel;

[WebService(Namespace = "http://surveyservices.sanraysinfotech.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
//[ScriptService]
// 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 Service : System.Web.Services.WebService
{
    List<wilaya> Wilayalist = new List<wilaya>();
    List<moughata> Moughataalist = new List<moughata>();
    List<commune> Communelist = new List<commune>();
    public Service () {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }

    [WebMethod]
    public string HelloWorld() {
        return "Hello World";
    }

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json,UseHttpGet=false)]
    public String GetWilaya()
    {
        // getting connection string
       
        string conStr = WebConfigurationManager.ConnectionStrings["SQLDbConnection"].ConnectionString;
        DataTable dt = new DataTable();
        SqlDataReader dr = null;
        // Creating Sql Connection
        using (SqlConnection conn = new SqlConnection(conStr))
        {
            // Creating insert statement
            string sql = string.Format(@"Select * from [WilayaMast]");
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandText = sql;
            cmd.CommandType = CommandType.Text;
            conn.Open();

            dr = cmd.ExecuteReader();
            dt.Load(dr);
            conn.Close();
            cmd = null;
        }

        int countRow = dt.Rows.Count;

        foreach (DataRow drEmp in dt.Rows)
        {
            Wilaya objwilaya = new Wilaya();
            objwilaya.WCode = Convert.ToInt32(drEmp["Wcode"].ToString());
            objwilaya.WName = drEmp["WName"].ToString();
            objwilaya.WID = drEmp["WID"].ToString();
            Wilayalist.Add(objwilaya);
        }
        return new JavaScriptSerializer().Serialize(Wilayalist);
        
    }

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public String GetCommune()
    {
        // getting connection string

        string conStr = WebConfigurationManager.ConnectionStrings["SQLDbConnection"].ConnectionString;
        DataTable dt = new DataTable();
        SqlDataReader dr = null;
        // Creating Sql Connection
        using (SqlConnection conn = new SqlConnection(conStr))
        {
            // Creating insert statement
            string sql = string.Format(@"Select * from [CommuneMast]");
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandText = sql;
            cmd.CommandType = CommandType.Text;
            conn.Open();

            dr = cmd.ExecuteReader();
            dt.Load(dr);
            conn.Close();
            cmd = null;
        }

        int countRow = dt.Rows.Count;

        foreach (DataRow drcommune in dt.Rows)
        {
            Commune objcommune = new Commune();
            objcommune.CCode = Convert.ToInt32(drcommune["CCode"].ToString());
            objcommune.CName = drcommune["CName"].ToString();
            objcommune.CID = drcommune["CID"].ToString();
            objcommune.MCode = Convert.ToInt32(drcommune["MCode"]);
            Communelist.Add(objcommune);
        }
        return new JavaScriptSerializer().Serialize(Communelist);
    }

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    //public List<moughata> GetMoughata()
    public String  GetMoughata()
    {
        // getting connection string

        string conStr = WebConfigurationManager.ConnectionStrings["SQLDbConnection"].ConnectionString;
        DataTable dt = new DataTable();
        SqlDataReader dr = null;
        // Creating Sql Connection
        using (SqlConnection conn = new SqlConnection(conStr))
        {
            // Creating insert statement
            string sql = string.Format(@"Select * from [MoughataaMast]");
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandText = sql;
            cmd.CommandType = CommandType.Text;
            conn.Open();

            dr = cmd.ExecuteReader();
            dt.Load(dr);
            conn.Close();
            cmd = null;
        }

        int countRow = dt.Rows.Count;

        foreach (DataRow drmoughata in dt.Rows)
        {
            Moughata objmoughata = new Moughata();
            objmoughata.MCode = Convert.ToInt32(drmoughata["MCode"].ToString());
            objmoughata.MID = drmoughata["MID"].ToString();
            objmoughata.WCode = Convert.ToInt32(drmoughata["WCode"].ToString());
            objmoughata.MName = drmoughata["MName"].ToString();
            Moughataalist.Add(objmoughata);
        }
        return new JavaScriptSerializer().Serialize(Moughataalist);
        //return Moughataalist;
    }

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public int Add(int a, int b)
    {
        return a + b;
    } 
}

[Serializable]
public class Wilaya
{
    public int WCode { get; set; }
    public string WName { get; set; }
    public string WID { get; set; }
    
}
[Serializable]
public class Commune
{
    public int CCode { get; set; }
    public int MCode { get; set; }
    public string CName { get; set; }
    public string CID { get; set; }
}
[Serializable]
public class Moughata
{
    public int MCode { get; set; }
    public int WCode { get; set; }
    public string MName { get; set; }
    public string MID { get; set; }

}

This is my android code
Java
public class MainActivity extends Activity {

    SQLiteDB sqlite_obj;
	
	Button get, store;
	List<string> list1, list2;
	
	InputStream is = null;
 
	String ip = "http://surveyservices.sanraysinfotech.com/Service.asmx/GetWilaya";
	String line = null;
	String result = null;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
        sqlite_obj = new SQLiteDB(MainActivity.this);
		
		get = (Button) findViewById(R.id.button1);
		store = (Button) findViewById(R.id.button2);
		
		get.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				
				webservice();
				Toast.makeText(getBaseContext(), "Success : Webservice Call", Toast.LENGTH_SHORT).show();
			}			
		});
		
		store.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				
				sqlite();
				Toast.makeText(getBaseContext(), "Stored in SQLite DB", Toast.LENGTH_SHORT).show();
			}
		});
    }


private void webservice() {
		// TODO Auto-generated method stub
		
		try {
			HttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(ip);
			httpPost.addHeader("Content-Type","application/json;charset=utf-8");
			HttpResponse response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();
		}
		catch (Exception e) {
			Log.e("Webservice 1", e.toString());
		}
		try {
			
			BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
			StringBuilder sb = new StringBuilder();
			
			while((line = reader.readLine()) != null) {
				 
				sb.append(line +"\n");
			}
			
			is.close();
			result = sb.toString();			
		}
		catch (Exception e) {
			Log.e("Webservice 2", e.toString());
		}
		try {
			
			JSONArray ja = new JSONArray(result);
			JSONObject jo = null;
			
			list1 = new ArrayList<string>();
			list2 = new ArrayList<string>();
			
			for(int i=0; i<ja.length();>				
				jo = ja.getJSONObject(i);
				list1.add(jo.getString("id"));
				list2.add(jo.getString("uname"));
			}			
		}catch (Exception e) {
			Log.e("Webservice 3", e.toString());
		}
	}

when i run this i got an error

 org.json.JSONException: Value {"d":"[{\"WCode\":0,\"WName\":\"Select\",\"WID\":\"0\"},{\"WCode\":1,\"WName\":\"El Hodh Ech Charghi\",\"WID\":\"1\"},{\"WCode\":2,\"WName\":\"El Hodh El Gharbi\",\"WID\":\"2\"},{\"WCode\":3,\"WName\":\"Assaba\",\"WID\":\"3\"},{\"WCode\":4,\"WName\":\"Gorgol\",\"WID\":\"4\"},{\"WCode\":5,\"WName\":\"Brakna           \",\"WID\":\"5\"},{\"WCode\":6,\"WName\":\"Trarza\",\"WID\":\"6\"},{\"WCode\":7,\"WName\":\"Adrar\",\"WID\":\"7\"},{\"WCode\":8,\"WName\":\"Dakhlet Nouadhibou\",\"WID\":\"8\"},{\"WCode\":9,\"WName\":\"Tiris Zemmour\",\"WID\":\"11\"},{\"WCode\":10,\"WName\":\"Inchiri\",\"WID\":\"12\"},{\"WCode\":11,\"WName\":\"Tagant\",\"WID\":\"9\"},{\"WCode\":12,\"WName\":\"Guidimagha\",\"WID\":\"10\"},{\"WCode\":13,\"WName\":\"Nouakchott\",\"WID\":\"13\"}]"} of type org.json.JSONObject cannot be converted to JSONArray
Posted
Updated 24-Jan-15 13:00pm
v2
Comments
Kornfeld Eliyahu Peter 25-Jan-15 4:35am    
The error is clear! You try to convert a single JSON object to an array! It can not be done! Why do you do that? Check your logic!
Sandip Paul 491984 25-Jan-15 5:19am    
can you tell me how to resolve this?
Kornfeld Eliyahu Peter 25-Jan-15 6:48am    
Not really, as I do not know why at the first place you tried to convert JSOn to JSON array...
What the value of 'result' at this pint: JSONArray ja = new JSONArray(result);?
Sandip Paul 491984 25-Jan-15 7:15am    
Actually the above android code woked for php so i just change the url to .asmx web service.i am new to android my aim is sync data from sqlite to remote ms sql server by using .asmx web service.
This is my web service
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.Runtime.Serialization.Json;
using System.Web.Script.Services;
using System.Web.Script.Serialization;
using System.ComponentModel;

[WebService(Namespace = "http://surveyservices.sanraysinfotech.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
//[ScriptService]
// 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 Service : System.Web.Services.WebService
{
List<wilaya> Wilayalist = new List<wilaya>();
List<moughata> Moughataalist = new List<moughata>();
List<commune> Communelist = new List<commune>();

[WebMethod]
public string HelloWorld() {
return "Hello World";
}

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public String GetWilaya()
{
string conStr = WebConfigurationManager.ConnectionStrings["SQLDbConnection"].ConnectionString;
DataTable dt = new DataTable();
SqlDataReader dr = null;
using (SqlConnection conn = new SqlConnection(conStr))
{
string sql = string.Format(@"Select * from [WilayaMast]");
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = sql;
cmd.CommandType = CommandType.Text;
conn.Open();

dr = cmd.ExecuteReader();
dt.Load(dr);
conn.Close();
cmd = null;
}

int countRow = dt.Rows.Count;

foreach (DataRow drEmp in dt.Rows)
{
Wilaya objwilaya = new Wilaya();
objwilaya.WCode = Convert.ToInt32(drEmp["Wcode"].ToString());
objwilaya.WName = drEmp["WName"].ToString();
objwilaya.WID = drEmp["WID"].ToString();
Wilayalist.Add(objwilaya);
}
return new JavaScriptSerializer().Serialize(Wilayalist);

}
}

[Serializable]
public class Wilaya
{
public int WCode { get; set; }
public string WName { get; set; }
public string WID { get; set; }

}
and the ouput is
<string>[{"WCode":0,"WName":"Select","WID":"0"},{"WCode":1,"WName":"El Hodh Ech Charghi","WID":"1"},{"WCode":2,"WName":"El Hodh El Gharbi","WID":"2"},{"WCode":3,"WName":"Assaba","WID":"3"},{"WCode":4,"WName":"Gorgol","WID":"4"},{"WCode":5,"WName":"Brakna ","WID":"5"},{"WCode":6,"WName":"Trarza","WID":"6"},{"WCode":7,"WName":"Adrar","WID":"7"},{"WCode":8,"WName":"Dakhlet Nouadhibou","WID":"8"},{"WCode":9,"WName":"Tiris Zemmour","WID":"11"},{"WCode":10,"WName":"Inchiri","WID":"12"},{"WCode":11,"WName":"Tagant","WID":"9"},{"WCode":12,"WName":"Guidimagha","WID":"10"},{"WCode":13,"WName":"Nouakchott","WID":"13"}]

please help me to sort out my prob

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