Contributing to Open Event Android App

The Open Event Android project consists of two components. The App Generator is a web application that is hosted on a server and generates an event Android app from a zip with JSON and binary files (examples here) or through an API. The second component we are developing in the project is a generic Android app – the output of the app generator. The Android app has a standard configuration file, that sets the details of the app (e.g. color scheme, logo of event, link to JSON app data).

The process for making a contribution in the project starts with making your account on GitHub. Secondly find the open source projects that interest you. Now as for me I started with open-event-android. Then follow these steps:

  1. Go through the project’s README.md file and get information about the various aspects and technologies of the project.
  2. Now fork that repo in your account.
  3. Open or setup the project as per the given information present in its documentation, for example for the sample android app you have to clone the project in your local machine and open it up using Android Studios.

Now you have your version of the project now it’s time for you to use the project on your own.

While doing so you have to work like a tester of the project, so you should explore each and every bit and find out any possible anomaly in the project that you would like to work on. Once you have that you are ready to create an issue.

Following are the steps to create a new issue,

Navigate to the main repo link, you will see an issues section as follows:

  • Click the new issue button and report every detail about the issue. For eg. The first issue that i worked on was Issue-1934
  • Even if you don’t find any problem in the project on your own you can always work on issues created by others, you just have to let the maintainers know that you want to work on the issue by commenting in it Issue 1709.
  • Now the next step is to work on that issue
  • On your machine you don’t have to change the code in the development branch as it’s considered to be as a bad practice. Hence checkout as a new branch. For eg. I checked out for the above issue as ‘crashfixed’
  • Make the necessary changes to that branch and test that the code is compiling and the issue is fixed followed by
  • The add command is used to bring the changes to the staging area so that they are ready to be committed/saved. You can also add individual files with the command
  • Next we want to save the changes that we made till now which can be done through git commit.
  • Finally we would push the changes that we made to our forked repository in github.
  • Now navigate to the repo and you will an option to create a Pull Request.
    Mention the Issue number and description and changes you done ,include screenshots of the fixed app.For eg.My first PR was  Pull Request 1936.

Sending the pull request is asking the maintainers of the code to add your changes to the main project which would be visible to all the contributors. But before getting merged your code may have to pass through several tests as in my case were:

-codacy/pr

-continuous-integration/travis-ci/pr

After your code passes the above tests you you would require one approved review from one of the maintainers of the project to get your code merged into the main one.

If your code is perfect in the very first attempt it would be accepted by the maintainer otherwise you would be asked to do some changes in it. You could carry out the changes on your local machine and once you are done with them you could push them to your forked repository and the changes would be amended in your pull request on its own.

Resources

Continue ReadingContributing to Open Event Android App

Comparison between SUSI AI with Mycroft AI and Amazon Alexa

Now is the era of Voice User Interface (VUI) devices and they play a very important role as personal assistants. Here we compare the SUSI AI, Mycroft AI and Amazon Alexa based on the number of skills, their availability, easiness to add and edit skills and the provision of the user to modify the skill and add more to it if needed, etc.

Issue: https://github.com/fossasia/labs.fossasia.org/issues/215

The Comparison:

  1. Starting with the number of skills, here Amazon Alexa supports way more number of skills as compared to both Mycroft AI and SUSI AI.
  2. Availability: Mycroft AI and SUSI AI are available everywhere and can set up anywhere regardless of the country whereas Alexa is available in U.S., U.K., Germany,  India but they are aggressively expanding.
  3. Adding and editing skills: Mycroft and SUSI are open source and their skills can be added and edited and viewed by the open source community. Issues can be made to enhance the functionality of the skills whereas Alexa skills are not open source and certification and publishing of the skill is done by the Amazon team. Mycroft and SUSI skills can be customized by the user but this fails with Alexa as users have to create that same skill from scratch if they have to customize them.
  4. Platforms supported: Mycroft, SUSI and Alexa all support Linux. Mycroft lacks support for Windows and Mac but supports Raspberry Pi and Android, Alexa provides support for Windows and Mac and Raspberry Pi. SUSI also provides support for Android and iOS and can be integrated with speakers, vehicles, Pi, etc.
  5. Dedicated devices: As of now SUSI AI lacks such device. Mycroft has Mark 1 and Alexa has Echo. These devices are portable and are good candidates for home automation.
  6. Languages used for skill development: Mycroft mostly uses python. Alexa uses python, NodeJS, C#, etc for development of applications. SUSI uses its own language but language like javascript can be included in it. It’s easier to specify patterns using wildcards and variables in SUSI.

