Implementing ProGuard in Open Event Orga App

In the Open Event Orga App there has been an issue with the size of the app. So to decrease the size of the app, we had to enable Proguard. By implementing proguard the size of the app has reduced from 5.9 Mb to 2.9 Mb. The following article shows the steps taken to implement Proguard.

  • Firstly the following parameters need to set to true in the the app level build.gradle file.
  release {
      minifyEnabled true
      shrinkResources true
      proguardFiles getDefaultProguardFile(‘proguard-android.txt’), ‘proguard-rules.pro’

The built-in shrinker in minify enabled removes the dead code. It doesn’t obfuscate or optimizes the code. In this section of code, we also set the proguard-rules.pro file in which all the rules regarding code obfuscation are set. The file is a custom file unlike the default proguard-android.txt file which is already a part of Android Studio.

  • Now we head over to the proguard-rules.pro file. But first we need to understand the 2 most important terms –dontwarn and –keep class.

 

2.1 -dontwarn → When proguard is implemented, code obfuscation takes place and the name of the classes get shortened to single letters. Because of this there might be a few conflicts. But there might be some unresolved references in the obfuscated code. dontwarn ignores all these references.

2.2 –keep class → Suppose there are certain classes which shouldn’t be obfuscated then they are preceded with keep class annotation.

 

  • In the proguard-rules.pro file the following lines are added
# Platform calls Class.forName on types which do not exist on Android to determine platform.
dontnote retrofit2.Platform
# Platform used when running on Java 8 VMs. Will not be used at runtime.
dontwarn retrofit2.Platform$Java8
# Retain generic type information for use by reflection by converters and adapters.
keepattributes Signature
# Retain declared checked exceptions for use by a Proxy instance.
keepattributes Exceptions

The keepattributes annotation is basically used for Generics which are JAVA JDK 5 and higher. It basically prevents the code from obfuscation.

  • Now Retrofit classes also need to be obfuscated. For that we add the following lines of code. The obfuscation considerably reduces the size of the app.
-dontwarn okio.**

-dontwarn com.squareup.okhttp.**
  • The model classes need to be prevented from getting obfuscated or else it may lead to app crash. Hence these classes need to be kept and so we add the following lines of code to prevent app crash. The link for the PR which fixed the app crash cause due to buggy proguard rule.
keep class org.fossasia.openevent.app.data.** {
*;
}
  • The orga app uses the Jackson library for parsing JSON data. Proguard rules also needs to be applied for this library.
# Jackson
keepattributes *Annotation*,EnclosingMethod,Signature
keepnames class com.fasterxml.jackson.** { *; }
dontwarn com.fasterxml.jackson.databind.**
keep class org.codehaus.** { *; }
-keepclassmembers public final enum org.codehaus.jackson.annotate.JsonAutoDetect$Visibility {
  public static final org.codehaus.jackson.annotate.JsonAutoDetect$Visibility *;
}
keep class com.github.jasminb.** { *; }
  • The other libraries used in the app also have specific proguard rules. These are listed below.
# General
keepattributes SourceFile,LineNumberTable,*Annotation*,EnclosingMethod,Signature,Exceptions,InnerClasses
keep class android.support.v7.widget.SearchView { *; }

keep class com.github.mikephil.charting.** { *; }
G
keep public class * extends com.bumptech.glide.module.AppGlideModule
keep class com.bumptech.glide.GeneratedAppGlideModuleImpl

 

References:

  1. Medium article by Jon Finerty https://medium.com/@jonfinerty/beginner-to-proguard-b3327ff3a831

Official Developer documentation  https://developer.android.com/studio/build/shrink-code

Continue ReadingImplementing ProGuard in Open Event Orga App

Add More Languages to a Skill in SUSI.AI

The SUSI SKill CMS provides skills in multiple languages. Often there are similar skills in different languages. For example, there is a News skill in English and Samachar skill in Hindi. Then why not link them together and mark one as the translation of the other. This will help the user to reach and explore the desired skill in an efficient way. Moreover, it may be easier to type ‘News’ than ‘समाचार’ and find the required skill through translations. So here it has been explained how to link two SUSI skills as translations.

Server side implementation

Create a skillSupportedLanguages.json file to store the related skills together as translations and make a JSONTray object for that in src/ai/susi/DAO.java file. The JSON file contains the language name and the skill name in that language, wrapped in an array.

public static JsonTray skillSupportedLanguages;

Path skillSupportedLanguages_per = skill_status_dir.resolve("skillSupportedLanguages.json");
Path skillSupportedLanguages_vol = skill_status_dir.resolve("skillSupportedLanguages_session.json");
skillSupportedLanguages = new JsonTray(skillSupportedLanguages_per.toFile(), skillSupportedLanguages_vol.toFile(), 1000000);
OS.protectPath(skillSupportedLanguages_per);
OS.protectPath(skillSupportedLanguages_vol);

Now create an API that accepts the skill details and translation details and stores them in the JSON file. Create UpdateSupportedLanguages.java class for the API.

Endpoint: /cms/updateSupportedLanguages.json

Minimum user role: Anonymous

Params:

  • Model
  • Group
  • Language (language of the skill for which translation is to be added)
  • Skill (name of the skill for which translation is to be added)
  • New language (translation language of the skill)
  • New skill name (name of the skill in translated language)

When a new translation is added check if it already exists in the translation group stored in the skillSupportedLanguages.json. Use the DAO object and loop over the array, check is the language name and the language name already exists. If yes then simply return.

if (!alreadyExixts) {
    groupName.put(createSupportedLanguagesArray(language_name, skill_name, new_language_name, new_skill_name));
}

Otherwise, create a new object containing the new language name and the skill name in that language and add it to the translation group.

public JSONArray createSupportedLanguagesArray(String language_name, String skill_name, String new_language_name, String new_skill_name) {
    JSONArray supportedLanguages =  new JSONArray();

    JSONObject languageObject = new JSONObject();
    languageObject.put("language", language_name);
    languageObject.put("name", skill_name);
    supportedLanguages.put(languageObject);

    JSONObject newLanguageObject = new JSONObject();
    newLanguageObject.put("language", new_language_name);
    newLanguageObject.put("name", new_skill_name);
    supportedLanguages.put(newLanguageObject);

    return supportedLanguages;
}

Add this API to SusiServer.java

// Add translation to the skill
UpdateSupportedLanguages.class

Resources

 

Continue ReadingAdd More Languages to a Skill in SUSI.AI

Using Android Architecture Components in Organizer App

In the Open Event Organizer Android App there is an issue with the Memory leaks, Data persistence on configuration changes and difficulty in managing the Activity lifecycle. So as to deal with these issues we have implemented Android Architecture Components.

The first step towards moving on with AAC’s was the conversion of a presenter class to a ViewModel class and then implementing LiveData in the refactored class.

LiveData

It is an Observable data holder. It notifies the observers whenever there is change in the data so that the UI can be updated.

Livedata is also bound to the lifecycle which means that it will be observing changes only when the activity is in started or resumed state and hence there is no chance of memory leaks or null pointer exceptions.

ViewModel

The ViewModel class is designed to hold and manage UI-related data in a life-cycle conscious way. This allows data to survive configuration changes such as screen rotations.

In the following I’ll be explaining how the LoginViewModel class was made in the Orga App.

Steps

  • Creating one’s own custom ViewModelFactory. This is done so as to follow the Single Responsibility Principle. This custom class extends the ViewModelProvider.Factory and handles the creation of View Models. Adding this class also ensures that a Constructor can also get injected in the View Model class.
@Singleton
public class OrgaViewModelFactory implements ViewModelProvider.Factory {

  private final Map<Class<? extends ViewModel>, Provider<ViewModel>> creators;

  @Inject
  public OrgaViewModelFactory(Map<Class<? extends ViewModel>, Provider<ViewModel>> creators) {
      this.creators = creators;
  }

  @NonNull
  @Override
  @SuppressWarnings({“unchecked”, “PMD.AvoidThrowingRawExceptionTypes”, “PMD.AvoidCatchingGenericException”})
  public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
      Provider<? extends ViewModel> creator = creators.get(modelClass);
      if (creator == null) {
          for (Map.Entry<Class<? extends ViewModel>, Provider<ViewModel>> entry : creators.entrySet()) {
              if (modelClass.isAssignableFrom(entry.getKey())) {
                  creator = entry.getValue();
                  break;
              }
          }
      }
      if (creator == null) {
          throw new IllegalArgumentException(“unknown model class “ + modelClass);
      }
      try {
          return (T) creator.get();
      } catch (Exception e) {
          throw new RuntimeException(e);
      }
  }
}
  • Injecting this custom ViewModelFactory into the ViewModelModule. Adding the method bindLoginViewModel with the LoginViewModel as its parameter. Always add any new ViewModel class into the ViewModelModule otherwise it might show DaggerAppComponent errors.
