Skip to main content

Node.js and MongoDB API with Android - Part II

In previous part of the tutorial we made simple node.js API sending a hardcoded json containing a message string to the Android client.
Now , we will be adding say EMPLOYEE details using one API (addEmployee)  into the Mongodb and retrieving the list using other API (listEmployee).

Mongodb is document-based, high-performance NoSQL database.
You can define multiple databases in MongoDB where each database can have many collections (like TABLE), and those collections are simply a set of documents that consist of data stored as a key-value pair.

i) In terminal , enter npm install mongodb --save that will download mongodb module locally and creates a directory mongodb inside node_modules.

Also ,enter npm install body-parser --save that will download body-parser module that allows sending parameters of post requests.

We will be modifying the same main.js file created in Part I of the tutorial.
Add below lines of code :

var express = require('express'); // import the express framework
var app = express();

//lets require/import the mongodb native drivers.
var mongodb = require('mongodb');

var bodyParser = require('body-parser')
app.use( bodyParser.json() );       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
  extended: true
}));

//We need to work with "MongoClient" interface in order to connect to a mongodb server.
var MongoClient = mongodb.MongoClient;

var db_name = 'EMPLOYEEDB';

// Connection URL. This is where your mongodb server is running.
var url = 'mongodb://localhost:27017/' + db_name;;

var jsonMessage = '{"status":"true","message":"hello node.js"}';

// this callback will respond with the message string
app.get('/hello', function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
 
   // Send the response body as hardcoded json containing message
   res.end(jsonMessage);
  })

// insert employee details using post
app.post('/addEmployee', function(req, res) {
 
   // Use connect method to connect to the Server
    MongoClient.connect(url, function(err, db) {

    db.collection('employee').insertOne( {
        name: req.body.name,
        city: req.body.city,
        age: req.body.age
    } , function(err, result) {
    console.log("Inserted a document into the employee collection.");

          if(!err)
          {
                   res.status(200).send({"success":"true"});
                console.log({"success":"true"});
           }
          else
           {
               res.status(200).send({"success":"false"});
                console.log({"success":"false"});
             }
      });
    });
  });

// get the list of employees from db
app.get('/listEmployees', function (req, res) {

  MongoClient.connect(url, function(err, db) {

    // Get the documents collection
    var collection = db.collection('employee');

    collection.find().toArray(function (err, result) {
        if (err) {
        console.log(err);
       } else if (result.length) {
         console.log('Found:', result);
         res.status(200).send('{"employee":'+ JSON.stringify(result)+"}");
       } else {
        console.log('No document(s) found with defined "find" criteria!');
       }
      //Close connection
      db.close();
    });
  });
})

var server = app.listen(8080, function () {

  var port = server.address().port

  console.log("Node app listening at http://127.0.0.1:%s", port)

})



The API addEmployee will insert details like name ,city and age in the collection employee of EMPLOYEEDB database and the API listEmployees will give list of employees from EMPLOYEEDB database returning in json format.

Again, run the above file using terminal.
Navigate to NodeExample folder and then enter node main.js to run the application at localhost/8080 or 127.0.0.1/8080.


ii) Now we will modify Android app created in previous part that had all the setup for the API calls (Helper calls).

1.Open layout file (activity_main.xml) and modify the layout file by adding below lines :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/btn_add"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="ADD" />

    <ListView
        android:id="@+id/lv_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/btn_add"></ListView>

</RelativeLayout>


When ADD button is clicked open dialog for capturing Employee details like name , city and age.

Screen with dialog output :


2.Modify the MainActivity.java file for displaying listing of employee from API and adding new employee details using dialog.

The entire MainActivity.java looks us follows :

public class MainActivity extends AppCompatActivity implements WebserviceResponseListner {

    Button btn_add;
    Dialog dialog;
    ListView lv_main;
    ArrayList<String> arrayEmployeeName;
    ArrayAdapter<String> adpater;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn_add = (Button) findViewById(R.id.btn_add);
        lv_main = (ListView) findViewById(R.id.lv_main);
        dialog = new Dialog(MainActivity.this);

        arrayEmployeeName = new ArrayList<>();
        adpater = new ArrayAdapter<>(this, android.R.layout.simple_expandable_list_item_1, arrayEmployeeName);
        lv_main.setAdapter(adpater);

        new WebService(MainActivity.this, (WebserviceResponseListner) MainActivity.this,
                "listEmployees").execute();

        btn_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.setContentView(R.layout.dialog_insert_employee);

