Implementation of Set Different Language for Query in SUSI Android

SUSI.AI has many skills. Some of which are displaying web search of a certain query, provide a list of relevant information of a topic, displaying a map of the certain position and simple text message of any query. Previously SUSI.AI reply all query in English language but now one important feature is added in SUSI.AI and that feature is, reply query of the user in the language that user wants. But to get the reply in different language user has to send language code of that language along with query to SUSI Server. In this blog post, I will show you how it is implemented in SUSI Android app.

Different language supported in SUSI Android

Currently, different languages added in option in SUSI Android and their language code are:

Language Language Code
English en
German de
Spanish es
French fr
Italian it
Default Default language of the device.

Layout design

I added an option for choosing the different language in settings. When the user clicks on Language option a dialog box pops up. I used listpreference to show the list of different languages.

<ListPreference

  android:title=“@string/Language”

  android:key=“Lang_Select”

  android:entries=“@array/languagentries”

  android:entryValues=“@array/languagentry”>

</ListPreference>

“title” is used to show the title of setting, “entries” is used to show the list of entry to the user and “entryValue” is the value corresponding to each entry. I used listpreference because it has own UI so we don‘t have to develop our own UI for it and also it stores the string into the SharedPreferences so we don’t need to manage the values in SharedPreference. SharedPreference needed to set value in Language in settings so that once user close app and again open it setting will show same value otherwise it will show default value. We used an array of string to show the list of languages.

<string-array name=“languagentries”>

  <item>Default</item>

  <item>English</item>

  <item>German</item>

  <item>Spanish</item>

  <item>French</item>

  <item>Italian</item>

</string-array>

SetLanguage implementation

To set language user must choose Language option in setting.

On clicking Language option a dialog box pop up with the list of different languages. When the user chooses a language then we save corresponding language code in preference with key “prefLanguage” so that we can use it later to send it to the server along with the query. It also uses to send language to the server to store user language on the server, so that user can use the same language in the different client.

querylanguage.setOnPreferenceChangeListener { _, newValue ->

  PrefManager.putString(Constant.LANGUAGE, newValue.toString())

  if(!settingsPresenter.getAnonymity()) {

      settingsPresenter.sendSetting(Constant.LANGUAGE, newValue.toString(), 1)

  }

}

newValue.toString() is the value i.e language code of corresponding language.

Now when we query anything from SUSI.AI we send language code along with query to the server. Default language is default language of the device. Before sending language to the server we check language is default language or any specific language.

val language = if (PrefManager.getString(Constant.LANGUAGE, Constant.DEFAULT).equals(Constant.DEFAULT))

Locale.getDefault().language

else PrefManager.getString(Constant.LANGUAGE, Constant.DEFAULT)

And after that, we send the corresponding language along with query to the server.

clientBuilder.susiApi.getSusiResponse(timezoneOffset, longitude, latitude, source, language, query)

Reference

Continue ReadingImplementation of Set Different Language for Query in SUSI Android

Using Vector Images in SUSI Android

Android designed to run across many devices with different screen sizes and display resolutions. One of the things that confuse many new Android developers is how to support multiple screen sizes. For making  SUSI Android app more user-friendly and interactive we used a lot of images in the form of drawable resources. Most of these drawables are in the form of PNG (Portable Network Graphic) and to support multiple screen size we have to include separate images of varied dimensions because we can’t scale PNG images without losing quality.

Other disadvantages of using PNG images are

  • PNG images take large disk space.
  • PNG images have fixed colour and dimensions which cannot be changed.

To overcome these shortcomings of PNG image we decided to use vector images in SUSI Android.

Advantages of using vector image are

  • It is smaller in size as compared to PNG i.e it takes less disk space than PNG.
  • It can be scaled without losing quality. So we need to include only a single image for all screen size.

Disadvantages of using vector image are

  • Reconstruction of vector data may take considerably longer than that contained in a bitmap file of equivalent complexity because each image element must be drawn individually and in sequence.
  • Vector image can’t be used to display complex photographs.
  • If the object consists of a large number of small elements then file size grow very fast.

Vector produce smaller size file than bitmap only for simple stuff. When it comes to creating a photographic quality vector where colour information is paramount and may vary on a pixel-by-pixel basis, the file can be much larger than its bitmap version, that’s why vector image is only suitable for small images like logo designs, icons etc.