@Module
public abstract class ViewModelModule {

  @Binds
  @IntoMap
  @ViewModelKey(LoginViewModel.class)
  public abstract ViewModel bindLoginViewModel(LoginViewModel loginViewModel);

  @Binds
  public abstract ViewModelProvider.Factory bindViewModelFactory(OrgaViewModelFactory factory);

}
  1. Refactoring the LoginPresenter to LoginViewModel class and extending it to ViewModel.
  2. In the fragment class injecting the ViewModelProviderFactory.
@Inject
ViewModelProvider.Factory viewModelFactory;
  • Pass this parameter in the ViewModelProviders.of( ) method as follows:
loginFragmentViewModel = ViewModelProviders.of(this, viewModelFactory).get(LoginViewModel.class);
  • Now the only task in hand is the use of LiveData in the ViewModels and observing the LiveData from the Fragments. In the following LiveData has been applied to observe the state of Progress Bar. When the login button is pressed, the value of MutableLiveData<Boolean> progress is set to true.
public void login() {
  compositeDisposable.add(loginModel.login(login)
      .doOnSubscribe(disposable -> progress.setValue(true))
      .doFinally(() -> progress.setValue(false))
      .subscribe(() -> isLoggedIn.setValue(true),
          throwable -> error.setValue(ErrorUtils.getMessage(throwable))));
}

 

  • This change in state is observed by the following code in the fragment class:
