Android--SQL Server Connectivity error - android

I'm new to the android but now days done much more coding in Android. Now I have a doubt. I created android database application using Android and SQL Lte. But SQL Lite is client site database. But now my requirement is,I want a database like SQL Server,so that I connect my application to SQL Server. So suppose,consider and example,I know about WCF. I create a WCF service which have a function just like:
I hosted WCF on IIS because android does not response localhost,so i hosted WCF on IIS
Public string check(string username,string password)
{
SQLConnection con=new SQLConnection("Data Source=.;Database=test;Integrated Security=true");
SQLDataAdapeter ad=new SQLDataAdapter("select * from table where usrename='"+username+"'and password='"+password+"'");
Dataset ds=new Dataset();
ad.fill(ds,"table");
if(ds.Tables[0].Rows.Count>0)
{
return "true";
}
else
{
return "false";
}
}
I hosted WCF in my local host so that I can use this service in My Android Application coding.
just like:
HttpGet httpGet=new HttpGet("http://192.168.1.111:8083/Service1.svc/checkLogin?username="+UserName+"&password="+Password);
//Get the response
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
InputStream stream=httpEntity.getContent();
However here I'm not getting any httpEntity though the code is correct.
I take this entity and want to convert it into string by using function like:
public static String convertStreamToString(InputStream is)
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
however,it does not return any string value,the debugger goes on catch point.
So what can I do so that i'll get result in string format from my WCF?

Based on above code, I am not sure how do you put mobile client app, WCF and SQL Server in perspective. The basic design is that WCF service will internally talk to SQL Azure and collect data for your. You mobile client will just connect to WCF service at exposed method and the method will pass the data to mobile client. I do not see that architecture in above description or code snippet.
I would suggest you to use oData WCF Data Services to connect any mobile application to SQL Server. OData services are fast and easy way to connect on-premise SQL Server or Cloud based RDBMS i.e. SQL Azure.
This article explains how to do it step by step so I would suggest trying it and if you met any problem, post to SO and we sure will help you:
Most of the Android developers actually prefer WCF using JSON to connect from Android to SQL Server/Azure so you sure can take a look as well here.

Related

Making chat app

I want to do a chat application and I found this code on GitHub : https://github.com/Pirngruber/AndroidIM. And author created a function to send a message which looks like this
public String sendHttpRequest(String params)
{
URL url;
String result = new String();
try
{
url = new URL(AUTHENTICATION_SERVER_ADDRESS);
HttpURLConnection connection;
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
PrintWriter out = new PrintWriter(connection.getOutputStream());
out.println(params);
out.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
result = result.concat(inputLine);
}
in.close();
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
if (result.length() == 0) {
result = HTTP_REQUEST_FAILED;
}
return result;
}
Where private static final String AUTHENTICATION_SERVER_ADDRESS = "http://192.168.0.102/android-im/index.php";
And also here he explained how to make it run
https://code.google.com/archive/p/simple-android-instant-messaging-application/
So, my question is that: As I understood author sends all messages to his server and after this server sends them to user. So, if PC will be turned off server won't work and his chat won't work too, is it right? If yes, can somebody explain me how to do a chat app without server?
Thank you
Yes, seems like it requires a server to be online at all times. But that's how all modern chat applications on smartphones work (Telegram, Whatsapp, Threema, all google chats...). Without a server you would rely on the fact that both smartphones are online at the same time in order to establish a direct connection. This is a huge disadvantage and works against any power-saving features of the mobile OS. Also two parties can hardly communicate if they are always online at different times.
So essentially you need to decide for yourself whether you really want a peer-to-peer or a server-based chat. Just remember that even in case of P2P, you will have to figure out the IP addresses of the other chat clients. And then you'll probably have to use some sort of server, again.
What you need is a P2P chat implementation, you can use WIFI direct for that in Android. Checkout this code: https://github.com/life0fun/wifi-direct-chat
Usually the chat apps need to have a central server to receive the messages and send it to the correct nodes. That code you paste is that kind of implementation.

Cross Platform technology Stack: Sharing code and database in Android and ASP.NET MVC