                final EditText edt_employee_name = (EditText) dialog.findViewById(R.id.edt_employee_name);
                final EditText edt_employee_city = (EditText) dialog.findViewById(R.id.edt_employee_city);
                final EditText edt_employee_age = (EditText) dialog.findViewById(R.id.edt_employee_age);

                Button btn_insert = (Button) dialog.findViewById(R.id.btn_insert);

                btn_insert.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        try {
                            AddEmployeeRequest addEmployeeRequest = new AddEmployeeRequest(edt_employee_name.getText().toString(), edt_employee_city.getText().toString(), edt_employee_age.getText().toString());

                            new WebService(MainActivity.this, (WebserviceResponseListner) MainActivity.this, addEmployeeRequest,
                                    "addEmployee").execute();

                        } catch (Exception e) {

                        }
                    }
                });
                dialog.show();
            }
        });
        //        new WebService(MainActivity.this, (WebserviceResponseListner) MainActivity.this,
        //                "hello").execute();
    }

    public class HelloNodeResponse {

        String status, message;

        public HelloNodeResponse(String status, String message) {
            this.status = status;
            this.message = message;
        }

        public String getStatus() {
            return status;
        }

        public void setStatus(String status) {
            this.status = status;
        }

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }
    }

    // Inserting the employee details
    public class AddEmployeeRequest {

        String name;
        String city;
        String age;

        public AddEmployeeRequest(String name, String city, String age) {
            this.name = name;
            this.city = city;
            this.age = age;
        }
    }

    public class AddEmployeeResponse {

        String success;

        public AddEmployeeResponse(String success) {
            this.success = success;
        }

        public String getSuccess() {
            return success;
        }

        public void setSuccess(String success) {
            this.success = success;
        }
    }

    // Listing of employees
    public class ListEmployeesResponse {

        ArrayList<employee> employee;

        public ListEmployeesResponse(ArrayList<ListEmployeesResponse.employee> employee) {
            this.employee = employee;
        }

        public ArrayList<ListEmployeesResponse.employee> getEmployee() {
            return employee;
        }

        public void setEmployee(ArrayList<ListEmployeesResponse.employee> employee) {
            this.employee = employee;
        }

        public class employee {

            String name, city, age;

            public employee(String name, String city, String age) {
                this.name = name;
                this.city = city;
                this.age = age;
            }

            public String getName() {
                return name;
            }

            public void setName(String name) {
                this.name = name;
            }

            public String getCity() {
                return city;
            }

            public void setCity(String city) {
                this.city = city;
            }

            public String getAge() {
                return age;
            }

            public void setAge(String age) {
                this.age = age;
            }
        }
    }

    @Override
    public void OnResponse(Object response, boolean flagToCheckFailure, String webServiceName) {

        if (webServiceName.equalsIgnoreCase("hello")) {

            if (!flagToCheckFailure) {
                HelloNodeResponse data = (HelloNodeResponse) response;

            } else {
                Toast.makeText(this, "Something went Wrong", Toast.LENGTH_LONG).show();
            }
        } else if (webServiceName.equalsIgnoreCase("addEmployee")) {
            if (!flagToCheckFailure) {

                AddEmployeeResponse data = (AddEmployeeResponse) response;

                if (data.getSuccess().equalsIgnoreCase("true")) {
                    Toast.makeText(this, "Inserted Successfully!!", Toast.LENGTH_LONG).show();

                    new WebService(MainActivity.this, (WebserviceResponseListner) MainActivity.this,
                            "listEmployees").execute();

                } else {
                    Toast.makeText(this, "Insert Failed", Toast.LENGTH_LONG).show();
                }

                dialog.dismiss();
            } else {
                Toast.makeText(this, "Something went Wrong", Toast.LENGTH_LONG).show();
                dialog.dismiss();
            }
        } else if (webServiceName.equalsIgnoreCase("listEmployees")) {

            if (!flagToCheckFailure) {
                ListEmployeesResponse data = (ListEmpl    Activity activity;
    WebserviceResponseListner listener = null;
    String METHOD_NAME = "";
    MainActivity.AddEmployeeRequest mAddEmployeePojo;

    public WebService(Activity activity, WebserviceResponseListner listner, String methodName) {
        this.activity = activity;
        this.METHOD_NAME = methodName;
        this.listener = listner;
    }

    public WebService(Activity activity, WebserviceResponseListner listner, MainActivity.AddEmployeeRequest mAddEmployeePojo, String methodName) {
        this.activity = activity;
        this.METHOD_NAME = methodName;
        this.listener = listner;
        this.mAddEmployeePojo = mAddEmployeePojo;
    }


    @Override
    protected String doInBackground(String... strings) {

        switch (METHOD_NAME) {
            case "hello":
                HelloNode();
                break;
            case "addEmployee":
                AddEmployee();
                break;
            case "listEmployees":
                ListingEmployees();
                break;
        }
        return null;
    }

    private void HelloNode() {

        RestClient.get().HelloNode(new RestCallback<MainActivity.HelloNodeResponse>() {

            @Override
            public void success(MainActivity.HelloNodeResponse updateProfileResponsePojo, Response response) {
                Log.e("Successful", response.toString() + "/" + response.getUrl());
                listener.OnResponse(updateProfileResponsePojo, false, "hello");
            }

            @Override
            public void failure(RetrofitError error) {
                Log.e("Url", error.toString() + "/" + error.getUrl());
                listener.OnResponse(new Object(), true, "hello");
            }
        });
    }

    private void AddEmployee() {

        RestClient.get().AddEmployee(mAddEmployeePojo, new RestCallback<MainActivity.AddEmployeeResponse>() {

            @Override
            public void success(MainActivity.AddEmployeeResponse mAddEmployeePojo, Response response) {
                Log.e("Success AddEmployee", response.toString() + "/" + response.getUrl());
                listener.OnResponse(mAddEmployeePojo, false, "addEmployee");
            }

            @Override
            public void failure(RetrofitError error) {
                Log.e("Url", error.toString() + "/" + error.getUrl());
                listener.OnResponse(new Object(), true, "addEmployee");
            }
        });
    }

    private void ListingEmployees() {

        RestClient.get().TestNode(new RestCallback<MainActivity.ListEmployeesResponse>() {

            @Override
            public void success(MainActivity.ListEmployeesResponse updateProfileResponsePojo, Response response) {
                Log.e("listEmployee", response.toString() + "/" + response.getUrl());
                listener.OnResponse(updateProfileResponsePojo, false, "listEmployees");
            }

            @Override
            public void failure(RetrofitError error) {
                Log.e("Url", error.toString() + "/" + error.getUrl());
                listener.OnResponse(new Object(), true, "listEmployees");
            }
        });
    }
oyeesResponse) response;
                arrayEmployeeName.clear();
                for (int i = 0; i < data.getEmployee().size(); i++) {
                    arrayEmployeeName.add(data.getEmployee().get(i).getName());
                }
                adpater.notifyDataSetChanged();
            } else {
                Toast.makeText(this, "Something went Wrong", Toast.LENGTH_LONG).show();
            }

        }
    }
}


