Reputation:
I have the following code in a WCF Service that returns a string, and I’m trying to consume it in an Android app.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace HelloService
{
public class HelloService : IHelloService
{
public string SayHello()
{
return "Bonjuor Android from WCF Service";
}
}
}
I have two problems,
1, I have no idea if I’m even close with the Java due to the try catch blocks. If I have them in the code the app works but doesn’t display the text in the toast or text view, and if I leave the try catch blocks out Eclipse tell me to fix the problem, add a try catch block…lol.
And 2, I have no idea what I’m doing.
@Override
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.contacts);
try
{
DefaultHttpClient httpClient = new DefaultHttpClient();
URI uri = new URI("http://www.themorningtonpeninsula.com/HelloService/HelloService.svc");
HttpGet httpget = new HttpGet(uri + "/SayHello");
httpget.setHeader("Accept", "application/json");
httpget.setHeader("Content-type", "application/json; charset=utf-8");
HttpResponse response = httpClient.execute(httpget);
HttpEntity responseEntity = response.getEntity();
long intCount = responseEntity.getContentLength();
char[] buffer = new char[(int)intCount];
InputStream stream = responseEntity.getContent();
InputStreamReader reader = new InputStreamReader(stream, "UTF-8");
try
{
reader.read(buffer);
String str = new String(buffer);
TextView thetext = new TextView(this);
thetext.setText(str);
setContentView(thetext);
Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
}
catch (IOException e)
{
e.printStackTrace();
}
stream.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Can someone please have a look at the code and let me know if I’m even close, or even better point me too, or post some code that does work???
Upvotes: 3
Views: 6598
Reputation: 1103
I think you should use another Thread to do Networking task and also you can use runOnUiThread()
method in order to do the UI updation like displaying your Toast, etc.
Upvotes: 0
Reputation:
All fixed, the Java code works fine, the problem was my WCF Service needed work. It wasn’t passing back correctly formatted JSON objects. So I went back and and found a great tutorial simple and to the point. I must have completed 10 tutorials before finding this one. Pat on the back for the author.
http://www.codeproject.com/KB/WCF/RestServiceAPI.aspx
Cheers,
Mike.
Upvotes: 3