loginFragmentViewModel.getProgress().observe(this, this::showProgress);

On observing this, the showProgress is called which handles the visibility if the progress bar. Currently as the progress value was set to True, the progress bar is visible till the processing goes on.

  • Once the login takes place the progress of the LoginViewModel is set to false and the progress bar gets hidden, again which gets observed in the fragment class.

References:

https://android.jlelse.eu/android-architecture-components-livedata-1ce4ab3c0466

Continue ReadingUsing Android Architecture Components in Organizer App

Adding Open Event Orga App as a Product Flavor on FDroid

To release the orga app on fdroid, product flavors need to be added to the app. This means that 2 different packages need to be maintained that handle the code for fdroid and playstore separately. For eg. There are certain proprietary software that are used in the app such as Google Play services which won’t get accepted on fdroid. Hence alternatives need to be found out and separate code has to be maintained.  

Steps:

  • Go to the build.gradle file where in the Android section add the following line of code in the groovy language. We specify the flavorDimension to be default and then add the productFlavor tag. Inside this tag there will be 2 more sub tags namely fdroid and playStore. These are the 2 different flavors we will be maintaining in the app. Because of this command, 4 different build variants will be created namely : fdroidDebug, fdroidRelease, playStoreDebug and playStoreRelease. The dimension for each is specified to be default.
flavorDimensions “default”

productFlavors {
  fdroid {
      dimension “default”
  }

  playStore {
      dimension “default”
  }
}
  • Now as testCoverage is being used in the app the file name also need to be changed from debug to playStore. So firstly go to the travis.yml file and change the testDebugUnitCoverage command to testPlayStoreDebugUnitCoverage. Hence when the travis will build, the modified command will be executed rather than the old command. We could also have used testfdroidDebugUnitCoverage.Following is the code snippet from the travis.yml file.
script:
./gradlew build
./gradlew testPlayStoreDebugUnitTestCoverage
  • Now command for testCoverage also needs to be changed in the config.yml. So navigate to this file and modify the command.
– run:
  name: Test Coverage
  command: ./gradlew testPlayStoreDebugUnitTestCoverage
  • Now navigate to the update-apk.sh script where we will change the name of the output apk in case of fdroid build and playStore build. As can be seen below we have first changed the name of the json file in each build. Also the name of the folder where they get generated are changed.
\cp -r ../app/build/outputs/apk/playStore/*/**.apk .
\cp -r ../app/build/outputs/apk/fdroid/*/**.apk .
\cp -r ../app/build/outputs/apk/playStore/debug/output.json playStore-debug-output.json
\cp -r ../app/build/outputs/apk/playStore/release/output.json playStore-release-output.json
\cp -r ../app/build/outputs/apk/fdroid/debug/output.json fdroid-debug-output.json
\cp -r ../app/build/outputs/apk/fdroid/release/output.json fdroid-release-output.json
  • Also the apk names in fastlane  are changed for playStore with the help of the following code.