3.Now we have to handle the API calls in WebService call which extends AsyncTask and giving back the response from the respectively API.

public class WebService extends AsyncTask<String, Void, String> {

    Activity activity;
    WebserviceResponseListner listener = null;
    String METHOD_NAME = "";
    MainActivity.AddEmployeeRequest mAddEmployeePojo;

    public WebService(Activity activity, WebserviceResponseListner listner, String methodName) {
        this.activity = activity;
        this.METHOD_NAME = methodName;
        this.listener = listner;
    }

    public WebService(Activity activity, WebserviceResponseListner listner, MainActivity.AddEmployeeRequest mAddEmployeePojo, String methodName) {
        this.activity = activity;
        this.METHOD_NAME = methodName;
        this.listener = listner;
        this.mAddEmployeePojo = mAddEmployeePojo;
    }


    @Override
    protected String doInBackground(String... strings) {

        switch (METHOD_NAME) {
            case "hello":
                HelloNode();
                break;
            case "addEmployee":
                AddEmployee();
                break;
            case "listEmployees":
                ListingEmployees();
                break;
        }
        return null;
    }

    private void HelloNode() {
        RestClient.get().HelloNode(new RestCallback<MainActivity.HelloNodeResponse>() {

            @Override
            public void success(MainActivity.HelloNodeResponse updateProfileResponsePojo, Response response) {
                Log.e("Successful", response.toString() + "/" + response.getUrl());
                listener.OnResponse(updateProfileResponsePojo, false, "hello");
            }

            @Override
            public void failure(RetrofitError error) {
                Log.e("Url", error.toString() + "/" + error.getUrl());
                listener.OnResponse(new Object(), true, "hello");
            }
        });
    }

    private void AddEmployee() {
        RestClient.get().AddEmployee(mAddEmployeePojo, new RestCallback<MainActivity.AddEmployeeResponse>() {

            @Override
            public void success(MainActivity.AddEmployeeResponse mAddEmployeePojo, Response response) {
                Log.e("Success AddEmployee", response.toString() + "/" + response.getUrl());
                listener.OnResponse(mAddEmployeePojo, false, "addEmployee");
            }

            @Override
            public void failure(RetrofitError error) {
                Log.e("Url", error.toString() + "/" + error.getUrl());
                listener.OnResponse(new Object(), true, "addEmployee");
            }
        });
    }