In this blog post, I will show you how we used vector images in SUSI Android.

How to create vector image using Asset Studio tool

Asset Studio is inbuilt Android Studio tool which we use to create a vector image from default material icon or local SVG images. To use vector asset in Android Studio

  • Go to File> New > Vector Asset
  • Vector Asset Studio Tool Window is prompted

  • Create vector image from default material icon or local SVG image.

Asset Studio will add icon in drawable. It can be used anywhere in the project.

Vector images in SUSI Android

In SUSI Android all drawable images like search, mic, arrow, check etc are vector images,  even the logo of the app is a vector image.

This vector image is the result of code you can find here.

Now I will describe some special attributes used here

  • fillColor: It defines the colour of the image. So the colour of your image depends on the colour you provide in fillColor. We used white color(#ffffff) as fillColor that’s why the image is white in colour.
  • strokeColour: It defines the colour of boundary of the image.
  • pathData: Shape of your image depends on pathData. Different commands used in pathData are
  1. M: It is used to define the starting point. For example, M10,10 means starting     Coordinate of the image will be (10,10). M used for absolute position and m   for relative position.
  2. L: L means to draw a line from the current position to given position. For example, M10,10 L20,20 means a straight line will be drawn from coordinate (10,10) to coordinate (20,20. L Use for absolute position and l for relative position.
  3. C: C means to draw an arc. For example, Cx1,x2 x3,x4 x5,x6 means draw a curve  (cubic Bezier curve) from coordinate  (x1,x2) using (x3,x4) as control point at the beginning and (x5,x6) as control point at the end.
  4. Z: Z means to close the path using the straight line between the current position and starting position.

    Example

Let’s consider a curve

M9,16.17L4.83,12l-1.42,1.41L9,19 21,7l-1.41,-1.41z

It starts from point (9,16.17). From (9,16.17) to (4.83,12) a straight line will be drawn. Now again a straight will be drawn from point (4.83,12) to the relative point (-1.42,1.41). After that from point (-1.42, 1.41) it will draw a polyline like an upward arrow(^) with the end point at (21,7). Again it will draw a straight line between point (21,7) and relative point (-1.41, -1.41). At the last z will close curve using the straight line between current point and starting point).

Resources

Tags

 

Continue ReadingUsing Vector Images in SUSI Android

Shift from Java to Kotlin in SUSI Android

Previously SUSI Android was written in JAVA. But recently Google announced that it will officially support Kotlin on Android as a first class language so we decided to shift from Java to Kotlin. Kotlin runs on Java Virtual Machine and hence we can use Kotlin for Android app development. Kotlin is new programming language developed by JetBrains, which also developed IntelliJ-the IDE that Android Studio is based on. So Android Studio has excellent support for Kotlin.

Advantages of Kotlin over Java

  • Kotlin is a null safe language. It changes all the instances used in the code to non nullable type thus it ensures that the developers don’t get any nullPointerException.
  • Good Android Studio support. Kotlin tool is included with Android Studio 3.0 by default. But for Android Studio 2.x we need to install the required plugin for Kotlin.
  • Kotlin also provides support for Lambda function and other high order functions.
  • One of Kotlin’s greatest strengths as a potential alternative to Java is interoperability between Java and Kotlin. You can even have Java and Kotlin code existing side by side in the same project.
  • Kotlin provides the way to declare Extension function similar to that of C# and Gosu. We can use this function in the same way as we use the member functions of our class.

After seeing the above points it is now clear that Kotlin is much more effective than Java. In this blog post, I will show you how ForgotPasswordActivity is shifted from JAVA to Kotlin in SUSI Android.

How to install Kotlin plugin in Android Studio 2.x

We are using Android Studio 2.3.0 in our android project. To use Kotlin in Android Studio 2.x we need to install Kotlin plugin.

Steps to include Kotlin plugin in Android Studio 2.x are:

  • Go to File
  • After that select Settings
  • Then select Plugin Option from the left sidebar.
  • After that click on Browse repositories.
  • Search for Kotlin and install it.

Once it is installed successfully, restart Android Studio. Now configure Kotlin in Android Studio.

Shift  SUSI Android from JAVA to Kotlin

Kotlin is compatible with JAVA. Thus it allows us to change the code bit by bit instead of all at once. In SUSI Android app we implemented MVP architecture with Kotlin. We converted the code by one activity each time from JAVA to Kotlin. I converted the ForgotPassword of SUSI Android from JAVA to Kotlin with MVP architecture. I will discuss only shifting of SUSI Android from JAVA to Kotlin and not about MVP architecture implementation.

First thing is how to extend parent class. In JAVA we need to use extend keyword

public class ForgotPasswordActivity extends AppCompatActivity

but in Kotlin parent class is extended like

class ForgotPasswordActivity : AppCompatActivity ()

Second is no need to bind view in Kotlin. In JAVA we bind view using Butter Knife.

@BindView(R.id.forgot_email)

protected TextInputLayout email;

and

email.setError(getString(R.string.email_invalid_title));

but in Kotlin we can directly use view using id.

forgot_email.error = getString(R.string.email_invalid_title)

Another important thing is that instead of using setError and getError we can use only error for both purposes.

forgot_email.error

It can be used to get error in TextInputLayout ‘forgot_email’ and

forgot_email.error = getString(R.string.email_invalid_title)

can be use to set error in TextInputLayout ‘forgot_email’.

Third one is in Kotlin we don’t need to define variable type always

val notSuccessAlertboxHelper = AlertboxHelper(this@ForgotPasswordActivity, title, message, null, null, button, null, color)

but in JAVA we need to define it always.

AlertboxHelper notSuccessAlertboxHelper = new AlertboxHelper(ForgotPasswordActivity.this, title, message, null, null, positiveButtonText, null, colour);

And one of the most important feature of Kotlin null safety. So you don’t need to worry about NullPointerException. In java we need to check for null otherwise our app crash

if (url.getEditText() == null)

      throw new IllegalArgumentException(“No Edittext hosted!”);

But in Kotlin there is no need to check for null. You need to use ’?’ and Kotlin will handle it itself.  

input_url.editText?.text.toString()

You can find the previous ForgotPasswordActivity here. You can compare it with new ForgotPaswordActivity.

Reference

Continue ReadingShift from Java to Kotlin in SUSI Android

Burst Camera Mode in Phimpme Android

Camera is an integral part of core feature in Phimpme Android. Various features were added in the camera part such as resolution, timer, shutter sound, white balance etc. Click burst shot from camera is also an important feature to be added. Burst shot is clicking multiple pictures in one go.

Adding a Burst mode in Phimpme Camera

  • Adding burst mode enable entry in options

The popup view in Camera is added programmatically in app. Setting up the values from sharedpreferences. It takes the value and set burst mode off, 1x, 2x etc. according to value.

final String[] burst_mode_values = getResources().getStringArray(R.array.preference_burst_mode_values);
  String[] burst_mode_entries = getResources().getStringArray(R.array.preference_burst_mode_entries);
String burst_mode_value = sharedPreferences.getString(PreferenceKeys.getBurstModePreferenceKey(), "1");

Two methods created for setting up the previous and next values. To set up the previous value we need to check the current value to be not equal to -1 and greater that zero. Upgrade or downgrade the value of burst mode, according to the click.

public int onClickPrev() {
         if( burst_mode_index != -1 && burst_mode_index > 0 ) {
            burst_mode_index--;
            update(); ...
}

public int onClickNext() {
            if( burst_mode_index != -1 && burst_mode_index < burst_mode_values.length-1 ) {
              burst_mode_index++;
            update();...
}
  • Saving the value in sharedpreferences

So on clicking the previous and next, the value of burst mode value will be updated. As shown in the above code snippet, after every increment and decrement the values set on view and called update method to update the value in the sharedpreference as shown below.

private void update() {
        String new_burst_mode_value = burst_mode_values[burst_mode_index];
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(main_activity);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(PreferenceKeys.getBurstModePreferenceKey(), new_burst_mode_value);
editor.apply();}

  • Taking multiple Images

Now in the implementation part, we need to continuously click the image according to the burst value set by the user. So to enable this, first check the value not to be negative and should be greater than zero. Whole iteration work on separate variable named remaining burst photos. The value of the variable decrease after every image click i.e. takePhoto method calls.

if( remaining_burst_photos == -1 || remaining_burst_photos > 0 ) {
  if( remaining_burst_photos > 0 )
     remaining_burst_photos--;
  long timer_delay = applicationInterface.getRepeatIntervalPref();
  if( timer_delay == 0 ) {
     phase = PHASE_TAKING_PHOTO;
     takePhoto(true);
  }
  else {
     takePictureOnTimer(timer_delay, true);
  }
}

Resources:

 

Continue ReadingBurst Camera Mode in Phimpme Android

Implementing Change Password Feature in SUSI Android App using Custom Dialogs

Recently a new servlet was implemented on the SUSI Server about changing the password of the logged in user. This feature comes in handy to avoid unauthorized usage of the SUSI Account. Almost all the online platforms have this feature to change the password to avoid notorious user to unethical use someone else’s account. In SUSI Android app this new API was used with a nice UI to change the password of the user. The process is very simple and easy to grasp. This blog will try to cover the API information and implementation of the Change Password feature in the android client.

API Information

For changing the password of SUSI Account of the user, we have to call on  /aaa/changepassword.json

We have to provide three parameters along with this api call:

  1. changepassword:  Email of user (type string) using which user is logged in.
  2. password:  Old password (type string with min length of 6) of the user.
  3. newpassword: New password (type string with min length of 6) of the user.
  4. access_token: An encrypted access_token indicating user is logged in.

Sample Response (Success)

{
  "session": {"identity": {
    "type": "email",
    "name": "YOUR_EMAIL_ADDRESS",
    "anonymous": false
  }},
  "accepted": true,
  "message": "Your password has been changed!"
}

Error Response (Failure). This happens when user is not logged in:

HTTP ERROR 401
Problem accessing /aaa/changepassword.json. Reason:
   Base user role not sufficient. Your base user role is 'ANONYMOUS', your user role is 'anonymous'

Implementation in SUSI Android App

The change password option is located in Settings Activity and displayed only when user is logged in. So, if a logged in user wants to change the password of his/her SUSI AI account, he/she can simply go to the Settings and click on the option. Clicking on the options open up a dialog box with 3 input layouts for:

  1. Current Password
  2. New Password
  3. Confirm New Password

So, user can simply add these three inputs and click “Ok”. This will change the password of their account. Let’s see some code explanation.

  1. When user clicks on the “reset password” option from the settings, the showResetPasswordAlert() method is called which displays the dialog. And when user clicks on the “OK” button the resetPassword method() in the presenter is called passing input from the three input layout as parameters.

settingsPresenter.resetPassword(password.editText?.text.toString(), newPassword.editText?.text.toString(), conPassword.editText?.text.toString())

fun showResetPasswordAlert() {
   val builder = AlertDialog.Builder(activity)
   val resetPasswordView = activity.layoutInflater.inflate(R.layout.alert_reset_password, null)
   password = resetPasswordView.findViewById(R.id.password) as TextInputLayout
   newPassword = resetPasswordView.findViewById(R.id.newpassword) as TextInputLayout
   conPassword = resetPasswordView.findViewById(R.id.confirmpassword) as TextInputLayout
   builder.setView(resetPasswordView)
   builder.setTitle(Constant.CHANGE_PASSWORD)
           .setCancelable(false)
           .setNegativeButton(Constant.CANCEL, null)
           .setPositiveButton(getString(R.string.ok), null)
   resetPasswordAlert = builder.create()
   resetPasswordAlert.show()
   setupPasswordWatcher()
   resetPasswordAlert.getButton(AlertDialog.BUTTON_POSITIVE)?.setOnClickListener {
       settingsPresenter.resetPassword(password.editText?.text.toString(), newPassword.editText?.text.toString(), conPassword.editText?.text.toString())
   }
}
  1. In the resetPassword method, all details about the passwords are checked like:
  1. If passwords are not empty.
  2. If passwords’ lengths are greater than 6.
  3. If new password and confirmation new password matches

   

When all the conditions are satisfied and all the inputs are valid, resetPassword() in model is called which makes network call to change password of the user.

settingModel.resetPassword(password,newPassword,this)

override fun resetPassword(password: String, newPassword: String, conPassword: String) {
   if (password.isEmpty()) {
       settingView?.invalidCredentials(true, Constant.PASSWORD)
       return
   }
   if (newPassword.isEmpty()) {
       settingView?.invalidCredentials(true, Constant.NEW_PASSWORD)
       return
   }
   if (conPassword.isEmpty()) {
       settingView?.invalidCredentials(true, Constant.CONFIRM_PASSWORD)
       return
   }

   if (!CredentialHelper.isPasswordValid(newPassword)) {
       settingView?.passwordInvalid(Constant.NEW_PASSWORD)
       return
   }

   if (newPassword != conPassword) {
       settingView?.invalidCredentials(false, Constant.NEW_PASSWORD)
       return
   }
   settingModel.resetPassword(password,newPassword,this)
}

Summary

So, this blog talked about how the Change Password feature is implemented in SUSI Android App. This included how a network call is made, logic for making network, information about API, making dialogs with custom UI, etc. So, If you are looking forward to contribute to SUSI Android App, this can help you a little. But if not so, this may also help you in understanding and how you can implement a dialog box with custom UI.

References

  1. To know about servlets https://en.wikipedia.org/wiki/Java_servlet
  2. To see how to implement one https://www.javatpoint.com/servlet-tutorial
  3. To see how to make network calls in android using Retrofit https://guides.codepath.com/android/Consuming-APIs-with-Retrofit
  4. Official docs for displaying dialog https://developer.android.com/guide/topics/ui/dialogs.html
  5. Implementing dialog boxes with custom UI https://stackoverflow.com/questions/13341560/how-to-create-a-custom-dialog-box-in-android
  6. Pull Request for API reference: https://github.com/fossasia/susi_server/pull/352
Continue ReadingImplementing Change Password Feature in SUSI Android App using Custom Dialogs

Setting the Foreground Color Based on the Background Color in Phimpme Android

In the situations where the background color gets changed, the foreground color should also change to some other color. Otherwise the foreground item may not be properly visible on the background.

In Phimpme Android, we came across this situation when dealing with the bottom navigation bar. We have a preference option in our application which enables the user to change the primary color of the application. This change affects the background color of the bottom navigation bar also. We initially had white as selected foreground item’s color and grey as the unselected items’ color. It was fine for darker background colors. But problem arose when we changed the primary color of the application to the lighter shade of any color. The foreground item which was in white color was not clearly visible over the background. So we had to dynamically decide the foreground color when the background color gets changed.

Deciding the foreground color of the bottom navigation bar in Phimpme Android was tough. The foreground item should not only be visible on the background color but it should also be visibly attractive. We needed a minimal look. So we decided to use only two colors – black and white for the selected item’s color. The unselected items’ color can be fixed. A shade of gray with less alpha can be used for it.

The black and white colors are decided based on the lightness of the background color. We used the rgb value of the background color to find the lightness. We fixed a threshold for this lightness by visual judgement and selected the foreground color from the black and white colors based on this threshold lightness. If the lightness of the background color of the bottom navigation color of Phimpme Android application is less than the defined threshold value, we used white as the foreground color and vice-versa.

The lightness can be found out by taking the average of the red, green and blue values of the background color. We considered 100 as the threshold lightness for deciding the foreground color.

void setIconColor(int color){
   if(Color.red(color) + Color.green(color)+ Color.blue(color) < 300)
       colors[0] = Color.WHITE;
   else
       colors[0] = Color.BLACK;
}

For setting the different colors for different states of the foreground items on the bottom navigation bar, we used the setItemIconTintList method which takes ColorStatesList as an argument.

colors[1]  = ContextCompat.getColor(this, R.color.bottom_navigation_tabs);
ColorStateList bottomNavList = new ColorStateList(states, colors);
navigationView.setItemIconTintList(bottomNavList);

This above ColorStateList takes a two dimensional array of states for which we wanted to change the color of item and an array of corresponding colors for those states as arguments. In Phimpme Android we used the following way.

private int[][] states = new int[][] {
       new int[] {android.R.attr.state_checked}, // checked
       new int[] {-android.R.attr.state_checked}, // unchecked
};

private int[] colors = new int[] {
       Color.WHITE, // checked
       0 // unchecked set default in onCreate
};

Resources:

Continue ReadingSetting the Foreground Color Based on the Background Color in Phimpme Android

Full-Screen Speech Input Implementation in SUSI Android App

SUSI Android has some very good features and one of them is, it can take input in speech format from user i.e if the user says anything then it can detect it and convert it to text. This feature is implemented in SUSI Android app using Android’s built-in speech-to-text functionality. You can implement Android’s built-in speech-to-text functionality using either only RecognizerIntent class or SpeechRecognizerIntent class, RecognitionListner interface and RecognizerIntent class. Using former method has some disadvantages:

  • During speech input, it shows a dialog box (as shown here) and it breaks the connection between user and app.
  • We can’t show partial result i.e text to the user but using the later method we can show it.

We used  SpeechRecognizerIntent class, RecognitionListner interface and RecognizerIntent class to implement Android’s built-in speech-to-text functionality in SUSI Android and you know the reason for that. In this blog post, I will show you how I implemented this feature in SUSI Android with new UI.

Layout design

You can give speech input to SUSI Android either by clicking mic button

or using ‘Hi SUSI’ hotword. When you click on mic button or use ‘Hi SUSI’ hotword, you can see a screen where you will give speech input.

Two important part of this layout are:

<TextView

  android:id=“@+id/txtchat”

  android:layout_width=“wrap_content”

  android:layout_height=“wrap_content”

  

 />

  • TextView: It used to show the partial result of speech input i.e it will show converted text (partial) of your speech.
<org.fossasia.susi.ai.speechinputanimation.SpeechProgressView

  android:id=“@+id/speechprogress”

  android:layout_width=“match_parent”

  android:layout_height=“50dp”

  android:layout_margin=“8dp”

  android:layout_gravity=“center”/>

  • SpeechProgressView: It is a custom view which use to show the animation when the user gives speech input. When the user starts speaking, the animation starts. This custom view contains five bars and these five bars animate according to user input.

Full-screen speech input implementation

When the user clicks on mic button or uses ‘Hi SUSI’ hotword, a screen comes where the user can give speech input. As already mentioned I used SpeechRecognizerIntent class, RecognitionListner interface and RecognizerIntent class to implement speech-to-text functionality in SUSI Android. RecognizerIntent class starts an intent and asks for speech input

val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)

intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,

    RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)

intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, “com.domain.app”)

