How to pass data between fragments of an Activity in Android app

This blog demonstrates how to pass values of a variable between two fragments of a single activity. The blog will mainly include the demonstration of passing values between fragments while using BottomSheet Navigation as done in PSLab Android application.

This blog contains the work done by me in the Lux Meter instrument of the PSLab Android app of passing data from LuxMeterConfiguration fragment to LuxMeterData fragment as shown in the featured image to set the high limit for the pointer and to set the update period of the Lux Sensor. The blog will solve the difficult task of communication between two fragments of a single activity. For passing data between multiple fragments of different activities, refer to [1].

How to pass data between fragments?

In this blog, I will pass data from Fragment 2 to Fragment 1 only. But vice versa or passing data from both the fragments can also be made using the same given approach.

  • First, make a static method in Fragment 1 which can set the parameters i.e. the value of the variables as soon as the fragment is inflated as follow
public static void setParameters(int one, int two, int three) {
        Fragment1.firstValue = one;
        Fragment1.secondValue = two;
        Fragment1.thirdValue = three;
  • Now, there is one point to mark that Fragment 1 will be inflated only when Fragment 2 gets destroyed. Else, other than default inflation of Fragment 1, there is no way Fragment 1 can be inflated after navigating to Fragment 2.
  • So, override the OnDestroy() method of Fragment 2 and use the setParameters() method to set the value of variables from Fragment 2 to be used in Fragment 1.
    public void onDestroyView() {
        highValue = getValueFromText(highLimit, 0, highLimitMax);
        updatePeriodValue = getValueFromText(updatePeriod, updatePeriodMin, updatePeriodMax + 100);
        Fragment1.setParameters(selectedSensor, highValue, updatePeriodValue);

Here, the highValue, updatePeriodValue and selectedSensor are the variables being used in the Lux Meter fragment in PSLab Android app. But they can be replaced by the necessary variables as per the app.

So, in this way, we can pass data between the fragments of the same Activity in an Android application. Above demonstration can be extended in passing values between multiple fragments of the same Activity by creating different methods in different fragments.


  1. Blog on how to pass data between fragments of different/same activities:
Continue Reading

Prevent Android Activity from Operating while using Bottom Sheet in PSLab App

This blog demonstrates how to prevent the Android Activity in the background from operating while the Bottom Sheet is up in the foreground. The demonstration will be purely from the work I have done under PR #1355 in PSLab Android repository.

Why prevent the Activity from operating?

When using Bottom Sheet in Android, it is preferable to dim the screen behind the Bottom Sheet to provide a good user experience. But the dimming of the screen is itself an indication that the screen won’t work. Also, if the Bottom Sheet is open and while sliding it, if, by mistake, any button in the background of the bottom sheet gets pressed, then if the function related to that button starts executing then it can create a bad user experience.

For example, in PSLab Android app, in Accelerometer instrument, there are record/pause and delete buttons in the toolbar as shown in figure 1. Now, if the bottom sheet is opened and while closing it if the delete button is by mistake pressed by the user, then whole recorded data gets deleted. Thus, it’s a good practice to prevent the background Activity from operating while Bottom Sheet is opened.

Figure 1. Accelerometer Instrument in PSLab Android app

How to prevent the Activity from operating?

In this demonstration, I will use the method followed by PSLab Android app in creating a Bottom Sheet and making the background dim using a View widget. A step by step guide on how to make a Bottom Sheet as in PSLab Android app can be found in [1] and [2].


The strategy used in solving this problem is setting an OnClickListener to the View that is used to dim the background and close the Bottom Sheet (if open) and hide the View as soon as the method is called. The View is again made visible when an upward slide gesture is made to open the Bottom Sheet.

Follow the below steps to get the desired results:

  • First, in OnCreate() method, set the OnTouchListener to the view.
view.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
  • Now, override the OnSlide() method of the GestureDetector class and add the following code to it.
public void onSlide(@NonNull View bottomSheet, float slideOffset) {
    Float value = (float) slideOffset, 0.0, 1.0, 0.0, 0.8);

So, now test the Bottom Sheet and you will find that the Bottom Sheet will get closed as soon as the click is made outside it if it is opened. The demonstration of the working of the above code is shown in figure 2.

Figure 2. Demonstration of preventing the background Activity from operating while Bottom Sheet is up


  1. Blog on how to make a Bottom Sheet in Android
Continue Reading

How to use Mobile Sensors as Instruments in PSLab Android App

This blog demonstrates how to use built-in mobile sensors in an Android application. This blog will mainly feature my work done in PSLab Android repository of making a Compass and Accelerometer instrument using built-in mobile sensors.

How to access built-in mobile sensors?

Android provides an abstract class called SensorManager which is able to communicate with the hardware i.e. here the sensors in the mobile. But the SensorManager can’t provide continuous data fetched by the sensor. For this, Android provides an interface known as SensorEventListener which receives notifications from SensorManager whenever there is a new sensor data.

How to implement the functionality of sensors in Android app?

Following is a step by step process on how to add support for different sensors in an Android app

  • First, make a new class which extends SensorEventListener and override the default methods.
public class SensorActivity extends Activity implements SensorEventListener {

     public SensorActivity() {
        // Default Constructor      

     public void onAccuracyChanged(Sensor sensor, int accuracy) {

     public void onSensorChanged(SensorEvent event) {

Here, the SensorActivity() is the default constructor of the class and the onAccuracyChanged() and onSensorChanged() methods will be explained soon.

  • Now declare the SensorManager and use the sensor needed in the app.
private final SensorManager mSensorManager;
private final Sensor mAccelerometer;

     public SensorActivity() {
         mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
         mAccelerometer =        mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

Here, I have used Sensor.TYPE_ACCELEROMETER to use the built-in Accelerometer in the device. Some of the other options available are:

  1. TYPE_LIGHT – To measure ambient light
  2. TYPE_MAGNETOMETER – To measure magnetic field along different axis
  3. TYPE_GYROSCOPE – To measure movements (sudden changes) in any particular direction

The list of all available sensors in Android can be found in [1].

  • It is necessary to disable the sensors especially when the activity is paused. Failing to do so can drain the battery in just a few hours.

NOTE: The system will not disable sensors automatically when the screen turns off.

So, to save the battery and make the app efficient, we can use the registerListener method to notify the SensorManager to start fetching data from sensor and unregisterListener to notify it to stop.

protected void onResume() {
         mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);

     protected void onPause() {

The onResume() method activates when the app is resumed from a paused state and the onPause() method is called when the app is paused i.e. some other app draws over the current app.

  • Now coming back to onAccuracyChanged() and onSensorChanged() methods, the onAccuracyChanged() method is used to set the accuracy of a sensor. For example, while using GeoLocation sensor, sometimes the position of the mobile isn’t very accurate and so we can define the accuracy level in this method so that the fetched data is used for calculations only if it is in the provided range. And the onSensorChanged() method is the main method where all the data is processed as soon as the new data is notified.

To get the latest value from the sensor, we can use

public void onSensorChanged(SensorEvent event) {
   data = Float.valueOf(event.values[0]);

Here, the event is an instance of the SensorEvent class which provides the updated data fetched from the sensor. Event.values is used to get the values for any of the three axis including the bias in their values. Following is the list of the index for which we can get a necessary value

values[0] = x_uncalib without bias compensation
values[1] = y_uncalib without bias compensation
values[2] = z_uncalib without bias compensation
values[3] = estimated x_bias
values[4] = estimated y_bias 
values[5] = estimated z_bias

So, in this way, we can add support for any built-in mobile sensor in our Android application.


Continue Reading

How to Add Icons or Menus into the PSLab Android App Toolbar

This blog demonstrates how to add different icons like help, play, pause, etc. and/or menu bar in the toolbar of an Android app along with setting their visibilities on the toolbar i.e. to display the icons only when space is available else to add them in the menu. The topic will be mainly explained by taking the example of menus and icons added to the PSLab app.

How to add a menu in a toolbar?

Following are the steps to add a menu or an icon in the toolbar widget of the Android app

  • First, add toolbar widget to the main layout file as follows
   app:title="@string/compass" />

Here, popupTheme is the theme that activates when inflating the toolbar. Usually, it is kept similar to the default theme of the toolbar.

  • Now as the toolbar is ready, we can make the menu that needs to be inflated on the toolbar. For making a menu, make a folder named menu in the resources folder. Now, add a menu resource file in it by giving a proper name and then add the following code
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android=""
       app:showAsAction="always" />

A detailed explanation of the above code is as follows:

  1. The <menu>…</menu> covers all the items in the menu. There can be sub-menu and also sub-sub-menu too. To make a sub-menu, use <menu>…</menu> inside the main menu.
  2. The <item> tag inside the menu defines a specific item to be included in the menu. The icon attribute of an item is used to show the icon on the toolbar. The title attribute of an item is used to show the text inside the menu if space isn’t available to show the icon on the toolbar. The showAsAction attribute is used to define the method of an item i.e. how the item should be visible to the user. Following are some of the values that showAsAction attribute can take:
    • always – It is used to show the icon of the item on the toolbar everytime
    • never – It is used to show the item as a text in the menu everytime the activity is opened
    • ifRoom – It is used to show the icon on the toolbar if there is enough space else the item is included in the menu

NOTE: Always give IDs to menu items as they are used to distinctly identify the item in the java code.

Figure 1. Example of menu and icons in toolbar in PSLab app

As shown in figure 1, the first two icons have always value in their showAsAction attribute whereas other items have never values in their showAsAction attribute.

  • Now the layout and the menu are ready to be inflated from the Java code. First, the toolbar needs to be set up from the Java code. So find the toolbar with its id and then write the following line in the code.
  • Now the toolbar is ready and so the menu can be inflated on it. So, override the following method to inflate the menu
public boolean onCreateOptionsMenu(Menu menu) {
   MenuInflater inflater = getMenuInflater();
   inflater.inflate(, menu);
   return true;

Here, the getMenuInflater() method is used to inflate the menu on the toolbar.

  • Now override the onCreateOptionsMenu() method to do the predefined task of selecting the icon or the item from the menu.
public boolean onOptionsItemSelected(MenuItem item) {
   switch (item.getItemId()) {
           // Do something
   return true;

So, in this way a menu can be made so that the number of items delivered to the user can be increased by using the minimum space possible.


  1. – Android Developers guide on how to make a menu in Android
Continue Reading

Implementing Custom Rotary Knobs and Circular Positioning in the Multimeter in the PSLab Android App

In my previous blog [2I have discussed about how to implement  normal rotary knob using an open source library, this blog will be about the new user interface (UI) of multimeter in the PSLab Android app, how a custom rotary knob is implemented in it and how how the text views are positioned circular in them.

Implementation of Custom Rotary Knob

In the PSLab device  the rotary knob is implemented using the BeppiMenozzi Knob library[1] as by doing this we don’t have to manually create the extra class for the knob and we don’t have to write the code from scratch.

Figure 1: A basic rotary knob

Figure 1 shows a basic knob implemented using the BeppiMenozzi library whereas figure 2 shows the implementation of a custom knob using the basic knob.

Figure 2: A custom Knob

Steps of making a Custom-Knob using a simple Knob

  1. Implement the the basic knob using the steps given in my previous knobs explained in my previous blogs.
  2. Download the images of the knob which has to be implemented.
  1. Using the above code amend the knob as per the requirement. The advantage of using the beppiMonzi library is that the knob is fully amenable  , we can even define the minimum and maximum angle and many more stuffs can be done using the library.






Figure 3: Showing the implementation of other custom knobs

The above figure shows the example of custom knobs implemented using the simple knob and by following the steps.

Implementation Circular positioning

One of the other major issues while making the new UI of the multimeter is the positioning of text-view around the circular knob. The issue was made overcome by implementing a circular positioning constraints in the text-views.

Steps of implementing circular positioning

  1. Use the constraint layout version 1.1.0 or above as the previous versions do not support the circular positioning feature.
  2. Add the circular constraint individually to every text-view.

The above code snippets shows the addition od circular constraints added to a text-view. Using these constraint it decides positions the views relative to another views at a particular angle which thus makes up circular positioning.

Thus, this is how we can implement circular positioning in the views.


  1. BeppiMenozzi Knob Library
  2. Rotary knob Blog
Continue Reading

Implementing Notification Action Buttons in Open Event Frontend

The Open-Event-Frontend allows the event organiser to create access codes for his or her event.  Access codes can be used to password protect hidden tickets reserved for sponsors, members of the press and media. Notifications are an important part of the project. We show each registered user notifications based on their activity. This blog post goes over the implementation of the notification action buttons in the notification panel.

Notification Action Model

The model for Notification action is very simple. It has the following variables:

  1. Subject: The subject of the notification. E.g. ‘event’, ‘order’ etc.
  2. actionType: The action that can be taken by the user for that notification. E.g: ‘view’, ‘submit’.
  3. subjectId: The id of the subject. In case of an event, it will store the event id. Similarly for other cases.
  4. Link: The link to be applied to the button.

import attr from 'ember-data/attr';
import ModelBase from 'open-event-frontend/models/base';
import { belongsTo } from 'ember-data/relationships';

export default ModelBase.extend({
  subject    : attr('string'),
  actionType : attr('string'),
  subjectId  : attr('number'),
  link       : attr('string'),

  notification: belongsTo('notification')

Action Button Title

We make use of ember computed property to determine the action button title. The title of the button depends on the subject and the actionType defined in the notification-action model. The actionType can be one of ‘download’, ‘submit’ and ‘view’. If the action type is ‘download’ and the subject is ‘invoice’, then the button title will be “Download Invoice”. Similarly, for other cases, we do the same.

buttonTitle: computed('subject', 'actionType', function() {
    let action;
    const actionType = this.get('actionType');
    switch (actionType) {
      case 'download':
        action = 'Download';

      case 'submit':
        action = 'Submit';

        action = 'View';

    let buttonSubject;
    const subject = this.get('subject');
    switch (subject) {
      case 'event-export':
        buttonSubject = ' Event';

      case 'event':
        buttonSubject = ' Event';

      case 'invoice':
        buttonSubject = ' Invoice';

      case 'order':
        buttonSubject = ' Order';

      case 'tickets-pdf':
        buttonSubject = ' Tickets';

      case 'event-role':
        buttonSubject = ' Invitation Link';

      case 'session':
        buttonSubject = ' Session';

      case 'call-for-speakers':
        if (this.get('actionType') === 'submit') {
          buttonSubject = ' Proposal';
        } else {
          buttonSubject = ' Call for Speakers';

        // Nothing here.

    return action + buttonSubject;

Action Button Route

The route that the button will lead to depends on the subject of the action. If the link is provided in the notification action, we simply set it on the button otherwise we use the subject to derive the route name. For e.g., if the subject is an event, then the route will be “events.view”.

   * The route name to which the action button will direct the user to.
  buttonRoute: computed('subject', function() {
    const subject = this.get('subject');
    let routeName;
    switch (subject) {
      case 'event-export':
        routeName = 'events.view';

      case 'event':
        routeName = 'events.view';

      case 'invoice':
        routeName = 'orders.view';

      case 'order':
        routeName = 'orders.view';

      // Nothing here.
    return routeName;


We simply check if the link exists or not. If it does then we simply use it otherwise we use the computed button route name.

     {{#link-to tagName='button' class='ui blue button'}}
         {{t action.buttonTitle}}
    {{#link-to action.buttonRoute action.subjectId tagName='button' class='ui blue button'}}
         {{t action.buttonTitle}}


Continue Reading

Measuring capacitor in PSLab and its Bugs

In this blog I will discuss about how we have measured capacitance in Pocket Science Lab and the  issues in capacitance measurement which was finally solved.

Measuring capacitance in PSLab device

To measure capacitance we need to go to the multimeter instrument from the instrument section of the PSLab

Figure 1.  Showing Multimeter Tile

Capacitance in PSLab is measured by keeping the capacitor or the element of which capacitance is to be measured between the CAP and ground pin.

 Figure 2.  Showing CAP pins in PSLab

For measuring capacitance in PSLab we use a specific method in which we supply a constant current to the CAP pin and thus we charge the capacitor to the maximum level, the math involved in it is as follow:-

We know that

Q{charge stored} = C*V


Q= I * time


I=current (constant)

Thus the capacitance

C = Q / V


C = I*time / V (measured). – (1)

Therefore we know the current supplied, we know the voltage measured and we have also set the time to charge the capacitor and thus we get the capacitance from equation (1).

Code implementation for measuring capacitance

This is the primary code for getting the data for measuring capacitance in which we pass the current range and the current time through which the data gets fetched from the device which is then further processed in another function in which we finally get the capacitance.

public double[] getCapacitance(int currentRange, int chargeTime) { // time in uSec
        try {
            Thread.sleep((long)(chargeTime * 1e-6 + .02));
            int VCode;
            do VCode = mPacketHandler.getVoltageSummation();
            while (VCode == -1);
            double v = 3.3 * VCode / 4095;
            double chargeCurrent = this.currents[currentRange];
            double c = 0;
            if (v != 0)
                c = (chargeCurrent * chargeTime * 1e-6 / v - this.SOCKET_CAPACITANCE) / this.currentScalars[currentRange];
            return new double[] {
        } catch (IOException | InterruptedException e) {
        return null;

In the above function we can clearly see how we send the bytes in the device by the sendByte function through which various functions are sending current, setting voltage, setting current range etc are done in the device and then we can see how the voltage measured is taken using the getVoltageSummition method (of packet Handler class) , how we get the current and finally using them in equation (1) we get the capacitance of the element.

The following implementation is taken from the PSLab desktop app where the same method is used to measure capacitance.

Bugs in measuring capacitance

The capacitance measurement although was working in the desktop app but had bugs in the android app. It could never read the correct value also everytime gave a null value for capacitance.

Figure 3.  Showing null value for capacitance  PSLab

Solving the Bug [2]

After a deep research in the inside  the code of the capacitance measurement it was found that the error was caused while fetching the incorrect data from the device and processing it. The device gives a negative one value when there is any error in capacitance measurement  and that was being processed, thus the error was solved by introducing a do while loop as shown

 do VCode = mPacketHandler.getVoltageSummation();
 while (VCode == -1);

And thus now only the correct data fetched is processed further and thus the bug was solved after which the capacitance measurement was correct.


Continue Reading

Onsite Attendee in Open Event Server

The Open Event Server enables organizers to manage events from concerts to conferences and meetups. It offers features for events with several tracks and venues. The Event organizers may add orders on behalf of others and accept payments onsite. This blog post goes over the implementation of the onsite attendee feature in the Open Event Server.


Normally we expect the payload for a POST request of order to contain already created attendees also. In this case we want to create the attendees internally inside the server. Hence we need some way to differentiate between the two types of orders. The most basic and easy to implement option is to use a query parameter to specify if the attendees are onsite or not. We use ?onsite=true in order to specify that the attendees are onsite and hence should be created internally.

In the POST request, we check if the query parameters contains the onsite param as true or not. If it is true then we create the attendees using a helper function. The helper function will be discussed in detail later in the article.

# Create on site attendees.
if request.args.get('onsite', False):
elif data.get('on_site_tickets'):
    del data['on_site_tickets']
require_relationship(['ticket_holders'], data)



In order to create attendees on the server, we need the information about each ticket bought and it’s quantity. This data is expected in the format declared in the OnsiteTicketSchema.

class OnSiteTicketSchema(SoftDeletionSchema):
    class Meta:
        type_ = 'on-site-ticket'
        inflect = dasherize

    id = fields.Str(load_only=True, required=True)
    quantity = fields.Str(load_only=True, required=True)

Creating onsite Attendees

Following are the few points which we need to focus on when creating onsite attendees:

  1. Validate if the ticket’s data is provided or not. We raise an error if the ticket data is not provided.
  2. Verify if the ticket is sold out or not. We raise an error if the ticket is sold out.
  3. In case an error is raised in any step then we delete the already created attendees. This is a very important point to keep in mind.

if not on_site_tickets:
        raise UnprocessableEntity({'pointer': 'data/attributes/on_site_tickets'}, 'on_site_tickets info missing')

ticket_sold_count = get_count(db.session.query(
                                      filter_by(ticket_id=int(, deleted_at=None))

        # Check if the ticket is already sold out or not.
        if ticket_sold_count + quantity > ticket.quantity:
            # delete the already created attendees.
            for holder in data['ticket_holders']:
                ticket_holder = db.session.query(TicketHolder).filter(id == int(holder)).one()
                except Exception as e:
                    logging.error('DB Exception! %s' % e)

            raise ConflictException(
                {'pointer': '/data/attributes/on_site_tickets'},
                "Ticket with id: {} already sold out. You can buy at most {} tickets".format(ticket_id,
                                                                                             ticket.quantity -

The complete method can be checked here.




Continue Reading

Pop-Up in Meilix Generator

Meilix Generator has fields which the user needs to fill up. There are fields for the required information and for customization process too. This solves the problems and helping user to know about the requirement of each field. We implemented a pop-menu which appears and tell about that particular field.

We will here describe only the implementation of email pop-up.

function hideDiv(){
document.addEventListener("click", hideDiv);
function noti()
	alert("Email is used to mail user the link to the build ISO");

We have embedded a javascript in html file.
Function hideDiv contains document.getElementsByClassName() method.

The getElementsByClassName() method returns a collection of all elements in the document with the specified class name.

Then we have a document.addEventListener() method with click and hideDiv function as the parameters. It also contain a function noti which get toggle at the time of click and display the alert message. hideDiv closes the toggle when clicked on the cross button again.

<label class="heading" id="label" for="email">Email *&ensp;<img src="{{ url_for('static', filename='alert.jpg') }}" height="20" width="20" onclick="noti()"></label>


We implemented a question mark after the email line which when clicked showed the following message on the webapp.

This will help user to know the requirement of the particular field.

Through the help of the required function and implementation of the button, we can embedded a help icon which pop-up to give required option present in the webapp.

These are different pop-ups that are currently present in the webapp. User can know about the particular field by clicking on any of the pop-up.


  1. HTML getElementsByClassName():
  2. Bootstrap 4 Form:

Continue Reading

UID file configuration for Meilix

Meilix has by default one user which is hotelos. Each user has a UID known as Unique Identification Display. Each UID is assigned some unique number. The range for uid is from 1000 to 65000. The login manager doesn’t create user which doesn’t have a uid in this range.


We found out that hotelos has a uid = 999 through this autologin file meilix-default-settings/usr/share/initramfs-tools/scripts/casper-bottom/15autologin. Therefore sddm would not accept this as the username.


Way 1: Increase the uid of the hotelos

Way 2: Decrease the default sddm uid through configuration file

We here tried with the second approach to decrease the uid of the sddm to 500, so that it will take hotelos as the default user.


# Hidden users, this is if any system users fall within your range, see /etc/passwd on your system.

# Maximum user id for displayed users

# Minimum user id for displayed users
MinimumUid=500 #My UID is 999


This is one of the way through which we have decreased the UID to 500.

We can use id -u in the terminal to check the uid of the user.

Root has uid = 0.

We can see different operations uid in the file /etc/passwd .

It looks like this:

We have a file /etc/login.defs where we can manage the max and min uid for the user.

# Min/max values for automatic uid selection in useradd
UID_MIN                     	1000
UID_MAX                    	60000
# System accounts
#SYS_UID_MIN              	100
#SYS_UID_MAX              	999

We can modify it to accept hotelos as the user.

\sed -i '/UID_MIN/ c\UID_MIN 998' /etc/login.defs


This will change the UID_MIN value to 998.


  1. User ID definition:
  2. SDDM User Issue:
Continue Reading
Close Menu