I am working on a project which will have some part developed as a Android APP and some part as a website. The website would be a content management system, and the android app will be one of the consumer of the data.
Just to be aware, my background is completely .NET, C#. And i am learning, Java and Android, so far good.
I was thinking about the technology i should use, so that the two parts can communicate and also how i can reuse most of the common components like Logging, Instrumentation etc.
Few questions where i am not sure which would be the best choice:
Sharing cross platform code? In android i am writing code in Java, and in the website C#. I am facing an issue where how to re-use the common components like logging. I have heard about some tools like IKVM, but are they really worth? Or writing the code at two places will be a better choice in long term ?
Database: I am planning to go with ASP.NET MVC and MySQL and then on Android i can have a SQLite local DB, which i can sync using a web service. I really want to use MSSQL Server (because i know it very well). Is there a way to sync the MS SQL Server hosted remotely and the local Android SQLite DB? Or any other suggestion.
Also, if anyone has any suggestion in how to architect a hybrid solution like this, it would be really helpful.
Note: I cannot use tools like Xamrin as they are not free, and cost is a worry for now. Also, i want to really develop a native android app, which means i don't want to go with PhoneGap etc.
Thanks in advance.
the best way for android and website to communicate is a web service
I have worked on android apps that communicate with a .net web service to access
sql server database (insert, update, delete, retrieve data....etc)
but I fount that having a local data base causes a big issue in sync.
so all my apps dont have local DB and request all info from a local server connected using Wi-Fi.
code wise: you need to use Android AsyncTask to send http (GET,POST) requests to the Web service, this is an example of the code:
public class httpGetProduct extends AsyncTask<Void,Void,String> {
String result, rs;
JSONArray jArray;
String itemcode="",price,desc_ar,desc_en;
#Override
protected void onPreExecute() {
super.onPreExecute();
isOnline=ping(); // a function that checks if local server is available
}
#Override
protected String doInBackground(Void... params) {
if(isOnline)
try {
String link = "http://"+ip+":"+port+"/PriceCheckerWS.asmx/get_product_data?barcode="+barcode;
URL url = new URL(link);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(link));
//execute http get request
HttpResponse response = client.execute(request);
// read the reply
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
// split string as the result is inside xml tags
String[] separated = result.split(">");
JSONObject jObject = new JSONObject(separated[2]);
jArray = jObject.getJSONArray("product");
// read the string in from of JSON array
JSONObject json_data = jArray.getJSONObject(0);
itemcode=json_data.getString("Barcode");
price=json_data.getString("Price");
desc_ar=json_data.getString("Item_Desc_Ar");
desc_en=json_data.getString("Item_Desc_En");
rs = "sucessful";
} catch (Exception e) {
rs = "Fail";
}
return rs;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//after execution is done you can do something here
if(!isOnline)
Toast.makeText(getApplicationContext(),
"Fail to connect to server", Toast.LENGTH_SHORT).show();
else if(itemcode.isEmpty())
{
if(lang){
Toast toast = Toast.makeText(getApplicationContext(),
"No information about this item in database", Toast.LENGTH_SHORT);
toast.show();
}
else{
Toast toast = Toast.makeText(getApplicationContext(),
R.string.no_data_ar, Toast.LENGTH_SHORT);
toast.show();
}
}else{
intent = new Intent(MainActivity.this, ViewProduct.class);
intent.putExtra("barcode", barcode);
intent.putExtra("price",price);
intent.putExtra("desc_ar",desc_ar);
intent.putExtra("desc_en",desc_en);
startActivity(intent);}
}
}
and in the onCreate you call the asynctask like this:
new httpGetProduct().execute();
hope this helps

RESTful web Service for Android Application