Due to different languages used, Mycroft AI skills can’t be directly used in SUSI AI. We need to convert Mycroft skills to SUSI skills if Mycroft skills are to be used for SUSI.

Some suggestions for making a dedicated device for SUSI:

  1. We can use a Raspberry Pi, USB headphones and a microphone to make a basic platform.
  2. We can install Jasper to enable the voice input on the Pi. Jasper is a open source application that enables us to make voice controlled applications.
  3. We can use SUSI server to interact with the device and the home appliances like lights. SUSI server can process the states of the the appliance (lights in this case) and return it as JSON objects to Raspberry Pi and then it may change the state as per user input.

Make a simple Hello World skill with SUSI:

  1. Visit https://github.com/fossasia/susi_skill_cms/blob/master/docs/Skill_Tutorial.md for a basic introduction to SUSI skills syntax and how does it work.
  2. Go to http://dream.susi.ai .
  3. Enter the skill name, say “hello”.
  4. You will be greeted by a welcome message – “roses are red…..”. Delete it and replace it with the following snippet.
::name <Skill_name> #<— Enter skill name. for example hello

::author <author_name>

::author_url <author_url> #<— You can leave this empty as of now.

::description <description> #<— skill description

::dynamic_content No

::developer_privacy_policy <link> #<— you can leave this as of now.

::image <image_url> #<— You can leave this as of now.

::term_of_use <link>

#Intent. Comments are written with a #

hi|hello|what’s up #<— This is what the user says

Hi|I am good|Hello #<— This is what the skill answers

6. Now go to http://susi.ai/chat for the testing.

7. In the SUSI chat dialog box (present at the bottom of the page) enter dream <test application name> where “test application name” is the name you enter when you first visit http://dream.susi.ai. In this case “dream hello”.

8. You can input “what’s up” in the dialog box and it will give you the desired output which you mentioned in the application.

Conclusion:

SUSI has its own good points but it lacks in some department like the number and type of skills. Like Mycroft we can start making various skills and try to make a basic prototype of a dedicated SUSI personal assistant device.

Resources

  1. Jasper
  2. Skill addition to SUSI
  3. Mycroft hello world skill

 

Continue ReadingComparison between SUSI AI with Mycroft AI and Amazon Alexa

Participate in the #OpenTechNights Program today and Win a Free Stay during the FOSSASIA Summit 2018 from the Open Source Initiative and UNESCO

The FOSSASIA Summit 2018 takes place in Singapore from Thursday, March 22 – Sunday, March 25. Open Source contributors can now apply for a free ticket to the event, and accommodation throughout the conference. In addition, you’ll be eligible to participate in: Featured cloud workshops, the UNESCO hackathon, and celebrate the 20th Anniversary of the Open Source Initiative. All you have to do is convince us, that you are an awesome Open Source contributor and book your trip to Singapore!

About #OpenTechNights

Developers from all over the world are joining the FOSSASIA Summit. We want to connect established and new Open Tech contributors alike. With the support of UNESCO, the Open Source Initiative, and other partners, we are inviting Free and Open Source Software contributors to join us. Winners will receive free lodging at a shared accommodation in the centre of Singapore, and a free ticket to the conference.

Winners are expected to join the summit each day, to participate in the workshops, and the Hackathon on Saturday/Sunday, March 24/25. We would also hope you can support the Open Source Initiative at their booth.

How do I sign up?

Step 1: Please fill in our form here before February 28, 2018.

Step 2: We will notify all winners within three days of their submission, however judging will begin immediately, and continue until all open spots are filled, so the earlier you apply, the higher your chances to win. Please note, winners will receive free accommodations in Singapore. Flight and other travel costs are not included and are the responsibility of the attendee.

Step 3: Selected applicants must confirm their itinerary and tickets before March 1st to insure their free stay in Singapore. Earliest check-in possible is Wednesday March 21, latest check-out is Monday, March 26. Please indicate your arrival and departure times in the application form.

