Sunday, 20 January 2019

Basic Question

What is Inent

An Intent is basically a message to say you did or want something to happen. Depending on the intent, apps or the OS might be listening for it and will react accordingly.

Intents are a way of telling to Android what you want to do. In other words, you describe your intention. Intents can be used to signal to the Android system that a certain event has occurred. Other components in Android can register to this event via an intent filter.
Following are 2 types of intents

1.Explicit Intents

used to call a specific component. When you know which component you want to launch and you do not want to give the user free control over which component to use. For example, you have an application that has 2 activities. Activity A and activity B. You want to launch activity B from activity A. In this case you define an explicit intent targeting activityB and then use it to directly call it.

2.Implicit Intents

used when you have an idea of what you want to do, but you do not know which component should be launched. Or if you want to give the user an option to choose between a list of components to use. If these Intents are send to the Android system it searches for all components which are registered for the specific action and the data type. If only one component is found, Android starts the component directly. For example, you have an application that uses the camera to take photos. One of the features of your application is that you give the user the possibility to send the photos he has taken. You do not know what kind of application the user has that can send photos, and you also want to give the user an option to choose which external application to use if he has more than one. In this case you would not use an explicit intent. Instead you should use an implicit intent that has its action set to ACTION_SEND and its data extra set to the URI of the photo.

Explicit Android Intent is the Intent in which you explicitly define the component that needs to be called by Android System.
 Intent MoveToNext = new Intent (getApplicationContext(), SecondActivity.class);
Implicit Android Intent
Implicit Android Intents is the intent where instead of defining the exact components, you define the action you want to perform.

                              Fragment

Fragment represents a behavior or a portion of user interface in an Activity. You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities. You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running (sort of like a "sub activity" that you can reuse in different activities).

Service

Service is an application component that can perform long-running operations in the background, and it does not provide a user interface. Another application component can start a service, and it continues to run in the background even if the user switches to another application. Additionally, a component can bind to a service to interact with it and even perform interprocess communication (IPC). For example, a service can handle network transactions, play music, perform file I/O, or interact with a content provider, all from the background.
These are the three different types of services:
Foreground
A foreground service performs some operation that is noticeable to the user. For example, an audio app would use a foreground service to play an audio track. Foreground services must display a status bar icon. Foreground services continue running even when the user isn't interacting with the app.
Background
A background service performs an operation that isn't directly noticed by the user. For example, if an app used a service to compact its storage, that would usually be a background service.

Friday, 24 November 2017

Object Animator

Android provides the Properties Animation API which allow to change object properties over a pre-defined time interval. It can be used for arbitrary object properties and on any object not only Android views




The superclass of the animation API is the Animator class. Typically the ObjectAnimator class is used to modify the attributes of an object.
You can also add an AnimatorListener class to your Animator class. This listener is called in the different phases of the animation. You can use this listener to perform actions before orafter a certain animation, e.g. add or remove a View from a ViewGroup.


 float scale = getResources().getDisplayMetrics().density;
        ObjectAnimator anim1 = ObjectAnimator.ofFloat(img,
                "x", transitionsContainer.getX(), 150.0f * scale);
        ObjectAnimator anim2 = ObjectAnimator.ofFloat(img,
                "y", transitionsContainer.getY(), 150.0f * scale);
