2 May 2016

Handling Multiple Item Selection in A Listview - Android Tutorial

In this tutorial, we will learn how to respond when a user selects multiple list items in an Activity . For the purpose of this tutorial, I will be selecting multiple list items for deleting them from the database. This tutorial also covers on how to change listItem background color when the user selects multiple items.

Idea :

Listen to long press on a list item and store list id in an ArrayList if checked state is True, otherwise, if checked state is false then remove the item id from ArrayList.

pre-setup :

    Added a ListView to the layout file and attached a cursorAdepter with it.This how my final
listview looks like. 

If you are displaying list using values from the database, then make sure that the primary key name is "_id" in your database table.
Now follow below-given steps to listen for multiple list item selection
1. Set Global Variable
Context context;
private  ListView list;
private ArrayList list_item = new ArrayList<>(); // for holding list item ids
2. Change list CHOICE_MODE as follows
//(list) is my ListView           
list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL); // Important

3. Set MultiChoiceModeListener to your ListView variable
list.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
            @Override
            public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
                //capture total checked items
                checkedCount = list.getCheckedItemCount();

                //setting CAB title
                mode.setTitle(checkedCount + " Selected");

                //list_item.add(id);
                if(checked){
                    list_item.add(id);     // Add to list when checked ==  true
                }else {
                    list_item.remove(id);
                }

            }

            @Override
            public boolean onCreateActionMode(ActionMode mode, Menu menu) {
                //Inflate the CAB
                MenuInflater inflater = mode.getMenuInflater();
                inflater.inflate(R.menu.contextual_menu, menu);
                return true;
            }

            @Override
            public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
                return false;
            }

            @Override
            public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
                final int deleteSize = list_item.size();
                      int itemId = item.getItemId();
                if(itemId == R.id.item_delete) {

                     for(long ids : list_item){
                            // Make proper check, if needed, before deletion 
                            String whereDelId = DBOpenHelper.COL_ID + "=" + ids;
                            int res = getContentResolver().delete(TripProvider.CONTENT_URI_START, whereDelId, null);
                            if(res == -1){
                               Log.d(TAG, "onActionItemClicked: Delete Failed for ID = "+ids);
                            }  
                     }

                }  
             Toast.makeText(context,deleteSize+" Items deleted",Toast.LENGTH_SHORT).show();

                checkedCount = 0;
                list_item.clear();
                mode.finish();
                return true;
            }

            @Override
            public void onDestroyActionMode(ActionMode mode) {
                // refresh list after deletion
                displayDataList();
            }
        });

Changing background Color of Selected ListView List items.

4.   Create a drawable XML for list item background.{mine is, select_list_bg,xml}
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"
    android:exitFadeDuration="@android:integer/config_shortAnimTime">
     <item  android:state_pressed="true"
         android:state_activated="true"
         android:drawable="@color/lightPink"></item>
    <item
        android:state_activated="true"
        android:drawable="@color/lightPink"></item>

    <item  android:drawable="@color/lightGreen"></item>
    <item android:state_enabled="true"
        android:drawable="@color/lightGreen"></item>
</selector>
5. Set above drawable as background to listItem
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/select_list_bg,xml"
    android:elevation="4dp">

 <!-- Your List item child views -->
</RelativeLayout>
This is the final look of the List when user selects multiple items.



7 Mar 2016

Animating Android App - Animation Tutorial 01

This is a ready to serve tutorial for learning animations in android applications.You will be able to animate your app right away after  going through this article.If want to learn android animation thoroughly then go by animation documentation by Google.

What will be covered in this tutorial

  1.    animations using ViewPropertyAnimator
  2.    animation using java code
  3.    animation using XML
1.  Using ViewPropertyAnimator

.animate () is an Object of the class ViewPropertyAnimator and very easy to use.There are several properties which can be animated by this function like, alpha, X, Y, rotation etc.
Example, FadeOut a TextView
 myTextView.animate().alpha(0).setDuration(500);

2. Using ObjectAnimator

This animator is used for some more complex animations and also helpful when you want to choreograph the animations.
Example, For transitioningTextView in x-direction.

//ObjectAnimator anim = ObjectAnimator.ofFloat(view,property, startvalue, endValue);
ObjectAnimator anim = ObjectAnimator.ofFloat(myTextView, View.X, 0, 100);
anim.setDuration(1000);
anim.start();

3. Using XML

XMLs are used for simple transformations (position, size, rotation, and transparency).XML file is recommended because of its readability, reusability than hard-coding the animation
Example, For scaling an ImageView
<set android:shareInterpolator="false">
    <scale
        android:interpolator="@android:anim/accelerate_decelerate_interpolator"
        android:fromXScale="1.0"
        android:toXScale="1.4"
        android:fromYScale="1.0"
        android:toYScale="0.6"
        android:pivotX="50%"
        android:pivotY="50%"
        android:fillAfter="false"
        android:duration="700" />