Expectations of Participants – Share what you learn

  1. Attendees support volunteers, speakers and participants at the event, and take a shift at the Open Source Initiative’s booth. Let’s bring the spirit of sharing Open Technologies and learning together!
  2. Please confirm your participation at the opening event at 12PM, Thursday, March 22, 2018 and participate in the specially featured cloud workshops on Friday, March 23, 2018 from 9.00 AM – 5.00PM.
  3. Attendees participate in the UNESCO Hackathon on Saturday, March 24 (2.00 PM – 10.00PM) and on Sunday, March 25 (9.00 AM – 5.00PM).
  4. Attendees help reach out to community members who cannot join us at the event, make tweets, share what you learn on social media, publish photos and put up blog post about the summit.

Apply Now

Apply for a free stay with #FOSSASIA #OpenTechNights supported by the Open Source Initiative and the UNESCO and participate in the FOSSASIA Summit 2018 now here!

More Information

More updates, tickets and information on speakers on our website: https://2018.fossasia.org

Links

Open Source Initiative: https://opensource.org

UNESCO: http://unesco.org

Continue ReadingParticipate in the #OpenTechNights Program today and Win a Free Stay during the FOSSASIA Summit 2018 from the Open Source Initiative and UNESCO

Announcing the FOSSASIA Codeheat Winners 2017/18

Today we are very proud to announce our Grand Prize Winners and Finalist Winners of Codeheat 2017/2018.

Codeheat was epic in every regard. Participants not only solved a massive amount of issues in FOSSASIA’s projects, reviewed pull requests, shared scrums, and wrote blog posts, but most importantly they encouraged and helped one another to learn and progress along the way. It was a very, very busy 5 months for everyone – we had 647 developers from 13 countries participating in the contest supported by 43 mentors. Thank you all for this amazing achievement!

With so much excellent work getting done, it was a super hard to choose the Grand Prize and Finalist Winners of the contest. Our winners stand out in particular as they contributed to FOSSASIA projects on a continuously high level following our Free and Open Source Best Practices. They worked in different areas – code, reviews, blog posts and supported other community members.

Each of the Grand Prize Winners is awarded a travel grant to join us at the FOSSASIA Summit in Singapore from March 22-25, 2018 where they receive the official Codeheat award, and meet with mentors and FOSSASIA developers. Other Finalist Winners will receive travel support vouchers to go to a Free and Open Source Software event of their choice. Active participants will also receive a certificate over the upcoming weeks. FOSSASIA mentors will meet many contributors and hand out prizes and Tshirts at our regular meetups and events across Asia.

Congratulations to our Grand Prize Winners, Finalist Winners, and all of the participants who spent the last few of months learning, sharing and contributing to Free and Open Source Projects. Well-done! We are deeply impressed by your work, your progress and advancement. The winners are (in alphabetical order):

Grand Prize Winners

Manish Devgan

Parth Shandilya

Raghav Jajodia

Finalist Winners

Anshuman Verma

Ayush Gupta

Bhavesh Anand

Mohit Sharma

Nikit Bhandari

Ritika Motwani

Vaibhav Singh

About Codeheat

Codeheat is a contest that the FOSSASIA organization is honored to run every year. We saw immense growth this year in participants and the depth of contributions.

Thank you Mentors and Supporters

Our 40+ mentors and many project developers, the heart and soul of Codeheat, are the reason the contest thrives. Mentors volunteer their time to help participants become open source contributors. Mentors spend hundreds of hours during answering questions, reviewing submitted code, and welcoming the new developers to project. Codeheat would not be possible without their patience and tireless efforts. Learn more about this year’s mentors on the Codeheat website.

Certificate of Participation

Participating developers, mentors and the FOSSASIA admin team learnt so much and it was an amazing and enriching experience and we believe the learnings are the main take-away of the program. We hope to see everyone continuing their contributions, sharing what they have learnt with others and to seize the opportunity to develop their code profile with FOSSASIA. We want to work together with the Open Tech community to improve people’s lives and create a better world for all. As a participating developer or mentor, you will receive your certificate over the upcoming weeks. Thank you!

More Links

Continue ReadingAnnouncing the FOSSASIA Codeheat Winners 2017/18

Installing Susper Search Engine and Deploying it to Heroku

Susper is a decentralized Search Engine that uses the peer to peer system yacy and Apache Solr to crawl and index search results.

Search results are displayed using the Solr server which is embedded into YaCy. All search results must be provided by a YaCy search server which includes a Solr server with a specialized JSON result writer. When a search request is made in one of the search templates, a HTTP request is made to YaCy. The response is JSON because that can much better be parsed than XML in JavaScript.