intent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true)

and send it through the speech recognizer. It does it through ACTION_RECOGNIZE_SPEECH. SpeechRecognizer class provides access to the speech recognition service. This service allows access to the speech recognizer and recognition related event occurs RecognitionListner receive notification from SpeechRecognizer class.

recognizer = SpeechRecognizer

      .createSpeechRecognizer(activity.applicationContext)

val listener = object : RecognitionListener {

 //implement all override methods

}

When the user starts speaking, the height of bars changes according to change in sound level. When sound level changes, onRmsChanged method get called where we are calling onRmsChanged method of SpeechProgressView class which is responsible for animating bars according to change in sound level.

override fun onRmsChanged(rmsdB: Float) {

  if (speechprogress != null)

      speechprogress.onRmsChanged(rmsdB)

}

When user finished speaking onEndOfSpeech method get called where we call onEndOfSpeech method of SpeechProgressView class which is responsible for rotating animation. Rotation is used to show that SUSI Android has finished listening and now it is processing your input.

override fun onEndOfSpeech() {

  if (speechprogress != null)

      speechprogress.onEndOfSpeech()

}

In case of any error, onError method get called and in case of successful speech input, onResults method get called. In both cases, we reset bars to their initial position and show chat activity user. The user can again give speech input either by clicking on mic or using ‘Hi SUSI’ hotword.