//                ObjectAnimator anim3 = ObjectAnimator.ofFloat(someImage,//                        "x", 220.0f*scale, 20.0f*scale);//                ObjectAnimator anim4 = ObjectAnimator.ofFloat(someImage,//                        "y", 220.0f*scale, 20.0f*scale);        AnimatorSet set = new AnimatorSet();
        set.play(anim2).after(500);
        // set.play(anim2).after(500);        set.setDuration(1000);
        set.setInterpolator(new LinearInterpolator());
        set.start();
        set.addListener(new Animator.AnimatorListener() {
            @Override            public void onAnimationStart(Animator animator) {

            }

            @Override            public void onAnimationEnd(Animator animator) {
                img.setVisibility(View.INVISIBLE);
                logo.setVisibility(View.VISIBLE);
                new Handler().postDelayed(new Runnable() {
                    @Override                    public void run() {
                        sharedPreferences= getSharedPreferences("pref",MODE_PRIVATE);
                        if(sharedPreferences.getBoolean("islogin",false)){
                            Intent in = new Intent(getApplicationContext(), Home_Activity.class);
                            Sample sample= new Sample( R.color.colorPrimary, "Shared Elements");
                            in.putExtra("sample", sample);
                            in.putExtra("type", 0);
                            transitionTo(in);
                            finish();
                        }else {
                            Intent in = new Intent(Splash.this, MainActivity.class);
                            // startActivity(in);                            Sample sample= new Sample( R.color.colorPrimary, "Shared Elements");
                            in.putExtra("sample", sample);
                            in.putExtra("type", 0);
                            transitionTo(in);
                            finish();
                        }
                    }
                },1000);

            }

            @Override            public void onAnimationCancel(Animator animator) {

            }

            @Override            public void onAnimationRepeat(Animator animator) {

            }
        });


Activity animations in Android with shared views

  sharedImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //This is where the magic happens.
                // makeSceneTransitionAnimation takes a context, view,
                // a name for the target view.
                ActivityOptions options =
                        ActivityOptions.
                        makeSceneTransitionAnimation(MainActivity.this, sharedImage, "sharedImage");
                Intent intent = new Intent(MainActivity.this, SecondActivity.class);
                startActivity(intent, options.toBundle());
            }
        });

Wednesday, 24 May 2017

Content Provider



If you want to share data with other applications you can use a content provider (short provider). Provider offer data encapsulation based on URI’s. Any URI which starts withcontent:// points to a resources which can be accessed via a provider. A URI for a resource may allow to perform the basic CRUD operations (Create, Read, Update, Delete) on the resource via the content provider.



Content providers let you centralize content in one place and have many different applications access it as needed. A content provider behaves very much like a database where you can query it, edit its content, as well as add or delete content using insert(), update(), delete(), and query() methods. In most cases this data is stored in an SQlite database.


Thursday, 4 May 2017

FragmentPagerAdapter VS FragmentStatePagerAdapter

FragmentPagerAdapter

This version of the pager is best for use when there are a handful of typically more static fragments to be paged through, such as a set of tabs. The fragment of each page the user visits will be kept in memory, though its view hierarchy may be destroyed when not visible. This can result in using a significant amount of memory since fragment instances can hold on to an arbitrary amount of state. For larger sets of pages, consider FragmentStatePagerAdapter.


FragmentStatePagerAdapter

This version of the pager is more useful when there are a large number of pages, working more like a list view. When pages are not visible to the user, their entire fragment may be destroyed, only keeping the saved state of that fragment. This allows the pager to hold on to much less memory associated with each visited page as compared to FragmentPagerAdapter at the cost of potentially more overhead when switching between pages.




  • FragmentPagerAdapter stores the whole fragment in memory, and could increase a memory overhead if a large amount of fragments are used in ViewPager.
  • In contrary its sibling, FragmentStatePagerAdapter only stores the savedInstanceState of fragments, and destroys all the fragments when they lose focus.
  • Therefore FragmentStatePagerAdapter should be used when we have to use dynamic fragments, like fragments with widgets, as their data could be stored in the savedInstanceState.Also it wont affect the performance even if there are large number of fragments.
  • In contrary its sibling FragmentPagerAdapter should be used when we need to store the whole fragment in memory.
  • When I say the whole fragment is kept in memory it means, its instances wont be destroyed and would create a memory overhead. Therefore it is advised to use FragmentPagerAdapter only when there are low number of fragments for ViewPager.
  • It would be even better if the fragments are static, since they would not be having large amount of objects whose instances would be stored.
To be more detail,
FragmentStatePagerAdapter:
  • with FragmentStatePagerAdapter,your unneeded fragment is destroyed.A transaction is committed to completely remove the fragment from your activity's FragmentManager.
  • The state in FragmentStatePagerAdapter comes from the fact that it will save out your fragment's Bundle from savedInstanceState when it is destroyed.When the user navigates back,the new fragment will be restored using the fragment's state.