In this blog, we will talk about how to install Susper search engine locally and deploying it to Heroku (A cloud application platform).

How to clone the repository

Sign up / Login to GitHub and head over to the Susper repository. Then follow these steps.

  1. Go ahead and fork the repository
https://github.com/fossasia/susper.com

2.   Get the clone of the forked version on your local machine using

git clone https://github.com/<username>/susper.com.git

3. Add upstream to synchronize repository using

git remote add upstream https://github.com/fossasia/susper.com.git

Getting Started

The Susper search application basically consists of the following :

  1. First, we will need to install angular-cli by using the following command:
npm install -g @angular/cli@latest

2. After installing angular-cli we need to install our required node modules, so we will do that by using the following command:

npm install

3. Deploy locally by running this

ng serve

Go to localhost:4200 where the application will be running locally.

How to Deploy Susper Search Engine to Heroku :

  1. We need to install Heroku on our machine. Type the following in your Linux terminal:
wget -O- https://toolbelt.heroku.com/install-ubuntu.sh | sh

This installs the Heroku Toolbelt on your machine to access Heroku from the command line.

  1. Create a Procfile inside root directory and write
web: ng serve
  1. Next, we need to login to our Heroku server (assuming that you have already created an account).

Type the following in the terminal:

heroku login

Enter your credentials and login.

  1. Once logged in we need to create a space on the Heroku server for our application. This is done with the following command
heroku create
  1. Add nodejs buildpack to the app
heroku buildpacks:add –index 1 heroku/nodejs
  1. Then we deploy the code to Heroku.
git push heroku master
git push heroku yourbranch:master # If you are in a different branch other than master

Resources

Continue ReadingInstalling Susper Search Engine and Deploying it to Heroku

Installing the Loklak Search and Deploying it to Surge

The Loklak search creates a website using the Loklak server as a data source. The goal is to get a search site, that offers timeline search as well as custom media search, account and geolocation search.

In order to run the service, you can use the API of http://api.loklak.org or install your own Loklak server data storage engine. Loklak_server is a server application which collects messages from various social media tweet sources, including Twitter. The server contains a search index and a peer-to-peer index sharing interface. All messages are stored in an elasticsearch index.

The site of this repo is deployed on the GitHub gh-pages branch and automatically deployed here: http://loklak.org

In this blog, we will talk about how to install Loklak_Search locally and deploying it to Surge (Static web publishing for Front-End Developers).

How to clone the repository

Sign up / Login to GitHub and head over to the Loklak_Search repository. Then follow these steps.

  1. Go ahead and fork the repository
https://github.com/fossasia/loklak_search
  1.   Get the clone of the forked version on your local machine using
git clone https://github.com/<username>/loklak_search.git
  1.   Add upstream to synchronize repository using
git remote add upstream https://github.com/fossasia/loklak_search.git

Getting Started

The Loklak search application basically consists of the following :

  1. First, we will need to install angular-cli by using the following command:
npm install -g @angular/cli@latest

2. After installing angular-cli we need to install our required node modules, so we will do that by using the following command:

npm install

3. Deploy locally by running this

ng serve

Go to localhost:4200 where the application will be running locally.

How to Deploy Loklak Search on Surge :

Surge is the technology which publishes or generates the static web-page demo link, which makes it easier for the developer to deploy their web-app. There are a lot of benefits of using surge over generating demo link using GitHub pages.

  1. We need to install surge on our machine. Type the following in your Linux terminal:
npm install –global surge

This installs the Surge on your machine to access Surge from the command line.

  1. In your project directory just run
surge
  1. After this, it will ask you three parameters, namely
Email
Password
Domain

After specifying all these three parameters, the deployment link with the respective domain is generated.

Auto deployment of Pull Requests using Surge :

To implement the feature of auto-deployment of pull request using surge, one can follow up these steps:

  • Create a pr_deploy.sh file
  • The pr_deploy.sh file will be executed only after success of Travis CI i.e. when Travis CI passes by using command bash pr_deploy.sh