</set>
Now we need to inflate and apply above animation to our ImageView.
//Animation XML is in directory Drawables>anim>scale_anim.xml
ImageView myImageView = (ImageView) findViewById(R.id.myImage);
Animation scaleAnimation= AnimationUtils.loadAnimation(this, R.anim.scale_anim);
myImageView.startAnimation(scaleAnimation);

If you want more in this series let me know through comments.

23 Jan 2016

How to create App video demo with zero budget ?

Have you developed an app and looking to create a video demo for it? then you must have come across many online service providers like, placeit.net, which provides a decent app demo.

But the problem with them is that their free version is not so great in video quality [plus watermark in background] and charge for premium version is quite high for a newcomer and a person like me, who don't have that much money.

how to create video demo with no money?

Well, I have a Jugaad for that, you just need Microsoft PowerPoint installed on your computer.

How to Do it?

01. Create a good looking slide background, give it a Tabletop  texture with some added features, like, coffee cup,pen.diary etc.


02.Create an outer frame of a smart phone and import it into the powerpoint slide.

03. Record you app Screen with whatever feature you want to show in the demo.[What I used is, AZ screen Recoreder]

04. Import captured video into powerpoint slide and Crop the unnecessary area.And try to fit the video inside Phone frame.[send it to backward]


05. Set animations to the instructions and set video play settings to automatic start.

06. Start SlideShow and record screen, with any other application or in-built screen recored in power point.

That's it, Although it may not look like a professional but serves the purpose until you get the money for a professional video demo.
Below is the video demo, I created for my app. and here is the ppt.




25 Dec 2015

Power of Habit II: How to Quit A Bad Habit?

A bad habit is a non-desirable behaviour or routine, for example, eating cookies while watching TV, overspending, nail-biting etc.

To Learn about How Habits work, Please go through Previous post.

Commonly it is very hard to eliminate a bad habit but Habits aren’t destiny they can be ignored, changed or replaced. You simply have to learn the different components of the habit loop for that particular bad habit to control.

Change might not be fast and it isn’t always easy. But with time and effort, almost any habit can be reshaped. Use the following framework to reshape your habit.

The Framework:
  • Identify the routine
  • Experiment with rewards
  • Isolate the cue
  • Have a plan
After understanding different segments of your habit, leave the cue and reward part and try to change the routine to achieve the same or equivalent reward.

Let’s say you have a bad habit of frequently wasting a lot of time on the internet during your studies.
Well, first I am going to break this habit in three fragments i.e. Cue, Routine and Reward. Identifying each fragment is a trial and error task. Follow above-mentioned steps for easing the task. 

Step 1: Identify the routine
Surfed some news articles then Opened Facebook from there went to YouTube.

Step 2: Experiment with Rewards
Try to figure out which cravings are driving this particular habit. Like, go outside and have a glass of water or a small chit-chat with parents, colleagues or anyone present out there, or just walk outside for some time and return to your desk. Don’t perform all of above activities on the same day instead try one activity for 3/4 days and see if after returning, you still have an urge for internet surfing, if yes then keep experimenting with the reward.
Let’s say Going out and wandering a little in the Balcony helped the problem. The reward needed by your brain was a little change of scenery.   

Step 3: Isolate the Cue
To identify a cue amid the noise we will identify categories of behaviour ahead of time to scrutinise in order to see the pattern. Experiments have shown that almost all habitual cues fit into one of five categories.
  • Location – Where are you? (sitting at your desk)
  • Time – What time is it? (8:30 pm)
  • Emotional State – What’s your emotional state? (bored)
  • Other people – Who else is around? (no one)
  • Immediately preceding action - What action preceded the urge? (Surfed Internet)
Answer above questions at different times of study hours and after 4/5 trial you will clearly understand that what is causing this behaviour. Like, you may find that boredom is causing this behaviour.

Step 4: Have a plan
Once you have identified Cue, Routine and Reward, try different routines to get the same rewards like going outside for a change of scenery, having a glass of water or a small chit chat with parents, neighbours etc.

Changing a habit is a difficult task but once you experiment with it and understand how a habit operates (once you diagnose the cue, the routine and the reward); you can control or change the habit for sure.
Remember,
  



Power of Habit I : How to form a new Habit?

Habit is a process by which behaviour becomes automatic. The brain does not take part in decision-making while performing a particular habitual Task, like eating.

The time period for forming a new habit varies person to person, it may take days to months.

This process of habit formation in our brain is a three-step loop. First one is the Cue, which tells our brain to go into automatic mode and use routine associated with that particular cue. Second is the Routine which can be physical or mental or emotional. The final step is the Reward which helps our brain to figure out if this particular loop is worth remembering for the future.

