Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: WCF Android
Hello all,
 
I'm trying to consume WCF service in android client but I'm getting following error :
java.lang.string cannot be converted to jsonobject
 
here is my code :
 
Android :
package com.example.studentsapp;
 
import java.io.InputStreamReader;
import java.io.Reader;
 
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
 
import android.os.Bundle;
import android.app.Activity;
import android.view.*;
import android.widget.*;
import android.view.View.OnClickListener;
 
public class MainActivity extends Activity 
{
	private final static String srvc_uri = "http://101.63.53.242/StudentWcfServiceforAndroid/service1.svc/GetName/";
	private EditText idTxt;
	private Button btn;
	private TextView tv;
	
 
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        idTxt = (EditText) findViewById(R.id.editText1);
        btn = (Button) findViewById(R.id.button1);
        btn.setOnClickListener(new OnClickListener() 
        {
			@Override
			public void onClick(View v) 
			{
				// TODO Auto-generated method stub
				try
				{
					DefaultHttpClient client = new DefaultHttpClient();
			    	// http get request
			    	HttpGet request = new HttpGet(srvc_uri + idTxt.getText());
 
			    	// set the hedear to get the data in JSON format
			    	request.setHeader("Accept", "application/json");
			        request.setHeader("Content-type", "application/json");
 
			        //get the response
			        HttpResponse response = client.execute(request);
 
			        HttpEntity entity = response.getEntity();
 
			        //if entity contect lenght 0, means no students exist in the system with these code
			        if(entity.getContentLength() != 0) 
			        {
			        	// stream reader object
			        	Reader reader = new InputStreamReader(response.getEntity().getContent());
				        //create a buffer to fill if from reader
			        	char[] buffer = new char[(int) response.getEntity().getContentLength()];
				        //fill the buffer by the help of reader
			        	reader.read(buffer);
				        //close the reader streams
			        	reader.close();
 
			        	//for the student json object
				        JSONObject s =  new JSONObject(new String(buffer));
				        
				        //Toast.makeText(getApplicationContext(), s.getString("StudentName"), Toast.LENGTH_LONG).show();
				        tv.setText(s.getString("StudentName"));
			        }  
				}
				catch(Exception ex)
				{
						Toast.makeText(getApplicationContext(), ex.toString(), Toast.LENGTH_LONG).show();
				}
			}
		});
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
    {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    
}
 
WCF :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
 
namespace StudentWcfServiceforAndroid
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
    [ServiceContract]
    public interface IService1
    {
 
        [OperationContract]
        string GetData(int value);
 
        [OperationContract]
        CompositeType GetDataUsingDataContract(CompositeType composite);
 
        // TODO: Add your service operations here

    }
 
    [ServiceContract]
    public interface IstudentInfo 
    {
        [OperationContract]
        [WebGet(UriTemplate = "GetName/{id}",
            BodyStyle = WebMessageBodyStyle.WrappedRequest,
            ResponseFormat = WebMessageFormat.Json,
            RequestFormat = WebMessageFormat.Json)]
        Student GetStudentName(int studentID);
    }
 
    public class StudentInfo : IstudentInfo 
    {
        public Student GetStudentName(int studentID)
        {
            Student studs = GetStuds().Where(s => s.StudentID == studentID).FirstOrDefault();
            return studs;
        }
 
        private List<Student> GetStuds()
        {
            return new List<Student>
            {
                new Student
                {StudentID=1, StudentName="AAA"},
                new Student
                {StudentID=2, StudentName="BBB"}
            };
        }
    }
 
    // Use a data contract as illustrated in the sample below to add composite types to service operations.
    [DataContract]
    public class CompositeType
    {
        bool boolValue = true;
        string stringValue = "Hello ";
 
        [DataMember]
        public bool BoolValue
        {
            get { return boolValue; }
            set { boolValue = value; }
        }
 
        [DataMember]
        public string StringValue
        {
            get { return stringValue; }
            set { stringValue = value; }
        }
    }
 
    [DataContract]
    public class Student
    {
        public int StudentID
        { get; set; }
 
        public string StudentName
        { get; set; }
    }
 
}
 
Web.config :
<?xml version="1.0"?>
<configuration>
 
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
 
    <standardEndpoints>
      <webHttpEndpoint>
        <standardEndpoint helpEnabled="true" automaticFormatSelectionEnabled="true" />
      </webHttpEndpoint>
    </standardEndpoints>
    <services>
      <service name="StudentWcfServiceforAndroid.StudentInfo">
        <endpoint kind="webHttpEndpoint" contract="StudentWcfServiceforAndroid.IStudentInfo" />
      </service>
    </services>
 
  </system.serviceModel>
 <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
 
</configuration>
 
Help me to get rid of this.
 
Now I've solved this problem but I'm neither getting any error nor output !!
Posted 2-Feb-13 22:45pm
Edited 5-Feb-13 19:30pm
v3
Comments
Sandeep Mewara at 3-Feb-13 4:14am
   
You have not shared the string that failed to convert. Error stack trace must be sharing the 'value' that fails conversion.
Krunal Rohit at 3-Feb-13 4:40am
   
JSONObject s = new JSONObject(new String(buffer));
Sandeep Mewara at 3-Feb-13 4:54am
   
What's this? You are sharing a line of code when I asked you the full stack trace message.
Krunal Rohit at 3-Feb-13 5:03am
   
I'm not printing message in stack race.! See code!

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

Maybe I'm missing something but shouldn't the line be
 
JSONObject s =  new JSONObject(buffer);
 
/Darren
  Permalink  
Comments
Krunal Rohit at 7-Feb-13 4:56am
   
Let me see if it could help !!
Krunal Rohit at 7-Feb-13 4:57am
   
Error !!!!
Darren_vms at 8-Feb-13 10:41am
   
ok I tried, good luck

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

  Print Answers RSS
0 DamithSL 265
1 CPallini 235
2 OriginalGriff 233
3 Maciej Los 175
4 George Jonsson 170
0 OriginalGriff 5,305
1 DamithSL 4,382
2 Maciej Los 3,760
3 Kornfeld Eliyahu Peter 3,470
4 Sergey Alexandrovich Kryukov 2,901


Advertise | Privacy | Mobile
Web01 | 2.8.141216.1 | Last Updated 7 Feb 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100