#!/usr/bin/env bash
if [ “$TRAVIS_PULL_REQUEST” == “false” ]; then
echo “Not a PR. Skipping surge deployment.”
exit 0
fi
npm i -g surge
export SURGE_LOGIN=test@example.co.in
# Token of a dummy account
export SURGE_TOKEN=d1c28a7a75967cc2b4c852cca0d12206
export DEPLOY_DOMAIN=https://pr-${TRAVIS_PULL_REQUEST}-fossasia-LoklakSearch.surge.sh
surge –project ./dist –domain $DEPLOY_DOMAIN;

Here, Travis CI is first installing surge locally by npm i -g surge  and then we are exporting the environment variables SURGE_LOGIN , SURGE_TOKEN and DEPLOY_DOMAIN.

Now, execute pr_deploy.sh file from .travis.yml by using command bash pr_deploy.sh

Resources

Continue ReadingInstalling the Loklak Search and Deploying it to Surge

How Errors from Server Side are Handled On Open Event Frontend

This blog article will illustrate how the various error or status codes are handled  in  Open Event Frontend, and how the appropriate response is generated corresponding to those error codes. Open Event Frontend, relies on Open Event Server for all server operations. Open Event Server exposes  a well documented JSON:API Spec Compliant REST API. The clients using the api primarily interact with it using GET, POST , PATCH and DELETE requests. And thus for each request the API returns corresponding data as response along with it’s status code.

For instance whenever the app opens, for the landing page, all the events are fetched by making a GET request to the end point v1/events. If the request is successful and events data is returned, the status code is 200 which stands for OK in the http standard set by IANA.

Fig 1: Screenshot of google chrome developer consoles’ networking tab while making a request.

Since Open Event server is compliant with JSON:API Spec, to quote it’s official documentation, “Error objects MUST be returned as an array keyed by errors in the top level of a JSON API document.” Thus whenever there is an error, or the request is unsuccessful due to a variety of reasons, the server has a predefined format to convey the information to the front end.

The process is illustrated by the reset password form on open event frontend. When a user forgets his password, he/she has the option to reset it, using his email address. Thus the form just takes in the email address of the user and makes a POST request to the reset-password API endpoint of the server.

  • Once the request is made there are 3 possibilities (check references for error code significance):
    The request is successful and a status code of 200 is returned.
  • The email address user entered doesn’t exists and no record is found in the database. 422 status code should be returned.
  • The server is down, or the request is invalid (something unexpected has occurred). In all such scenarios error code 404 should be returned.