override fun onResults(results: Bundle) {

  if (speechprogress != null)

      speechprogress.onResultOrOnError()

  activity.supportFragmentManager.popBackStackImmediate()

}

Reference

Continue ReadingFull-Screen Speech Input Implementation in SUSI Android App

Uploaded Images History in Phimpme Android

In Phimpme Android one core feature is of sharing images to many different platforms. After sharing we usually wants to look in the our past records, where we uploaded what pictures? Which image we uploaded? What time it was? So I added a feature to view the upload history of images. User can go to the Upload history tab, present in the navigation drawer of the app. From there he can browse the repository.

How I added history feature in Phimpme

  • Store the data when User initiate an upload

To get which data uploading is in progress. I am storing its name, date, time and image path. When user approve to upload image from Sharing Activity.

Created a database model

public class UploadHistoryRealmModel extends RealmObject{

   String name;
   String pathname;
   String datetime;

   public String getName() {
       return name;
   }

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

   public String getPathname() {
       return pathname;
   }

   public void setPathname(String pathname) {
       this.pathname = pathname;
   }

   public String getDatetime() {
       return datetime;
   }

   public void setDatetime(String datetime) {
       this.datetime = datetime;
   }
} 

This is the realm model for storing the name, date, time and image path.

Saving in database

UploadHistoryRealmModel uploadHistory;
uploadHistory = realm.createObject(UploadHistoryRealmModel.class);
uploadHistory.setName(sharableAccountsList.get(position).toString());
uploadHistory.setPathname(saveFilePath);
uploadHistory.setDatetime(new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new Date()));
realm.commitTransaction();