gem install fastlane
fastlane supply –apk app-playStore-release.apk –track alpha –json_key ../scripts/fastlane.json –package_name $PACKAGE_NAME

Resources

  1. Official fdroid website https://f-droid.org/en/
  2. Google Developer website https://developer.android.com/studio/build/build-variants
Continue ReadingAdding Open Event Orga App as a Product Flavor on FDroid

Implement Tests for Feedback List in Open Event Orga App

In the Open Event Orga App test have been written for all the presenters and viewmodel classes to ensure that the implemented functionalities work well.

In the following blog post I have discussed one particular test which I implemented which is the FeedbackList Presenter Test.

Implementation

  1. Instantiation of the variables.
@Rule
public MockitoRule mockitoRule = MockitoJUnit.rule();
@Mock
public FeedbackListView feedbackListView;
@Mock
public FeedbackRepository feedbackRepository;

We should first know the meaning of the Annotations being used:

@Rule : It tells mockito to create the mocks based on the @Mock annotation. This annotation always needs to be used.

@Mock: It tells Mockito to mock the FeedbackListView interface and FeedbackRepository class.

Here we are mocking 3 classes namely: MockitoRule, FeedbackListView, FeedbackRepository.

Before moving forward we first need to understand the meaning of Mock. A mock object is a dummy implementation for an interface or a class in which you define the output of certain method calls. Mock objects are configured to perform a certain behavior during a test. They typically record the interaction with the system and tests can validate that.

 

private static final List<Feedback> FEEDBACKS = Arrays.asList(
  Feedback.builder().id(2L).comment(“Amazing!”).build(),
  Feedback.builder().id(3L).comment(“Awesome!”).build(),
  Feedback.builder().id(4L).comment(“Poor!”).build()
);

The list of feedbacks is populated with demo values which can be used for testing purpose later.

2) The @Before annotation is applied before the set up. Before any tests are created, the setUp( ) is executed. A feedbackListPresenter object is created and the required parameters are passed. The RxJava Plugin’s setIoSchedulerHandler, setComputationSchedulerHandler and setInitmainThreadSchedulerHandler use the Scheduler.Trampoline( ) .  It lets the internal call Observable call to end before asserting the result.

setIOSchedulerHandler( ) -> It basically is a type of Scheduler which handles the Input and Output of the RxJava code.

setComputationSchedulerHandler( ) -> It is another Scheduler which handles the computations which are carried out during call to RxJava methods.

setInitMainThreadSchedulerHandler( ) -> It is called to notify the Scheduler that the IO operations would be carried out on the main thread.

@Before
public void setUp() {
  feedbackListPresenter = new FeedbackListPresenter(feedbackRepository);
  feedbackListPresenter.attach(ID, feedbackListView);

  RxJavaPlugins.setIoSchedulerHandler(scheduler -> Schedulers.trampoline());
  RxJavaPlugins.setComputationSchedulerHandler(scheduler -> Schedulers.trampoline());
  RxAndroidPlugins.setInitMainThreadSchedulerHandler(schedulerCallable -> Schedulers.trampoline());
}

Some of the tests are discussed below:

→  The following test is written to ensure that the feedback list gets updated automatically after a feedback is received.

@Test
public void shouldLoadFeedbackListAutomatically() {
  when(feedbackRepository.getFeedbacks(anyLong(), anyBoolean())).thenReturn(Observable.fromIterable(FEEDBACKS));

  feedbackListPresenter.start();

  verify(feedbackRepository).getFeedbacks(ID, false);
}

As can be seen above , I have used the when and return functionality of Mockito. It is basically used to check the return type of the object. So when the required parameters are passed in the getFeedback( ) , then the return type of what is expected is mentioned in the thenReturn( ).

verify ensures that the getFeedback( ) is called on the feedbackfeedbackRepository mock only.

→ The following test is written to ensure that there is an error message on loading data after swipe refresh is made. Firstly the list of feedbacks is fetched from the feedbackRepository with the help of getFeedbacks( ) where the parameters event id and the boolean variable true are passed. Then the thenReturn( ) has the statement Observable.error(Logger.TEST_ERROR) which is actually written to specify the expected result we want i.e in this case we are expecting the TEST_ERROR statement as a response and hence it is written before.

