Introduction
My previous article,
Angular Manage MSSQL Table CRUD With MVC Web API for Beginners, is related to managing data table records with a JSON object on a server using SQL database tables and MVC APIs. This tutorial is for beginners/freshers or students. Now again, we are accessing CRUD functionality in Android by using MVC Web API. I explain all data operations, and how to access APIs in Android applications. I hope it will be helpful for you to get/update or save data on the server using Android applications.
Table CRUD with API in Android
First, read the previous article carefully then download code from the previous article and install as per instruction, or if you know them already, then just download code for the Android application and change it as per your system setting URL of localhost.
Note
No validation testing, please ignore.
- Add a new record by inputting data in the field name, age, and city, then click on the Save button.
- Edit select record then update data in the field name, age, and city then click on the Save button.
- Delete select record then click on delete button.
- Refresh button to reload data in list.
Example Screenshot
Section First
Create a new empty project in Android. Then open build.gradle(app) add compile files ('libs/httpmime-4.2.1.jar') and implementation 'com.google.code.gson:gson:2.2.4' in dependencies section. Then add useLibrary 'org.apache.http.legacy' in android section. Both are showing in a red circle in the below android app structure. You can also download
httpmime-4.2.1.jar and copy the jar file in the android libs folder.
Now next add LinearLayout on the root in orientation vertical, then add three child element two LinearLayout and one is ListView. First, in the two child LinearLayout add three EditText, and in the next child, LinearLayout add three Buttons in a horizontal orientation. The design below shows an example.
Now I added one interface method processFinish(String) to get AsyncResponse when the AsyncTask call finished. Next derived class MyAsyncTask from AsyncTask. Constructor received three-parameter context, action, and param. Context is used to run progress call spinner. Our example has not used ProgressDialog option to show a loader view. Method onPreExecute() is used to pre-setup of variables before calling method doInBackground() if requires. Method doInBackground() calls static method POST which is available in MyUtility class, and PSOT calls again inside APICALLJSON(String action,String body) method. Then finally calls method onPostExecute(String) if the background request call is finished.
- public interface AsyncResponse {
- void processFinish(String output);
- }
-
- public class MyAsyncTask extends AsyncTask<String, Void, String> {
-
- public Context context;
- public AsyncResponse delegate = null;
- private String soapAction,callParam;
-
-
- public MyAsyncTask(Context _context,String _soapAction,String _callParam){
- soapAction=_soapAction;
- callParam=_callParam;
- this.context=_context;
- }
- @Override
- protected void onPreExecute() {
- }
- @Override
- protected String doInBackground(String... urls) {
- return MyUtility.POST(soapAction,callParam);
- }
- @Override
- protected void onPostExecute(String result) {
- delegate.processFinish(result);
- }
-
- }
Now the below method belongs to class MyUtility.java. This is static method which name is APICALLJSON(String action,String body). Action is the name of the API function name, and the body is a JSON body off parameter. API URL is localhost of your computer IP address. Create a HttpClient object to call request. Also create object of HttpPost and set header in request. Finally, execute the HTTP client and check the response status and get a response, convert to string and return to call location.
- public class MyUtility {
-
- public static String POST(String action, String callparam) {
- String sResult = "";
- Log.e("Post:==>", action+"=="+callparam);
- try {
- sResult=APICALLJSON(action,callparam);
-
- } catch (Exception e) {
- Log.d("Post", e.getMessage());
- }
- return sResult;
- }
-
- public static String APICALLJSON(String action, String body) {
-
- final String urlPost="http://192.168.42.82/mywapi/api/tcrud/"+action;
- String sResult = "";
- try {
- HttpClient httpclient = new DefaultHttpClient();
- HttpPost httppost = new HttpPost(urlPost);
- httppost.setHeader("Accept-Encoding", "gzip,deflate");
- httppost.setHeader("Content-Type", "application/json");
-
- httppost.setHeader("Host", "192.168.42.82");
- httppost.setHeader("Connection", "Keep-Alive");
- httppost.setHeader("User-Agent", "Apache-HttpClient/4.1.1");
- StringEntity se = new StringEntity(body);
- httppost.setEntity(se);
- HttpResponse resp = httpclient.execute(httppost);
- if(resp.getStatusLine().getStatusCode()== HttpStatus.SC_OK){
- HttpEntity ent = resp.getEntity();
- sResult = EntityUtils.toString(ent);
- return sResult;
- }
- } catch (Exception e) {
- Log.d("Post", e.getMessage());
- }
- finally {
- sResult="";
- }
- return sResult;
- }
-
- }
Next is a created model class which is named MyPerson. This class property is related to the SQL table TblPerson, and the script is available in my previous article
Angular Manage MSSQL Table CRUD With MVC Web API for Beginners. The other method selectRecord(String) is created to get List of MyPerson class objects. Because we received json response and by using Gson() to convert string json to object list of MyPerson object. Added get, set property of Id, Name, Age and City variable. Also, I created another two method getPersonRow() and setPersonRow(). Method getPersonRow is used to get rows of single record MyPerson class. Another is to convert a string to object of MyPerson class.
- public class MyPerson {
-
- private int Id;
- private String Name;
- private int Age;
- private String City;
-
- public int getId() {
- return Id;
- }
- public void setId(int id) {
- Id = id;
- }
- public String getName() {
- return Name;
- }
- public void setName(String name) {
- Name = name;
- }
- public int getAge() {
- return Age;
- }
- public void setAge(int age) {
- Age = age;
- }
- public String getCity() {
- return City;
- }
- public void setCity(String city) {
- City = city;
- }
-
- public String getPersonRow(){
- return String.valueOf(this.getId())+", "+this.getName()+", "+String.valueOf(this.getAge())+", "+this.getCity();
- }
-
- public MyPerson setPersonRow(String row){
- String []sAry=row.split(",");
- MyPerson objP=new MyPerson();
- objP.setId(Integer.parseInt(sAry[0].trim()));
- objP.setName(sAry[1].trim());
- objP.setAge(Integer.parseInt(sAry[2].trim()));
- objP.setCity(sAry[3].trim());
- return objP;
- }
-
- public List<MyPerson> selectRecord(String sResponse){
- List<MyPerson> objList =null;
- sResponse=sResponse.replace("\\","");
- sResponse=sResponse.substring(1,sResponse.length()-1);
- try{
- Gson gson = new Gson();
- Type listType = new TypeToken<List<MyPerson>>() {}.getType();
- objList = gson.fromJson(sResponse,listType);
- return objList;
- }
- catch(Exception ex){
- return null;
- }
- }
- }
Finally, we are taking the MainActivity class of this tutorial. In our example, the MainActivity class is extends AppCompatActivity implements AsyncResponse. Next, get the object from design view in android. Here, it shows a button function method of save, refresh and delete in all function setup action type and initialize asynctask object by calling taskInitSetup which received the API action name and body as a JSON string.
- public class MainActivity extends AppCompatActivity implements AsyncResponse{
-
- private EditText etname,etage,etcity;
- private Button btnsave, btnrefresh,btndelete;
- private ListView lvperson;
- private MyAsyncTask myAsyncTask = null;
- private String sActionType,sqryprmjson;
- private int iPersonId;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
-
-
- etname=(EditText)findViewById(R.id.etname);
- etage=(EditText)findViewById(R.id.etage);
- etcity=(EditText)findViewById(R.id.etcity);
- btnsave=(Button)findViewById(R.id.btnsave);
- btnrefresh=(Button)findViewById(R.id.btnrefresh);
- btndelete=(Button)findViewById(R.id.btndelete);
- lvperson=(ListView)findViewById(R.id.lvperson);
- iPersonId=0;
- sActionType="";
- btnsave.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- sActionType="S";
- String sname=etname.getText().toString();
- String sage=etage.getText().toString();
- String scity=etcity.getText().toString();
- if (iPersonId > 0)
- sqryprmjson = "{\"StrQry\":\"UPDATE [TblPerson] SET [Name]=\'" + sname + "\',[Age]=" + sage + ",[City]=\'" + scity + "\' WHERE [Id]=" + iPersonId + "\"}";
- else
- sqryprmjson = "{\"StrQry\":\"INSERT INTO [TblPerson] ([Name],[Age],[City]) VALUES(\'" + sname + "\'," + sage + ",\'" + scity + "\')\"}";
- myAsyncTask=taskInitSetup("recsave",sqryprmjson);
- myAsyncTask.execute();
- }
- });
- btnrefresh.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- sActionType="R";
- etname.setText("");etage.setText(""); etcity.setText("");
- iPersonId= 0;
- sqryprmjson="{'StrQry':'SELECT * FROM [TblPerson]'}";
- myAsyncTask=taskInitSetup("recselect",sqryprmjson);
- myAsyncTask.execute();
- }
- });
- btndelete.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- if(iPersonId==0)return;
- sActionType="D";
- sqryprmjson="{'StrQry':'DELETE FROM [TblPerson] WHERE Id="+iPersonId+"'}";
- myAsyncTask=taskInitSetup("recselect",sqryprmjson);
- myAsyncTask.execute();
- }
- });
- btnrefresh.callOnClick();
- }
- public MyAsyncTask taskInitSetup(String _soapAction, String _sBody) {
- MyAsyncTask _task = new MyAsyncTask(this, _soapAction, _sBody);
- _task.delegate = MainActivity.this;
- return _task;
- }
The below method is called when async task is request finished and return for output. Because I have use switch case due to different action type request in our example which is Save,Refresh,Delete.Edit or Delete call when you select record in listview, then you can call method.fillListView function takes json data as string, and convert json string to List. Next, we create ArrayAdapter for listview to set and display data.
- @Override
- public void processFinish(String output) {
- myAsyncTask=null;
- iPersonId=0;
- if(output!=null && output.trim()!="") {
- switch (sActionType) {
- case "D":
- btnrefresh.callOnClick();
- break;
- case "S":
- btnrefresh.callOnClick();
- break;
- case "R":
- fillListView(output);
- break;
- }
-
- }else{
- Toast.makeText(getApplicationContext(), "Try again...!", Toast.LENGTH_LONG).show();
- }
- }
-
- public void fillListView(String output){
- sActionType="";
- List<MyPerson> list = null;
- MyPerson obj;
- obj = new MyPerson();
- list = obj.selectRecord(output);
- try{
- if(list!=null && list.size()>0){
- String[] personRow=new String[list.size()];
- for(int r=0;r<list.size();r++)
- personRow[r]=list.get(r).getPersonRow();
- ArrayAdapter <String>adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, personRow);
- lvperson.setAdapter(adapter);
- lvperson.setOnItemClickListener(new AdapterView.OnItemClickListener() {
- @Override
- public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
- String sRow=adapterView.getItemAtPosition(i).toString();
- MyPerson objP=new MyPerson();
- objP=objP.setPersonRow(sRow);
- etname.setText(objP.getName());
- etage.setText(String.valueOf(objP.getAge()));
- etcity.setText(objP.getCity());
- iPersonId= objP.getId();
- }
- });
- }else{
- lvperson.setAdapter(null);
- Toast.makeText(getApplicationContext(), "No record found.", Toast.LENGTH_LONG).show();
- }
- }catch (Exception ex){
- Toast.makeText(getApplicationContext(), ex.getMessage(), Toast.LENGTH_LONG).show();
- }
- }
- }
Conclusion
This article showed and explained to beginner/fresher/student how to use an API request in Android and manage a data table by calling. Also, it showed the use of SQL, MVC API, and an Android app to build good mobile apps.