this.get('loader')
         .post('auth/reset-password', payload)
         .then(() => {
           this.set('successMessage', this.l10n.t('Please go to the link sent to your     

           email to reset your password'));
         })
         .catch(reason => {
           if (reason && reason.hasOwnProperty('errors') && reason.errors[0].status

               === 422) {
             this.set('errorMessage', this.l10n.t('No account is registered with this

                      email address.'));
           } else {
             this.set('errorMessage', this.l10n.t('An unexpected error occurred.'));
           }
         })
         .finally(()=> {
           this.set('isLoading', false);
         }
         );
Figure 2 : The reset password UI

Thus as mentioned in the JSON:API docs, the errors property is expected to contain the status code and error message(optional) , which ember handles via the the catch block. The catch block is executed whenever the response from the request is not successful. The contents of the response are present in the reason property. If the status of the error is 422, the corresponding message is stored inside the errorMessage property of the component which is further used to display the alert by rendering an error block on the forgot password form.

In case there is no error, the errorMessage is undefined, and the error block is not rendered at all. In case of any other unexpected error, the standard text is displayed by initialising the errorMessage property to it.

Resources

Continue ReadingHow Errors from Server Side are Handled On Open Event Frontend

Camera Controls Using Volume Buttons In The Phimpme Application

The Phimpme Android application has a camera, Gallery section, edit image section and also the inbuilt sharing option. In spite of having all of the above features, the Phimpme application doesn’t compromise on the quality and functions of each of the sections. For instance, we can control the camera fully with the help of just the volume buttons. For this, we have provided an option in the settings of the application to change and select the behaviour of the volume buttons according to the users choice. In this post, I will be discussing how we have achieved this functionality.

Step 1

First, we have to display an ArrayList of options using the ListPreference in the settings. The user can perform the following functions using the volume keys.

  1. Take Photo
  2. Focus
  3. Zoom in/out
  4. Change Exposure Level
  5. Switch Auto Level on/off

There are also two other option to change device volume and to do nothing in case the user wants the default behaviour.

The above options in the settings can be provided using the following lines of code.

<ListPreference
   android:defaultValue="volume_take_photo"
   android:entries="@array/preference_volume_keys_entries"
   android:entryValues="@array/preference_volume_keys_values"
   android:key="preference_volume_keys"
   android:summary="@string/preference_volume_keys_summary"
   android:title="@string/preference_volume_keys" />

Step 2

Now as the user selects a particular option from the ListPreference, the value in the SharedPreference associated with a particular key value gets updated. After this, we have to perform the particular activity as soon as the volume button is pressed. For this, we have to Override the onKeyDown() function of the KeyEvent.Callback class in Android. This function takes in the Integer keycode and the KeyEvent as the parameters.

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
   if (MyDebug.LOG)
       Log.d(TAG, "onKeyDown: " + keyCode);
   boolean handled = mainUI.onKeyDown(keyCode, event);
   if (handled)
       return true;
   return super.onKeyDown(keyCode, event);
}

Step 3

We have defined another onKeyDown() method in the MainUI class to keep the code modularized. In this, we have made use of the Switch cases to perform the different actions. This can be done by using the following line of code snippet.

Switch (volume_keys) {
  case "volume_take_photo":
     main_activity.takePicture();
     return true;

  case "volume_zoom":
     if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
        main_activity.getPreview().zoomTo(main_activity.getPreview().getCameraController().getZoom() + 1);
     }
     else {
        main_activity.getPreview().zoomTo(main_activity.getPreview().getCameraController().getZoom() - 1);
     }
     return true;

In the above code snippet, we have defined the function to perform the zoom operation and to click picture using the volume keys. Similarly, we can add the functions to perform all the above mentioned activities. To get the full source code, please refer to the Phimpme Android GitHub repository mentioned in the resources section below.

Resources

  1. Android Developer Guide – KeyEvent.Callback class – https://developer.android.com/reference/android/view/KeyEvent.Callback.html
  2. GitHub – Phimpme Android Repository – https://github.com/fossasia/phimpme-android/
  3. StackOverflow – Handling key events in Android – https://stackoverflow.com/questions/5631977/keyevent-handling-in-android
  4. Blog post – Handleling Key Events – https://android-developers.googleblog.com/2009/12/back-and-other-hard-keys-three-stories.html

 

Continue ReadingCamera Controls Using Volume Buttons In The Phimpme Application

Slideshow option in the Phimpme Android Application

The Phimpme Android application along with all the basic features for viewing and sharing images also has some interesting functions, for example, the ability to view all the images at once using the slideshow option. The users can also manage the time duration for which a particular photo will be displayed before switching on to the next image. In this post, we will be discussing how we have achieved this functionality in the Phimpme Android application.

Step 1

First, we have to provide the user with an option to enter the time duration for which they want to view a particular photo. For this, we have made use of the themed dialog box which will take the input from the user and then we will be converting the time entered by them into milliseconds. This can be done by using the following code snippet.

dialog.setButton(DialogInterface.BUTTON_POSITIVE, getString(R.string.ok).toUpperCase(), new DialogInterface.OnClickListener() {
   @Override
   public void onClick(DialogInterface dialog, int which) {
       String value= editTextTimeInterval.getText().toString();
       if(!"".equals(value))
       {
           slideshow=true;
           int intValue = Integer.parseInt(value);
           SLIDE_SHOW_INTERVAL = intValue * 1000;

Step 2

For changing the photo at a particular duration of time, we need to make use of the Runnable interface in Java, which uses a method run() to execute the tasks. To use it, we have to create a Handler object and initialize it. This can be done using the following lines of the code.

private Handler handler;
handler = new Handler();

After this, we have to define and initialize our Runnable object which will be used later to change the picture. The code snippet for initializing the runnable object is given below.

Runnable slideShowRunnable = new Runnable() {
   @Override
   public void run() {
       try{
           mViewPager.scrollToPosition((getAlbum().getCurrentMediaIndex() + 1) % getAlbum().getMedia().size());
       }
       catch (Exception e) {
           e.printStackTrace();
       }
       finally{
           handler.postDelayed(this, SLIDE_SHOW_INTERVAL);
       }

As the run() method gets executed, the scrollToPosition function of the ViewPager class gets called which changes the position of the image displayed to the next image available.

Step 3

To call the runnable object we created in the second step, we have to use the postDelayed function of the Handler class which takes in a Runnable object and the time in milliseconds as the parameter. The code snippet for this is provided below.

handler.postDelayed(this, SLIDE_SHOW_INTERVAL);

Please note that we have also included the above line of code in the finally block after each successful run of the method because as the slideshow starts, we will have to call this function to scroll to the new position after every finite provided duration.

This is how we have achieved the Slideshow functionality in the Phimpme Android application. To get the full source code for this implementation, please check out the Phimpme Android GitHub repository listed in the resources section below.

Resources

  1. GitHub – Phimpme Android Repository – https://github.com/fossasia/phimpme-android/
  2. Android Developer Guide – Handler class – https://developer.android.com/reference/android/os/Handler.html
  3. StackOverflow – Runnable in Java – https://stackoverflow.com/questions/13327571/in-a-simple-to-understand-explanation-what-is-runnable-in-java
  4. StackOverflow – Image Slideshow in Android – https://stackoverflow.com/questions/2995145/image-slideshow-example-in-android

 

Continue ReadingSlideshow option in the Phimpme Android Application

Compressing Albums in the Phimpme Android Application

The Phimpme Android application comes in with all the functionalities ranging from viewing images to taking photos, editing pictures  and sharing them with the world from within a single application without having to switch to or install other social media apps on your mobile phone. Apart from these basic functionalities, the Phimpme Android app also comes with additional features to enhance user experience like the ability to compress the whole album with a large number of photos so that it becomes easier to share them. In this post, I will be explaining how we achieved this functionality to compress the Albums.

Step 1

The first thing we need to do before compressing an album is to get all the paths of the images in that album and store it in an ArrayList<String> so that it can be used later for the compression process. This can be done using the code snippet provided below, it stores all the paths of the file in a particular folder whose name ends with .jpg

path = new ArrayList<>();
File folder = new File(getAlbums().getSelectedAlbum(0).getPath() + "/");
File[] fpath = folder.listFiles();
for(int i = 0; i < fpath.length; i++){
   if(fpath[i].getPath().endsWith(".jpg") ){
       path.add(fpath[i].getPath());
   }
}

Step 2

Since the compression is a heavy task, we can make use of an AsyncTask to run the task on the background thread so that the user experience is not at all hampered. In the onPreExecute method of the AsyncTask, we need to display the Notification that the compression of the particular album has started, for this we have made use of the Notification handler class that we have created in the Phimpme Android application to ease the process of displaying the notification and to avoid repetition of codes. The onPreExecute method of the AsyncTask is given below.

@Override
protected void onPreExecute() {
   super.onPreExecute();
   NotificationHandler.make(R.string.folder, R.string.zip_fol, R.drawable.ic_archive_black_24dp );
}

Step 3

On the doInBackground method of the AsyncTask, we run the process to compress the files one by one. For this we will make use of the ZipEntry class which is used to represent a zip file entry in Android/Java. First we will create a File with the .zip extension.  After this, we will make use of an object of the class ZipOutputStream as depicted in the code snippet provided below.

BufferedInputStream origin = null; 
FileOutputStream dest = new FileOutputStream(_zipFile); 
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest)); 
byte data[] = new byte[BUFFER];

After initializing the ZipOutPutStream object, we will put the zip entries in it by using the putNextEntry function of the class. To create a Zip entry of a file, we need to make use of for loop to generate the object of type ZipEntry and after that by using the putNextEntry function of the class, we will put the entries one by one as depicted in the code snippet given below.

for (int i = 0; i < path.size(); i++) {
FileInputStream fi = new FileInputStream(path.get(i));
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(path.get(i).substring(path.get(i).lastIndexOf("/") + 1));
out.putNextEntry(entry);

While preparing the Zip file, we will update the progress of the compression operation by making use of the Notification handler class.

This is how we have implemented the feature to compress the Albums in the Phimpme Android Application. To get the full source code for the same, please check the Phimpme Android GitHub repository listed on the resources below.

Resources

  1. StackOverflow – Compressing Files in Android – https://stackoverflow.com/questions/25562262/how-to-compress-files-into-zip-folder-in-android
  2. Blog – Compressing Files in Android programmatically – http://stacktips.com/tutorials/android/how-to-programmatically-zip-and-unzip-file-in-android
  3. GitHub – Phimpme Android Repository – https://github.com/fossasia/phimpme-android/
Continue ReadingCompressing Albums in the Phimpme Android Application