I have an application and I need to get some data from my database(MySQL and it stays on web, not local). I think a simple RestFul webservice will be the best option for me to access this database and get the data. However, I m not able to create the webservice. I did some researches but I got confused. All I need is just accessing the database and get a few data from the table. Please give me some help to create the neccessary webservice. I don't want it to be a complex webservice. Thank to you all
this is php page of web-service. in this userid is taken from android java file that requesting that data. and after that selecting data from mySql it will simply echo all data and that will be given to java file as response.
seluser_profile.php
<?php
//$con=mysql_connect("localhost","root","");
//mysql_select_db("android_db",$con);
$con=mysql_connect("localhost","root","");
mysql_select_db("android_db",$con);
$uname=$_POST['userid'];
$q="select * from user_details where username='$uname'";
$rec=mysql_query($q);
if(mysql_num_rows($rec)==1)
{
$arr=mysql_fetch_array($rec);
echo $arr[0]+" "+$arr[2]+" "+$arr[3];
}
else
{
echo "false";
}
?>
Java code for requesting to web service.
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.0.2/webservice/seluser_profile.php");
try {
// Add your data
//Toast.makeText(getApplicationContext(), "Hello", Toast.LENGTH_LONG).show();
List<NameValuePair> namevpair = new ArrayList<NameValuePair>(2);
namevpair.add(new BasicNameValuePair("userid",valueIWantToSend));//in this first argument is name of post variable which we will use in php web service as name of post varible $_POST['fname'];
httppost.setEntity(new UrlEncodedFormEntity(namevpair));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
str = inputStreamToString(response.getEntity().getContent()).toString();
//Toast.makeText(getApplicationContext(), "your answer="+str, Toast.LENGTH_LONG).show();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
use this java code in doInBackground method of Asynctask class. otherwise it will give you network handler exception.
private StringBuilder inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Return full string
return total;
}
and also add this function for string building from inputstream.
Here is a link, You may seen this while surfing, I know this is not an answer , but I cannot comment bcz I dnt have enough Rep.
http://www.androidhive.info/2014/01/how-to-create-rest-api-for-android-app-using-php-slim-and-mysql-day-12-2/
I used this in one of my project, customization was very easy..and a great tutorial.

How can i create and use only SOAP server without client on GAE?

First, sorry for my poor English.
I found this article and follow it.
https://developers.google.com/appengine/articles/soap?hl=vi
It's worked. Now i want to create only the server like that to use in other client.Is that ok?
For example when i deployed the HelloSOAPServerServlet to the abc#appspot.com
And when i want to use my service, i just paste this URL: abc#appspot.com/hellosoapserver?name=SOAP&arriving=true to the browser. How can i do something like that?
Because i want my client what use this service is the Andoird phone.
abc#appspot.com is an email address. You can not deploy GAE code to it.
When you create a GAE application you must pick a unique application name, for example mysoap. The url of your app would then be http://mysoap.appspot.com/.
After you upload your code to it you could access your SOAP at http://mysoap.appspot.com/hellosoapserver?name=SOAP&arriving=true
You got it in that example.
You made the SOAP Webservice in :
Building a SOAP Server on Google App Engine
and then you created a client that consume it from a Servlet:
Building a SOAP Client on Google App Engine Using JAX-WS
Now what you need is to make a HTTP Client call to that URL from your Android application with correct values in params.
Using the example available at http://developer.android.com/reference/java/net/HttpURLConnection.html and url provided your sample
URL url = new URL(" http://greeter-client.appspot.com/hellosoapclient?name=SOAP&arriving=true");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
finally {
urlConnection.disconnect();
}
In readStream is where you read the response from your service hosted at GAE
readStream can be something like this:
private static String readStream(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}

How to perform syncing in android?

I am creating a networking website's Application in android.I want to know how can I perform syncing ie I want to store all user contacts on websites to my android phone.
user's details will come in XML format.
Please Guide me ..
For that you have to make a web service call either by using HttpClient or by using other third-party libraries like kSoap2. But i would prefer native class instead of third-party library.
Here is a best example: http://lukencode.com/2010/04/27/calling-web-services-in-android-using-httpclient/
After making a call, you will receive a XML, after that you can parse the received XML response either by using SAX parser, Pull Parser or DOM Parser.
This is the scenario to fetch data from web to your local database.
For your info: To get response from Web:
public static InputStream getInputStreamFromWeb(String url) {
InputStream content = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet(url));
content = response.getEntity().getContent();
} catch (Exception e) {
Log.("GET", "Network exception", e);
}
return content;
}

Categories

Resources