At the end it is verified using the statement verify statement where the feedbackListView is passed and the error is captured.

 

@Test
public void shouldShowErrorMessageOnSwipeRefreshError() {
  when(feedbackRepository.getFeedbacks(ID, true)).thenReturn(Observable.error(Logger.TEST_ERROR));

  feedbackListPresenter.loadFeedbacks(true);

  verify(feedbackListView).showError(Logger.TEST_ERROR.getMessage());
}

3) After the tests have been applied, the RxJava plugins are reset.

@After
public void tearDown() {
  RxJavaPlugins.reset();
  RxAndroidPlugins.reset();

}

Resources:

→ Mockito tutorial :

http://www.vogella.com/tutorials/Mockito/article.html

→ Testing in RxJava:

https://stackoverflow.com/questions/40233956/how-to-use-schedulers-trampoline-inrxjava

Continue ReadingImplement Tests for Feedback List in Open Event Orga App

Adding Support for Playing Audio in SUSI iOS App

SUSI.AI supports various actions like the answer, map, table, video play and many more. You can play youtube videos in the chat screen. It also supports for playing audio in the chat screen. In this post, we will see that how playing audio feature implemented in SUSI iOS.

Getting audio action from server side –

In the chat screen, when we ask SUSI to play audio, we get the audio source from the server side. For example, if we ask SUSI “open the pod bay door”, we get the following action object:

"actions": [
{
"type": "audio_play",
"identifier_type": "youtube",
"identifier": "7qnd-hdmgfk"
},
{
"language": "en",
"type": "answer",
"expression": "I'm sorry, Dave. I'm afraid I can't do that."
}
]

In the above action object, we can see that we get two actions, audio_play and answer. In audio_play action, we are getting an identifier type which tells us about the source of audio. Identifier type can be youtube or local or any other source. When the identifier is youtube, we play audio from youtube stream. In identifier, we get the audio file path. In case of youtube identifier type, we get youtube video ID and play from youtube stream. In answer action type, we get the expression which we display in chat screen after thumbnail.

Implementing Audio Support in App –

We use Google’s youtube Iframe API to stream audio from youtube videos. We have a VideoPlayerView that handle all the iFrame API methods and player events with help of YTPlayer HTML file.

Presenting the YouTubePlayerCell –

If the action type is audio_play, we are presenting the cell in chat screen using cellForItemAt method of UICollectionView.

if message.actionType == ActionType.audio_play.rawValue {
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ControllerConstants.youtubePlayerCell, for: indexPath) as? YouTubePlayerCell {
cell.message = message
cell.delegate = self
return cell
}
}

Setting size for cell –

Using sizeForItemAt method of UICollectionView to set the size.

if message.actionType == ActionType.audio_play.rawValue {
return CGSize(width: view.frame.width, height: 158)
}

In YouTubePlayerCell, we fetch thumbnail and display in the cell with a play button. On clicking the play button, we open the player and stream music.

Final Output –

Resources –

  1. Apple’s Documentations on sizeForItemAt
  2. SUSI API Sample for Audio Play Action
  3. YouTube iFrame API for iOS
  4. Apple’s Documentations on cellForItemAt
Continue ReadingAdding Support for Playing Audio in SUSI iOS App

Selecting Multiple Tickets in Open Event Android

Open Event Android allows the user to select multiple tickets for an event this blog post will guide you on how its done. Ticket Id and quantity of ticket selected is stored in the form of List of pair. The first element of the List is the Id of the ticket and the second element is its quantity.

private var tickeIdAndQty = ArrayList<Pair<Int, Int>>()

Whenever the user selects any ticket using the dropdown the following snippet of code is executed. handleTicketSelect takes id and quantity of the selected ticket and search if any pair with passed id as the first element exists in the ticketIdAndQty list, if exists it updates that record else it inserts a new pair with given id and quantity into the list.