Creating realm object and setting the details in begin and commit Transaction block

  • Added upload history entry in Navigation Drawer

    <LinearLayout
       xmlns:android="http://schemas.android.com/apk/res/android"
       android:id="@+id/ll_drawer_uploadhistory"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:background="@drawable/ripple"
       android:clickable="true"
       android:orientation="horizontal">
    
       <com.mikepenz.iconics.view.IconicsImageView
           android:id="@+id/Drawer_Upload_Icon"
           android:layout_width="@dimen/icon_width_height"
           android:layout_height="@dimen/icon_width_height"
           app:iiv_icon="gmd-file-upload"/>
    
       <TextView
           android:id="@+id/Drawer_Upload_Item"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="@string/upload_history"
           android:textColor="@color/md_dark_background"
           android:textSize="16sp"/>
    </LinearLayout>

It consist of an ImageView and TextView in a horizontal oriented Linear Layout

  • Showing history in Upload History Activity

Added recyclerview in layout.

<android.support.v7.widget.RecyclerView
   android:id="@+id/upload_history_recycler_view"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:layout_below="@id/toolbar">
</android.support.v7.widget.RecyclerView>

Query the database and updated the adapter of Upload History

uploadResults = realm.where(UploadHistoryRealmModel.class);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
uploadHistoryRecyclerView.setLayoutManager(layoutManager);
uploadHistoryRecyclerView.setAdapter(uploadHistoryAdapter);