This process for a particular behaviour is saved inside our brain; it just needs a cue to trigger the process. Focus of brain shifts to reward rather than on process, that’s why we don’t need to think while performing the routine.

For example, a soon as we see a man crossing a road (cue) our foot automatically pushes the break (saved routine for this cue) to stop (result) the car.

How to form a New Habit?

Suppose you have a fat belly and want to develop a habit of daily exercise, then to form the habit, you have to break the process in, cue (which will help in triggering the habit), routine (the automatic behaviour which will be saved in brain) and reward (On which brain's focus will be while performing the behaviour) segments.

Keep cues as simple as possible, for example, keep your running shoes nearby your bed in the night so as soon as brain sees the shoe, it triggers the routine to go outside for a run. Keep rewards worth remembering for the brain, like have a cup of coffee or a beautiful conversation with a neighbour while returning.


So as soon as your brain remembers this loop, the moment you will put shoes on, brain's focus will shift from hard the part[going outside for running] to the smooth ‘reward’ part [getting a coffee while retuning].   

For Learning How to change a bad Habit Please go through next Post. 


17 Dec 2015

How to speed up Lagging android Phone without installing any Application ?

If your android phone is getting slow and lagging frequently, and installing any external apps isn't solving the problem then we have a nice solution for you.


First understand the possible cause:

Your android phone may be getting slow due to a higher animations scale, in which different animations takes a longer time to complete, or due to too many running apps in the background, consuming your phone's battery and RAM.

Now Let's get to the Solution:

For speeding up the phone, we will decrease the animation scale and limit the number of the background processes, eventually, this will increase your phone's battery life.

For this Approach, first of all, enable the 'DEVELOPER OPTION' in your android phone by tapping 5 to 7 times on 'Build Number' [settings > About Phone > Build Number].
[See Video Below]
After enabling 'Developer options' open it and scroll down to 'Drawing' section and decrease all animation scale to 0.5x.
then scroll down to 'Apps' section and click 'Background process limit' and select 3 or 4 processes.

video help:


That's it, now see the difference while using your phone.

7 Dec 2015

How to deal with redirecting ad type virus in Android

Recently I faced an issue with my android device whenever I would try to access a link or do a google search in Google Chrome / Mozilla Firefox, I would get redirected to Malware/Adware sites.

The Problem:
These Malware / Adware sites then redirect to  an annoying pop up saying that I have won an Award or My Tab has a dangerous Virus.And there is no way of going back to the previous site.
I tried many anti-virus and anti-malware but no relief.


Solution:
First of all, Clean Junk and any unnecessary stuff from your device using any cleaning app, like Clean master then try a Good anti-virus or anti-malware, if it works for you then good luck.
If it doesn’t work then here are two quick solutions,
1. Delete your browser Directory Manually by connecting your device to PC and then,
Android >> data >> browser(chrome) >> shift-Delete


2. Try to open your web page in ‘Desktop’ Mode by Clicking the ‘Request desktop site’ option. this is not a permanent solution but a good one if you are trying to do a secure transaction on your android device (like, banking).




5 Dec 2015

Li-Fi : The Next Generation High Speed Wireless Network

Li-Fi (Light Fidelity)  is the latest high speed and fully networked wireless communication technology.Original founder of Li-Fi is Professor Harald Hass from the University of Edinburgh in the UK, he is also a Co-Founder of pureLiFi, a company that has taken a lead in bringing this ground breaking-research to market.

Some of amazing Fact about this technology are as follows:
0. Very High Speed
  In real-world office and industrial environments a speed of 1 Gbit/s has been achieved but Researchers have reached a data rate of over 224 Gbit/s in a laboratory environment, at this speed you can download 18 feature-length movies in single second.

1. No limitations on capacity
 This technology uses visible light or infra-red and near ultraviolet spectrum, it does not uses Radio wave frequency which can cause a potential spectrum crisis because Wi-Fi is close to full capacity. Li-Fi has almost no limitations on capacity.

2. Use of LEDs bulbs as a data transmitter 
 Lifi will transmit data with the help of LED light bulbs by turning them ON and OFF at a very high rate, too quickly to be noticed by a human eye.At night time bulbs can be dimmed to below human visibility while still emitting enough light to carry data.


3. Can be used in Aircraft Cabins
 Li-Fi can be used in electromagnetic sensitive areas such Aircraft Cabins, Hospitals and Nuclear power plants.

4. Direct line of sight isn't necessary
 For Li-Fi to transmit signals, light reflected off walls can achieve a speed of 70 Mbit/s.


5. More Privacy and Security
 Light waves can not pass through walls which makes it a short range network, though making it more secure from hacking, relative to Wi-Fi.

In short Li-Fi is expected to be Ten times cheaper than Wi-Fi. But Short Range, Low Reliability and high installation costs are the potential downsides.

Here is Promo Video By PureLiFi,