private fun handleTicketSelect(id: Int, quantity: Int) {
       val pos = ticketIdAndQty.map { it.first }.indexOf(id)
       if (pos == –1) {
           ticketIdAndQty.add(Pair(id, quantity))
       } else {
           ticketIdAndQty[pos] = Pair(id, quantity)
       }

When the user selects register the ticketIdAndQty list which contains details of selected tickets is added to the bundle along with the event id and are passed to attendee fragment. Attendee fragment allows the user to fill in other details such as country, payment option, first name etc.

Later attendee fragment with the help of attendee view model creates individual attendee on the server

rootView.register.setOnClickListener {
           if (!ticketsViewModel.totalTicketsEmpty(ticketIdAndQty)) {
               val fragment = AttendeeFragment()
               val bundle = Bundle()
               bundle.putLong(EVENT_ID, id)
               bundle.putSerializable(TICKET_ID_AND_QTY, ticketIdAndQty)
               fragment.arguments = bundle
               activity?.supportFragmentManager
                       ?.beginTransaction()
                       ?.replace(R.id.rootLayout, fragment)
                       ?.addToBackStack(null)
                       ?.commit()
           } else {
               handleNoTicketsSelected()
           }
       }

When the register is selected an attendee is created for every ticket id inside ticketIdandQty list wherever the second element of the pair that is quantity is greater than zero. FFirst name last name, email and other information is taken from the text views populated on the screen and attendee object is created using these data. Lastly, createAttendee view model function is called passing the generated attendee, country, and selected payment option. The former calls service layer function and created an attendee by making a post request to the server.

 ticketIdAndQty?.forEach {
                   if (it.second > 0) {
                       val attendee = Attendee(id = attendeeFragmentViewModel.getId(),
                               firstname = firstName.text.toString(),
                               lastname = lastName.text.toString(),
                               email = email.text.toString(),
                               ticket = TicketId(it.first.toLong()),
                               event = eventId)
                       val country = if (country.text.isEmpty()) country.text.toString() else null
                       attendeeFragmentViewModel.createAttendee(attendee, id, country, selectedPaymentOption)
                   }
               }

The above-discussed procedure creates one attendee for every ticket quantity which means if a user select ticket id 1 with 3 quantity and ticket id 2 with 5 as quantity total 8 attendees will be generated. Later after successfully generating the attendee’s order is created. Every order has an array of attendees along with other other related information.

Resources

Continue ReadingSelecting Multiple Tickets in Open Event Android

How webclient Settings are Implemented in SUSI.AI Accounts

The goal of accounts.susi is to implement all settings from different clients at a single place where user can change their android, iOS or webclient settings altogether and changes should be implemented directly on the susi server and hence the respective clients. This post focuses on how webclient settings are implemented on accounts.susi. SUSI.AI follows the accounting model across all clients and every settings of a user are stores at a single place in the accounting model itself. These are stored in a json object format and can be fetched directly from the ListUserSettings.json endpoint of the server.

Continue ReadingHow webclient Settings are Implemented in SUSI.AI Accounts

Updating User information in Open Event Android

A user can update its information such as first name, last name from the Edit Profile Fragment in Open Event Android. Edit Profile Fragment can be accessed from the menu inside the Profile page. On opening Edit Profile Fragment user can interact with the simple UI to update his/her information. This blog post will guide you on how its implemented in Open Event Android.

To update a User we send a patch request to Open Event Server. The patch request contains the Updated User as body and auth token as header and it returns the updated user in response. Following it what the interface method looks like

@PATCH(“users/{id}”)
fun updateUser(@Body user: User, @Path(“id”) id: Long): Single<User>

This method is exposed to the View Model using a service layer function which calls the above function and also inserts the returned user in the database.

fun updateUser(user: User, id: Long): Single<User> {
       return authApi.updateUser(user, id).map {
           userDao.insertUser(it)
           it
       }
   }

On using map on Single<User> returned by updateUser we can access the user inside the scope which is then inserted into the database using the DAO method insert user and the same user object is returned by the function.

This service layer method is then used in updateUser method of EditProfileViewModel class which specifies how it is subscribed and on which thread observer should be set etc. The Edit Profile Fragment fragment calls this method whenever the user clicks on the Update button.

fun updateUser(firstName: String, lastName: String) {
       val id = authHolder.getId()
       if (firstName.isEmpty() || lastName.isEmpty()) {
           message.value = “Please provide first name and last name!”
           return
       }
       compositeDisposable.add(authService.updateUser(User(id = id,          firstName = firstName, lastName = lastName), id)
               .subscribeOn(Schedulers.io())
               .observeOn(AndroidSchedulers.mainThread())
               .doOnSubscribe {
                   progress.value = true
               }
               .doFinally {
                   progress.value = false
               }
               .subscribe({
                   message.value = “User updated successfully!”
                   Timber.d(“User updated”)
               }) {
                   message.value = “Error updating user!”
                   Timber.e(it, “Error updating user!”)
               })
   }

UpdateUser takes two parameters first name and last name if any of these parameters is empty the function returns with an error message which is displayed on the UI else service layer update user function is called with argument a User object with first name and last name as provided to view model function and an id which is accessed using authHolder’s getId method. Whenever this is subscribed we set progress.value true which displays spinner on the UI this is set false after the operation is complete. If the patch request results in success then toast message is shown on screen and a success message is logged similar to this in case of error, an error toast is displayed and an error is logged.

This goes for the logic to update user we also need UI and menu item which launches this fragment.

Inside Menu.xml add the following snippet of code

<item
  android:id=“@+id/edit_profile”
  android:title=“@string/edit_profile” />

This will create a menu item inside the ProfileFragment. The next step is to wire this logic which tells what happens when the user selects this menu item. The following code wires it to EditProfileFragment.

R.id.edit_profile -> {
               val fragment = EditProfileFragment()              activity?.supportFragmentManager?.beginTransaction()?.replace(R.id.frameContainer, fragment)?.addToBackStack(null)?.commit()
               return true

Resources

Continue ReadingUpdating User information in Open Event Android

Implement Sensor Data Fetching Using AsyncTask

In PSLab android app we have implemented sensor data fetching of various sensors inbuilt in the mobile device like light sensor, accelerometer, gyrometer. We can use PSLab to log the data and show in the form of the graph or maybe export the data in the form of CSV format for future use.

But recording data from the phone sensor imposes a serious problem in the performance of the Android app as it is a costly to process in terms of memory, resources and time. In CS terms there is too much work that has to be done on the single main thread which sometimes leads to lag and compromises the UX.

So as a solution we applied a concept of the Multithreading provided by Java in which we can shift the heavy process to a separate background thread so that the main thread never gets interrupted during fetching the sensor data and the background thread handles all the fetching and updates the UI as soon as it gets the data, till then the Main thread continues to serves the user so to user the application remains always responsive.

For implementing this we used a special class provided by Android Framework called AsyncTask. Which provides below methods:-

  • doInBackground() : This method contains the code which needs to be executed in the background. In this method, we can send results multiple times to the UI thread by publishProgress() method.

  • onPreExecute() : This method contains the code which is executed before the background processing starts.

  • onPostExecute() : This method is called after doInBackground method completes processing. Result from doInBackground is passed to this method.

  • onProgressUpdate() : This method receives progress updates from doInBackground() method, which is published via publishProgress() method, and this method can use this progress update to update the UI thread.

  • onCancelled(): This method is called when the background task has been canceled. Here we can free up resources or write some cleanup code to avoid memory leaks.

We created a class SensorDataFetch and extended this AsyncTask class and override its methods according to our needs.

private class SensorDataFetch extends AsyncTask<Void, Void, Void> implements SensorEventListener {

   private float data;
   private long timeElapsed;

   @Override
   protected Void doInBackground(Void... params) {
      
       sensorManager.registerListener(this, sensor, updatePeriod);
       return null;
   }

   protected void onPostExecute(Void aVoid) {
       super.onPostExecute(aVoid);
       visualizeData();
   }

   @Override
   protected void onPreExecute() {
 super.onPreExecute();
   //do nothing
   }

   @Override
   protected void onProgressUpdate(Void... values) {
       super.onProgressUpdate(values);
          //do nothing
   }

   @Override
   protected void onCancelled() {
       super.onCancelled();
          //do nothing
   }

In doInBackground() method we implemented the fetching raw data from the sensor by registering the listener and in onPostExecute() method we updated that data on the UI to be viewed by the user.

When this process is being run in the background thread the Main UI thread is free and remains responsive to the user. We can see in Figure 1 below that the UI is responsive to the user swipe action even when the sensor data is updating continuously on the screen.

Figure 1 shows Lux Meter responding to user swipe while fetching sensor data flawlessly.

 

Resources

https://developer.android.com/reference/android/os/AsyncTask – Android Developer documentation for Async Task class.

Continue ReadingImplement Sensor Data Fetching Using AsyncTask