Added the adapter for recycler view and created an Item using Constraint layout.

Resources

Continue ReadingUploaded Images History in Phimpme Android

Shortcuts in the Phimpme Android Application

The Phimpme Android application comes with a great functionality of capturing moments, editing them, and sharing it with the world using various social media or cloud platforms integrated into the application. Sometimes, the user may want to directly go to a particular section of the application without having to go to the home activity all the time. We have solved this issue using the App shortcuts option which is provided on Android versions greater than 7.0 Nougat. When the user long clicks on the icon of the application, it provides us with multiple options to choose which activity or section we would like to go to as depicted in the screenshot below.

In this post, I will be explaining how we have achieved this functionality in the Phimpme Android application.

Step 1

In the Phimpme app, we have three main sections named Camera, Gallery and Accounts and we have added these three options in the app shortcut menu. To do this, first of all, we need to add a meta data to the main activity in the AndroidManifest.xml file. To do this, search for the activity which contains “android.intent.action.MAIN” and add the following line of code in the activity tag.

<meta-data android:name="android.app.shortcuts"
  android:resource="@xml/shortcuts" />

Step 2

Now after we have configured the manifest file, we need to create shortcuts.xml file in the resources folder which will contain the information about our app shortcuts along with the intent action to go to a particular activity.

After creating the xml file, add the following line of code.

