Android – SQL Server Database Connectivity (Part – 2, Get & Post Data)
WCF Service
Windows Communication Foundation (WCF) is a framework for building service-oriented applications. Using WCF, you can send data as asynchronous messages from one service endpoint to another. A service endpoint can be part of a continuously available service hosted by IIS, or it can be a service hosted in an application. An endpoint can be a client of a service that requests data from a service endpoint. The messages can be as simple as a single character or word sent as JSON, XML, or as complex as a stream of binary data.
HttpURLConnection
A URLConnection with support for HTTP-specific features. See the spec for details.
Uses of this class follow a pattern:
- Obtain a new HttpURLConnection by calling URL.openConnection() and casting the result to HttpURLConnection.
- Prepare the request. The primary property of a request is its URI. Request headers may also include metadata such as credentials, preferred content types, and session cookies.
- Optionally upload a request body. Instances must be configured with setDoOutput(true) if they include a request body. Transmit data by writing to the stream returned by getOutputStream().
- Read the response. Response headers typically include metadata such as the response body’s content type and length, modified dates and session cookies. The response body may be read from the stream returned by getInputStream(). If the response has no body, that method returns an empty stream.
- Disconnect. Once the response body has been read, the HttpURLConnection should be closed by calling disconnect(). Disconnecting releases the resources held by a connection so they may be closed or reused.
For example, to retrieve the webpage at http://www.wintechtutorials.com/:
URL url = new URL("http://www.wintechtutorials.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
} finally {
urlConnection.disconnect();
}
Step by Step Tutorial
Step 1: Open Android Studio.
Step 2: Create a new project as follows:
If you see the Welcome to Android Studio dialog, choose Start a new Android Studio project, available under ‘Quick Start’ on the right of the dialog.
Otherwise, click File in the Android Studio menu bar, then New, New Project.
Step 3: Enter your app name, company domain, and project location, as prompted. Then click Next.
Step 4: Select the form factors you need for your app. If you’re not sure what you need, just select Phone and Tablet. Then click Next.
Step 5: Select Blank Activity in the ‘Add an activity to Mobile’ dialog. Then click Next.
Step 6: Enter the activity name, layout name and title as prompted. The default values are fine. Then click Finish.
After that wait for few seconds. Android Studio starts Gradle and builds of your project.
Step 7: First of all add permission in Android Manifest xml file.
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Step 8: Go to content_main.xml file and add listview widget
<ListView android:id="@+id/list" android:layout_width="match_parent" android:layout_height="match_parent"></ListView>
Step 9: Now go to activity_main.xml file and do some changes with default FloatingActionButton
<android.support.design.widget.FloatingActionButton android:id="@+id/fab" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="bottom|end" android:layout_margin="@dimen/fab_margin" app:srcCompat="@android:drawable/ic_input_add" />
Step 10: Now add a list item xml file for list.
Right click on layout folder (under res folder) -> New -> Layout resource file
give the name of this resource file (i give name brandlist)
Step 11: Declare public variable ArrayList<HashMap<String, String>>
ArrayList<HashMap<String, String>> BrandList;
Step 12: Declare object of Array and ListView.
BrandList = new ArrayList<HashMap<String, String>>(); ListView list = (ListView) findViewById(R.id.list);
Step 13: Now create a new class extend with AsyncTask<> in MainActivity.java file
AsyncTask enables proper and easy use of the UI thread. This class allows you to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.
class GetBrandList extends AsyncTask<String, Void, String> { String status= null; Activity context; ListView listView; public GetBrandList(Activity context, ListView listView){ this.context =context; this.listView=listView; } protected void onPreExecute(){ } protected String doInBackground(String... connUrl){ HttpURLConnection conn=null; BufferedReader reader; try{ final URL url=new URL(connUrl[0]); conn=(HttpURLConnection) url.openConnection(); conn.addRequestProperty("Content-Type", "application/json; charset=utf-8"); conn.setRequestMethod("GET"); int result = conn.getResponseCode(); if(result==200){ InputStream in=new BufferedInputStream(conn.getInputStream()); reader = new BufferedReader(new InputStreamReader(in)); StringBuilder sb=new StringBuilder(); String line = null; while((line=reader.readLine())!=null){ status=line; } } }catch(Exception ex){ ex.printStackTrace(); } return status; } protected void onPostExecute(String result){ super.onPostExecute(result); if(result!=null){ try{ ArrayList<String> stringArrayList = new ArrayList<String>(); JSONArray jsonArray = new JSONArray(result); for(int i=0; i<jsonArray.length(); i++){ JSONObject object = jsonArray.getJSONObject(i); String Brand= object.getString("Brand"); HashMap<String, String> itemList = new HashMap<String, String>(); itemList.put("Brand",Brand); BrandList.add(itemList); } adapter = new SimpleAdapter(MainActivity.this, BrandList,R.layout.brandlist, new String[]{"Brand"},new int[]{R.id.txtBrand}); ((AdapterView<ListAdapter>) listView).setAdapter(adapter); }catch (Exception ex){ ex.printStackTrace(); } }else{ Toast.makeText(MainActivity.this,"Could not get any data.",Toast.LENGTH_LONG).show(); } } }
Step 14: Code below mention line to execute AsyncTask class file.
new GetBrandList(MainActivity.this,list).execute("http://10.0.1.200:8081/service1.svc/GetBrandName");
Now you can run your code and check the output in your mobile. you will see the Get mehtod will get the record from server and display it on Mobile device.
Now the next steps to Post data from Mobile to Database.
Step 15: Now add a new Empty Activity in your project.
Right click on layout folder -> New -> Activity -> Empty Activity
Give the name of activity and project name in popup dialog box and click on Finish button. (I give the name activity_add_brand)
Step 16: Add edit text and submit button in newly created activity (activity_add_brand.xml)
<LinearLayout android:layout_width="368dp" android:layout_height="495dp" android:orientation="vertical" tools:layout_editor_absoluteY="8dp" tools:layout_editor_absoluteX="8dp"> <EditText android:id="@+id/txtAddBrand" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="2dp" android:layout_marginBottom="10dp"/> <Button android:id="@+id/btnAdd" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Save" android:padding="5dp" android:layout_marginTop="10dp"/> </LinearLayout>
Step 17: Now go to AddBrandActivity.java file and create a new AsyncTask Class file. following is the code.
class SaveBrand extends AsyncTask<String, Void, String> { String status= null; protected void onPreExecute(){ } protected String doInBackground(String... connUrl){ HttpURLConnection conn=null; BufferedReader reader; try{ final URL url=new URL(connUrl[0]); conn=(HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setChunkedStreamingMode(0); conn.addRequestProperty("Content-Type", "application/json; charset=utf-8"); conn.setRequestMethod("POST"); JSONObject jsonObject = new JSONObject(); jsonObject.put("brand",Brand); //object name is case senstive. it must be same as service parameter. OutputStream out = new BufferedOutputStream(conn.getOutputStream()); out.write(jsonObject.toString().getBytes()); out.flush(); out.close(); int result = conn.getResponseCode(); if(result==200){ InputStream in=new BufferedInputStream(conn.getInputStream()); reader = new BufferedReader(new InputStreamReader(in)); StringBuilder sb=new StringBuilder(); String line = null; while((line=reader.readLine())!=null){ status=line; } } }catch(Exception ex){ ex.printStackTrace(); } return status; } protected void onPostExecute(String result){ super.onPostExecute(result); if(result!=null){ Toast.makeText(AddBrandActivity.this,"Brand Saved Successfuly.",Toast.LENGTH_LONG).show(); }else{ Toast.makeText(AddBrandActivity.this,"Doesn't Saved Data.",Toast.LENGTH_LONG).show(); } } }
Step 18: Do the following code in onCreate() to execute the AsyncTask class file.
final EditText txtAddBrand = (EditText) findViewById(R.id.txtAddBrand); Button btnAdd = (Button) findViewById(R.id.btnAdd); btnAdd.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Brand = txtAddBrand.getText().toString(); new SaveBrand().execute("http://10.0.1.200:8081/service1.svc/AddBrand"); } });
Now your full code is ready to run. you can save data into Sql Server database with post method and load list of item with Get Method.
Full source code:
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.suraj.sqlconnectionsample"> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity" android:label="@string/app_name" android:theme="@style/AppTheme.NoActionBar"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".AddBrandActivity"></activity> </application> </manifest>
Activity_Main.xml
<?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.suraj.sqlconnectionsample.MainActivity"> <android.support.design.widget.AppBarLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/AppTheme.AppBarOverlay"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:popupTheme="@style/AppTheme.PopupOverlay" /> </android.support.design.widget.AppBarLayout> <include layout="@layout/content_main" /> <android.support.design.widget.FloatingActionButton android:id="@+id/fab" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="bottom|end" android:layout_margin="@dimen/fab_margin" app:srcCompat="@android:drawable/ic_input_add" /> </android.support.design.widget.CoordinatorLayout>
content_main.xml
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:context="com.example.suraj.sqlconnectionsample.MainActivity" tools:showIn="@layout/activity_main"> <ListView android:id="@+id/list" android:layout_width="match_parent" android:layout_height="match_parent"></ListView> </android.support.constraint.ConstraintLayout>
brandlist.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/txtBrand" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout>
activity_add_brand.xml
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.suraj.sqlconnectionsample.AddBrandActivity"> <LinearLayout android:layout_width="368dp" android:layout_height="495dp" android:orientation="vertical" tools:layout_editor_absoluteY="8dp" tools:layout_editor_absoluteX="8dp"> <EditText android:id="@+id/txtAddBrand" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="2dp" android:layout_marginBottom="10dp"/> <Button android:id="@+id/btnAdd" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Save" android:padding="5dp" android:layout_marginTop="10dp"/> </LinearLayout> </android.support.constraint.ConstraintLayout>
MainActivity.java
package com.example.suraj.sqlconnectionsample; import android.app.Activity; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.Menu; import android.view.MenuItem; import android.widget.AdapterView; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONObject; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; public class MainActivity extends AppCompatActivity { ArrayList<HashMap<String, String>> BrandList; ListAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); BrandList = new ArrayList<HashMap<String, String>>(); ListView list = (ListView) findViewById(R.id.list); new GetBrandList(MainActivity.this,list).execute("http://10.0.1.200:8081/service1.svc/GetBrandName"); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { /*Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show();*/ Intent intent = new Intent(MainActivity.this, AddBrandActivity.class); startActivity(intent); } }); } class GetBrandList extends AsyncTask<String, Void, String> { String status= null; Activity context; ListView listView; public GetBrandList(Activity context, ListView listView){ this.context =context; this.listView=listView; } protected void onPreExecute(){ } protected String doInBackground(String... connUrl){ HttpURLConnection conn=null; BufferedReader reader; try{ final URL url=new URL(connUrl[0]); conn=(HttpURLConnection) url.openConnection(); conn.addRequestProperty("Content-Type", "application/json; charset=utf-8"); conn.setRequestMethod("GET"); int result = conn.getResponseCode(); if(result==200){ InputStream in=new BufferedInputStream(conn.getInputStream()); reader = new BufferedReader(new InputStreamReader(in)); StringBuilder sb=new StringBuilder(); String line = null; while((line=reader.readLine())!=null){ status=line; } } }catch(Exception ex){ ex.printStackTrace(); } return status; } protected void onPostExecute(String result){ super.onPostExecute(result); if(result!=null){ try{ ArrayList<String> stringArrayList = new ArrayList<String>(); JSONArray jsonArray = new JSONArray(result); for(int i=0; i<jsonArray.length(); i++){ JSONObject object = jsonArray.getJSONObject(i); String Brand= object.getString("Brand"); HashMap<String, String> itemList = new HashMap<String, String>(); itemList.put("Brand",Brand); BrandList.add(itemList); } adapter = new SimpleAdapter(MainActivity.this, BrandList,R.layout.brandlist, new String[]{"Brand"},new int[]{R.id.txtBrand}); ((AdapterView<ListAdapter>) listView).setAdapter(adapter); }catch (Exception ex){ ex.printStackTrace(); } }else{ Toast.makeText(MainActivity.this,"Could not get any data.",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.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
AddBrandActivity.java
package com.example.suraj.sqlconnectionsample; import android.app.Activity; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; 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.Toast; import org.json.JSONArray; import org.json.JSONObject; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; public class AddBrandActivity extends AppCompatActivity { private String Brand; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_brand); final EditText txtAddBrand = (EditText) findViewById(R.id.txtAddBrand); Button btnAdd = (Button) findViewById(R.id.btnAdd); btnAdd.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Brand = txtAddBrand.getText().toString(); new SaveBrand().execute("http://10.0.1.200:8081/service1.svc/AddBrand"); } }); } class SaveBrand extends AsyncTask<String, Void, String> { String status= null; protected void onPreExecute(){ } protected String doInBackground(String... connUrl){ HttpURLConnection conn=null; BufferedReader reader; try{ final URL url=new URL(connUrl[0]); conn=(HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setChunkedStreamingMode(0); conn.addRequestProperty("Content-Type", "application/json; charset=utf-8"); conn.setRequestMethod("POST"); JSONObject jsonObject = new JSONObject(); jsonObject.put("brand",Brand); //object name is case senstive. it must be same as service parameter. OutputStream out = new BufferedOutputStream(conn.getOutputStream()); out.write(jsonObject.toString().getBytes()); out.flush(); out.close(); int result = conn.getResponseCode(); if(result==200){ InputStream in=new BufferedInputStream(conn.getInputStream()); reader = new BufferedReader(new InputStreamReader(in)); StringBuilder sb=new StringBuilder(); String line = null; while((line=reader.readLine())!=null){ status=line; } } }catch(Exception ex){ ex.printStackTrace(); } return status; } protected void onPostExecute(String result){ super.onPostExecute(result); if(result!=null){ Toast.makeText(AddBrandActivity.this,"Brand Saved Successfuly.",Toast.LENGTH_LONG).show(); }else{ Toast.makeText(AddBrandActivity.this,"Doesn't Saved Data.",Toast.LENGTH_LONG).show(); } } } }
One thought on “Android – SQL Server Database Connectivity (Part – 2, Get & Post Data)”