FragmentPagerAdapter:
  • By comparision FragmentPagerAdapter does nothing of the kind.When the fragment is no longer needed.FragmentPagerAdapter calls detach(Fragment) on the transaction instead of remove(Fragment).
  • This destroy's the fragment's view but leaves the fragment's instance alive in the FragmentManager.so the fragments created in the FragmentPagerAdapter are never destroyed.

Tuesday, 25 April 2017

OOPS Concept

Abstraction


abstraction is a process of hiding the implementation details from the user, only the functionality will be provided to the user. In other words, the user will have the information on what the object does instead of how it does it.

Abstract Class

A class which contains the abstract keyword in its declaration is known as abstract class.
  • Abstract classes may or may not contain abstract methods, i.e., methods without body ( public void get(); )
  • But, if a class has at least one abstract method, then the class must be declared abstract.
  • If a class is declared abstract, it cannot be instantiated.
  • To use an abstract class, you have to inherit it from another class, provide implementations to the abstract methods in it.
  • If you inherit an abstract class, you have to provide implementations to all the abstract methods in it.

Abstract Methods

If you want a class to contain a particular method but you want the actual implementation of that method to be determined by child classes, you can declare the method in the parent class as an abstract.
  • abstract keyword is used to declare the method as abstract.
  • You have to place the abstract keyword before the method name in the method declaration.
  • An abstract method contains a method signature, but no method body.
  • Instead of curly braces, an abstract method will have a semoi colon (;) at the end.
                                           
                                                inheritance

Inheritance allows a Child class to inherit properties from its parent class. In Java this is achieved by using extends keyword. Only properties with access modifier public and protected can be accessed in child class.

What is multiple inheritance and does java support?
Ans) If a child class inherits the property from multiple classes is known as multiple inheritance. Java does not allow to extend multiple classes. The problem with with multiple inheritance is that if multiple parent classes have a same method name, then at runtime it becomes diffcult for the compiler to decide which method to execute from the child class. To overcome this problem it allows to implement multiple Interfaces. The problem is commonly referred as What is Diamond Problem.

                                              Encapsulation
Binding (or wrapping) code and data together into a single unit is known as encapsulation. For example: capsule, it is wrapped with different medicines.
In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class.

The encapsulation is achieved by combining the methods and attribute into a class. The class acts like a container encapsulating the properties. The users are exposed mainly public methods.The idea behind is to hide how thinigs work and just exposing the requests a user can do.Encapsulation is used for access restriction to a class members and methods.
Access modifier keywords are used for encapsulation in object oriented programming. For example, encapsulation in java is achieved using privateprotected and public keywords.
                                        

                           Polymorphism

When one task is performed by different ways i.e. known as polymorphism. For example: to convince the customer differently, to draw something e.g. shape or rectangle etc.
In java, we use method overloading and method overriding to achieve polymorphism.
Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.

Mehtod overriding: Overriding occurs when a class method has the same name and signature as a method in parent class. When you override methods, JVM determines the proper method to call at the program’s run time, not at the compile time.
Overloading: Overloading is determined at the compile time. It occurs when several methods have same names with:
  • Different method signature and different number or type of parameters.
  • Same method signature but different number of parameters.
  • Same method signature and same number of parameters but of different type
Example of Overloading
int add(int a,int b)
 float add(float a,int b)
 float add(int a ,float b)
 void add(float a)
 int add(int a)
 void add(int a) //error conflict with the  method int add(int a)
class BookDetails {
  String title;
  setBook(String title){}
}
class ScienceBook extends BookDetails {
  setBook(String title){} //overriding
  setBook(String title, String publisher,float price){} //overloading
}

Friday, 16 December 2016

Code Standand

  • Bad coding
  • Not following standard
  • Not keeping performance in mind
  • History, Indentation, Comments are not appropriate.
  • Readability is poor
  • Open files are not closed
  • Allocated memory has not been released
  • Too many global variables.
  • Too much hard coding.
  • Poor error handling.
  • No modularity.
  • Repeated code.