<shortcuts xmlns:tools="http://schemas.android.com/tools"
  xmlns:android="http://schemas.android.com/apk/res/android">

Now after this we have to create a shortcut tag and define the id of our shortcut and should add the icon to it which will be displayed to the user along with the shortcut text as depicted in the screenshot above. This can be done using the following line of code.

android:shortcutId="camera"
android:enabled="true"
android:icon="@drawable/ic_camera_alt_black_24dp"
android:shortcutShortLabel="@string/camera_short"
android:shortcutLongLabel="@string/camera_long"
android:shortcutDisabledMessage="@string/camera_short"

Now after this, we have to define the action which we want to perform when the user clicks on a particular app shortcut. To do this, create an intent tag and add the following lines of code in it.

<intent
  android:action="android.media.action.IMAGE_CAPTURE_SECURE"
  android:targetPackage="org.fossasia.phimpme"
  android:targetClass="org.fossasia.phimpme.opencamera.Camera.CameraActivity" />
<categories android:name="android.intent.category.DEFAULT" />

The above code sets the action type as Image capture and defines the package name of the application. The above code is used to open the Camera activity of the Phimpme Application from the shortcut menu. In the similar fashion as described above, we have implemented the option to open up the Gallery and Accounts section of our application by just modifying the action name of the shortcut.

