Showing posts with label Android. Show all posts
Showing posts with label Android. Show all posts

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.

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).




27 Sept 2015

Developing Notifications In android

Notification in android  is a special type of message which is used to show useful information when your app's UI is not visible to user.
Creating Notification is very simple, even you can create Notification by simply reading android Developer Guide.
Today I am will provide a ready to use code for creating notification for your app, Just copy this code and paste in your app code.
notification
 @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
 public void createNotification(){

     NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

// Following Three notification contents are *required 
     builder.setSmallIcon(R.drawable.notification_icon);
     builder.setContentTitle("Notification Title");
     builder.setContentText("Notification Details");

 // intent to start activity, provide Activity name where you want user to
  //to land when he/she clicks on notification, like: MainActivity

     Intent resultIntent = new Intent(this,MainActivity.class);

// Task builder to implement normal navigation 
     TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
     stackBuilder.addParentStack(MainActivity.class);

     stackBuilder.addNextIntent(resultIntent);

     PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
     builder.setContentIntent(resultPendingIntent);

     NotificationManager mNotifym = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// specify notification id,as first argument, i.e. I have used id=10
     mNotifym.notify(10, builder.build());


 }

 For Removing Notification use following code.
NotificationManager mNotifym = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mNotifym.cancelAll();

This is a basic version of notification, you can add more feature by going through documentation. 

15 Aug 2015

how to Learn Android App Development ?

For Learning Android Development, there are thousands of tutorial available online, But choosing one which explains concepts in a easy way is very difficult.

Today I am going to list out some of best online resources to learn Android Development,most of these Tutorial are available free of cost. And if you are new to android Development, then before going to any other Tutorial, I would suggest you to go through following Tutorials which very useful and conceptual tutorials.

  1. Android Development for Beginners - Udacity : Video Tutorial for Complete beginners.
  2. Training for Android developers - Web based Text Tutorial Covering Basic Concepts By Google.
If during going through above Tutorial you find some topics difficult to understand then Google for that particular topic.
After going through above Tutorials you can go for any other tutorial, like Android Essential Training from Lynda.com.
Best Way to learn is to Develop small Apps,which cover basic android concepts, while learning Android Development.

So in the upcoming posts in this series of Android Development i will be posting Ideas and Concepts for Developing simple android Apps.