    private void ListingEmployees() {

        RestClient.get().ListEmployees(new RestCallback<MainActivity.ListEmployeesResponse>() {
            @Override
            public void success(MainActivity.ListEmployeesResponse updateProfileResponsePojo, Response response) {
                Log.e("listEmployee", response.toString() + "/" + response.getUrl());
                listener.OnResponse(updateProfileResponsePojo, false, "listEmployees");
            }

            @Override
            public void failure(RetrofitError error) {
                Log.e("Url", error.toString() + "/" + error.getUrl());
                listener.OnResponse(new Object(), true, "listEmployees");
            }
        });
    }
}


4. Lastly modify ApiMethods interface adding API call addEmployee for adding employee details and API call listEmployees for getting employee listing from the remote database.

public interface ApiMethods {

    @GET("/hello")
    void HelloNode(RestCallback<MainActivity.HelloNodeResponse> restCallback);

    @POST("/addEmployee")
    void AddEmployee(@Body MainActivity.AddEmployeeRequest shareRequest, RestCallback<MainActivity.AddEmployeeResponse> restCallback);

    @GET("/listEmployees")
    void ListEmployees(RestCallback<MainActivity.ListEmployeesResponse> restCallback);

}

Run the Application on an emulator while the main.js node application is still running on localhost (that we have left running above).
You will get the following output in the app :

            



If you are stuck anywhere while implementing above example be patient and try to debug or kindly comment your queries here.

Comments

  1. Hi, something went wrong with copy-pasting in the above code. See line
    "ListEmployeesResponse data = (ListEmpl Activity activity;"

    Cheers!

    ReplyDelete
  2. Its a great article on your blog. Thank you for sharing
    MEAN Stack Training in Hyderabad

    ReplyDelete
  3. The code before "oyeesResponse) response;" is missing.
    can you please help me with that??

    ReplyDelete
  4. Thank you for this wonderful article. I'm learning a lot from here. Keep us updated by sharing more such great information.
    Node JS Training

    ReplyDelete

  5. Thank you for sharing the article. The data that you provided in the blog is informative and effective. Best nodejs Training Institute

    ReplyDelete
  6. Thanks a lot for sharing, Contains A to Z concepts.
    Full Stack Online Training

    ReplyDelete
  7. I really enjoyed your blog Thanks for sharing and it was very usefully to me
    NodeJs Online Training
    NodeJs Training in Hyderabad

    ReplyDelete
  8. Inspirational content, have acquired a good knowledge of the above content useful for all aspirants.Thanks for sharing
    Node JS Online training
    Node JS training in Hyderabad

    ReplyDelete
  9. This idea is mind blowing. I think everyone should know such information like you have described on this post. Thank you for sharing this explanation. Thank you for your post. This is excellent information. It is amazing and wonderful to visit your site

    oracle training in chennai

    oracle training institute in chennai

    oracle training in bangalore

    oracle training in hyderabad

    oracle training

    oracle online training

    hadoop training in chennai

    hadoop training in bangalore

    ReplyDelete
  10. To bring JavaScript functionalities into an Android app via RapidAPI, use the Retrofit library to make API calls. First, create an interface for the API endpoints. Utilize the enqueue method to handle asynchronous calls. To execute JavaScript-based tasks, call the relevant endpoint methods and process responses. Remember to add required dependencies to your project's build.gradle. This approach enables seamless integration of RapidAPI's JavaScript-powered features into your Android application. Get more on JS to android app.

    ReplyDelete

Post a Comment

Popular posts from this blog

Node.js and MongoDB API with Android - Part I

We are starting with a tutorial series which will be multi-part consisting creation of a simple Node.js API with MongoDB integration and later will be connecting the API to Android App. i) We will be creating Node.js API and running it locally on localhost. Node.js is basically written in javascript and will be needing a text editor. Will be using Sublime Text 2 which as powerful editing options with more plugins gives good control to code. You should have basic understanding of Node.js and its specific modules like  Express. Download latest version of Node.js installable archive file from Node.js Downloads . We will be using Express framework module which gives functionality for HTTP Requests. In terminal , enter npm install express --save that will download express installation locally and creates a directory express inside node_modules. Create a folder NodeExample and inside create file main.js . main.js   var express = require('express'); // import...