This is how we have implemented the App shortcut functionality in the Phimpme app. To get the full source code of the Shortcuts.xml file, please refer to the Phimpme Android repository.

Resources

  1. Android Developer’s Guide – App shortcuts – https://developer.android.com/guide/topics/ui/shortcuts.html
  2. GitHub – Google Sample Project to depict the usage of app shortcuts – https://github.com/googlesamples/android-AppShortcuts
  3. Blog – Using app shortcuts in Android 7.0 – http://www.brevitysoftware.com/blog/how-to-use-app-shortcuts-in-android-7-1-nougat/
  4. GitHub – Phimpme Android repository – https://github.com/fossasia/phimpme-android/
Continue ReadingShortcuts in the Phimpme Android Application

Using RecyclerView Instead Of ViewPager For Gallery

Phimpme is an Image app that provide camera, editing ,sharing options and a gallery section. The Gallery section allows us to view large number of images that are locally available in the users device. Generally developers used viewpager to swipe the horizontal images although we are also using viewPager but the problem is it is taking more time to load large size images and that disturb the user smooth experience. After so much research I came to new solution. So in this post, I will be explaining how to use recyclerview to view gallery images instead of viewPager.

Let’s get started

Make sure you have Recyclerview support in your dependencies in build.gradle. As recyclerView required an adapter and viewHolder to set data in recyclerView. So I will be explaining about adapter.

ViewHolder for RecyclerView

public static class ViewHolder extends RecyclerView.ViewHolder {
  ImageView imageView;
  LinearLayout linearLayout;

  public ViewHolder(View itemView) {
      super(itemView);
      imageView = new ImageView(context);
      linearLayout = (LinearLayout) itemView.findViewById(R.id.layout);
      WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
      Display display = wm.getDefaultDisplay();
      Point size = new Point();
      display.getSize(size);
      int width = size.x;
      int height = size.y;
      LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
              width, height);
      imageView.setLayoutParams(params);
      imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
      linearLayout.addView(imageView);
  }
}

Right now the imageView is adjusting according to device screen size so that it will be compatible with all devices.

I am passing the width and height in LayoutParams to parent of imageview i.e in our case linearlayout is parentView.

Adapter for RecyclerView

public ImageAdapter(ArrayList<Media> media) {
  this.media = media;
}

@Override
public ImageAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
  View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.unit_image_pager, null, false);

  return new ViewHolder(view);
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
  Glide.with(getContext())
          .load(media.get(position).getUri())
          .diskCacheStrategy(DiskCacheStrategy.SOURCE)
          .thumbnail(0.5f)
          .into(holder.imageView);
  holder.imageView.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
          basicCallBack.callBack(0,null);
      }
  });
}

MediaList is an arrray of media that contains the list of images with URI that will help to load images. I am using Glide to load images you can use any library to load images. Adapter helps to load data in recyclerView.

Now set viewPager where you require to scroll images horizontally

@Nullable @BindView(R.id.photos_pager)
RecyclerView mRecylerPager;
mRecylerPager.setLayoutManager(linearLayoutManager);
mRecylerPager.setHasFixedSize(true);
mRecylerPager.setLongClickable(true);

Our recycler view is ready now the most important part is to set things onPageChangeListner. For example : In Phimpme we are getting path of current position image to show in image description so to update the value we are writing that codde in onPageChangeListner and to update the toolbar.

mViewPager.setOnPageChangeListener(new PagerRecyclerView.OnPageChangeListener() {
  @Override
  public void onPageChanged(int oldPosition, int position) {
      getAlbum().setCurrentPhotoIndex(position);
      toolbar.setTitle((position + 1) + " " + getString(R.string.of) + " " + size_all);
      invalidateOptionsMenu();
      pathForDescription = getAlbum().getMedia().get(position).getPath();
  }
});

To scroll to the given position we require to set the position to recyclerView and it can be done by the following code

mViewPager.scrollToPosition(getCurrentPsotion());

This is how I implemented the recyclerView instead of ViewPager to load gallery images faster as compare to ViewPager.

RecyclerView in Phimpme to load gallery Images

Resources:     

 

Continue ReadingUsing RecyclerView Instead Of ViewPager For Gallery