Friday 19 August 2016

FireBase Data Storage and Retrival .Real Time Update of Recycler View

Declare FireBase dependencies in Gradle Files and do necessary steps for FireBase Setup.

I'm gonna write only the coding part.

//Declare this in oncreate of your activity
Firebase.setAndroidContext(this);

//Get a FireBase Reference Change URL a/c to your Firebase project(Check it in Firebase console)
Firebase ref = new Firebase("https://birthday-2599.firebaseio.com/");



//Onclick of the button save data to FireBase

Person person = new Person();

String name = nameEd.getText().toString().trim();
String phNo = number.getText().toString().trim();
String dob = tv.getText().toString().trim();
//Adding valuesif(!(name.equals("") || phNo.equals("") || dob.equals(""))) {
    person.setName(name);
    person.setPhNo(Integer.parseInt(phNo));
    person.setDob(dob);
    FirebaseHelper.save(person);
    finish();
}




//Save method

//SAVEpublic static Boolean save(Person person) {
    if (person == null) {
        saved = false;
    } else {

        ref.push().setValue(person);

        saved = true;

    }
    return saved;
}




//Retrive
//Set valuechange event listener and update data in RecyclerView


ref.addValueEventListener(new ValueEventListener() {

    @Override    public void onDataChange(DataSnapshot snapshot) {
//Clear array which your are passing in the adapter
        displayArray.clear();
        for (DataSnapshot postSnapshot : snapshot.getChildren()) {
            //Getting the data from snapshot            Person person = postSnapshot.getValue(Person.class);

            //Adding it to a string            String string = person.toString();


            displayArray.add(string);
            RecyclerView.Adapter adapter = new DataAdapter(displayArray);
            recyclerView.setAdapter(adapter);


        }
    }

    @Override    public void onCancelled(FirebaseError firebaseError) {
        System.out.println("The read failed: " + firebaseError.getMessage());
    }


});


ProjectFiles


Wednesday 13 July 2016

Cannot load modern controls UI. Upgrade to the latest version of the Android YouTube API (FIX)


YouTube Video you have uploaded not playing in app using YouTubeAPI android

One of the reason I found is while uploading video to youtube do not share it private..

If you do you get the warning as cannot load...and video will not be played

Tuesday 5 July 2016

RecyclerView as a Fragment and OnclickListener on the CardViews(ListItems) of the recyclerView

Following is an XML which we inflate in the RecyclerViewFragment


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/cardview_light_background"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"

    android:paddingTop="@dimen/activity_vertical_margin">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/my_recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="vertical" />

</RelativeLayout>



RecyclerView as Fragment




public class RecyclerViewFragment extends Fragment {
    private static final String TAG = "RecyclerViewFragment";


  


    private enum LayoutManagerType {

        LINEAR_LAYOUT_MANAGER    }

    protected LayoutManagerType mCurrentLayoutManagerType;


    protected RecyclerView mRecyclerView;
    protected CustomCardAdapter adapter;
    protected RecyclerView.LayoutManager mLayoutManager;

    //rowIteems is a list in which we shall fill the data which is to be displayed
    private static ArrayList<RowItem> rowItems;


    @Override    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Initialize dataset
        initDataset();
    }

    private void initDataset() {
       //RowItem is a model class which provides data
        rowItems = new ArrayList<RowItem>();
        for (int i = 0; i < titles.length; i++) {
            RowItem item = new RowItem(images[i], titles[i], descriptions[i]);
            rowItems.add(item);
        }
    }


    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_recycler_view, container, false);
        rootView.setTag(TAG);


        mRecyclerView = (RecyclerView) rootView.findViewById(R.id.my_recycler_view);

        // LinearLayoutManager is used here, this will layout the elements in a similar fashion        // to the way ListView would layout elements. The RecyclerView.LayoutManager defines how        // elements are laid out.        mLayoutManager = new LinearLayoutManager(getActivity());

        mCurrentLayoutManagerType = LayoutManagerType.LINEAR_LAYOUT_MANAGER;

        mRecyclerView.setLayoutManager(mLayoutManager);

        adapter = new CustomCardAdapter(rowItems);
        // Set CustomAdapter as the adapter for RecyclerView.        mRecyclerView.setAdapter(adapter);
        mRecyclerView.addOnItemTouchListener(
                new RecyclerItemClickListener(this.getContext(), new RecyclerItemClickListener.OnItemClickListener() {
                    @Override public void onItemClick(View view, int position) {
                        
                       //Do whatever you want onclick works here you can show a toast here





                    }
                })
        );

        return rootView;
    }



    @Override    public void onStop() {
        super.onStop();
        Constants.dismissDialogue();
    }
}





ItemClick listener class of the RecyclerView




package com.example.hp.listview.Activity;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;




public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
    private OnItemClickListener mListener;

    public interface OnItemClickListener {
        public void onItemClick(View view, int position);
    }

    GestureDetector mGestureDetector;

    public RecyclerItemClickListener(Context context, OnItemClickListener listener) {
        mListener = listener;
        mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
            @Override public boolean onSingleTapUp(MotionEvent e) {
                return true;
            }
        });
    }

    @Override public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
        View childView = view.findChildViewUnder(e.getX(), e.getY());
        if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
            mListener.onItemClick(childView, view.getChildPosition(childView));
            return true;
        }
        return false;
    }

    @Override public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) { }

    @Override    public void onRequestDisallowInterceptTouchEvent (boolean disallowIntercept){}
}



Sunday 26 June 2016

  1. Retrofit/Volley :- Networking libraries which ease your task of writing long network requests and related boiler-plate code.
  2. Picasso/Glide :- Loading image into imageview from an url is made very simple using any one of these.
  3. Simple Facebook :- Will relatively ease your burden of implementing facebook social login.
  4. ActiveAndroid/GreenDAO :- Reduces the boilerplate code required for interacting with local Sqlite database.

Volley Vs Retrofit

Volley has flexible caching mechanism whereas Retrofit does not provide support for caching.

Volley support retrying mechanism whereas Retrofit does not provide support for retrying.

Volley is a networking library, developed by Google engineers. 
It was introduced in Google IO 2013, it offers great features like synchronous requests, asynchronous requests, 
prioritization, making multiple requests at the same time, ordered requests and of course caching. But one of the major problems faced by 
developers using this library is that it lacks detailed official documentation. 


On the other hand Retrofit is a clean, simple, and light library for Android by Square, Inc. 
In other words, Retrofit is a REST client for Android, through which you can make easy to use interfaces which can turn 
any Android app into a powerful one. What makes it different is that, Retrofit can perform Async and sync requests with automatic 
JSON parsing without any effort. This feature alone makes it powerful enough to make a contender for this comparison. 


2) In-Built Request Types
The data returned from a web service always complicates the implementation, but thankfully now with help of these libraries almost all types of responses can be captured. Android Volley can capture four types of responses automatically through these requests:

StringRequest – Make this type of request and the returned data is parsed and converted in to a String.
JsonObjectRequest – This type of request converts the response in to a JSONObject.
JsonArrayRequest – Make this type of request and response is automatically converted into a JSONArray.
ImageRequest – This type of request converts the response into a decoded bitmap automatically.
On the other hand Retrofit can parse many other types of responses automatically like:

Boolean – Web API response needs to be a String boolean.
Integer – Web API response needs to be an integer.
Date– Web API response should be Long format date.
String – Web API response needs to be in String format.
Object – Web API response needs to be in Json object.
Collections – Web API response needs to be in a String Format.

Two methods of passing object by Intent (Serializable,Parcelable)
https://www.javacodegeeks.com/2014/01/android-tutorial-two-methods-of-passing-object-by-intent-serializableparcelable.html


Transient variables value will not be saved to file and hence cannot be retrieved in the new object. Similarly static variable values are also not serialized since they belongs to class and not object.


A Service helps you to execute tasks in the background. Like downloading a file or tracking user location changes.
It is an Application Componenet with no user interface. It has a simple life cycle and comes with a set of features.
There are two types of Services
Bound Service  This kind of service is bound to a component like an Activity and runs as long as the Activity runs.
Started Service  This kind of service can run indefinitely. Even when the Activity that started is is destroyed.
You can create a new service by extending either the Service Class or the IntentService Class.

IntentService allows you to create a started service.



One of the major changes in Android Marshmallow is the new permission system. In earlier versions we were declaring the permission in the AndroidManifest.xml file. But with Android Marshmallow we need to ask the permission at run time.  In this post I will show you a simple Android Marshmallow Permissions Example. So lets begin.

Material Design, its a comprehensive guide of UI Widgets introduced since Android 5.0 and it improves the visual appeal of the apps.




Android’s latest release, Lollipop (Android 5.0 API Level 21) includes the new RecyclerView and CardView widgets. They’re also made available for use on devices running API Level 7 and above through the Support Libraries.
The RecyclerView provides a more advanced and flexible way of displaying lists than the old ListView.
The CardView widget enables you to display views inside a card. You can design the card so that its look is consistent across your app.

Displaying Lists

The RecyclerView widget is essentially a container that you can use to display large sets of data. It’s very efficient as it only displays a few items at a time. Views that are no longer needed are recycled and reused. Not having to keep on inflating views saves CPU resources and valuable memory is saved by not having to keep views alive in the background.


Android RecyclerView is a more advanced, powerful and flexible version of the ListView. RecyclerView is similar to ListView when it comes to implementation except the fact that it forces us to use a RecyclerView.ViewHolder class to hold the elements which was not a compulsion in ListView.
As the name suggests, a RecyclerView is used to reuse cells when scrolling up and down by recycling the items in the list. Another improvement in RecyclerView is that it allows us to set the LayoutManagers dynamically at runtime unlike the ListView which was only available in a Vertical scrolling List. RecyclerView allows us to set the following types of Layouts at runtime.
  • LinearLayoutManager : it supports both vertical and horizontal lists
  • StaggeredLayoutManager : it supports staggered lists
  • GridLayoutManager : it supports displaying grids as seen in GalleryView earlier

The RecyclerView.ItemAnimator class provides better support to animating the views unlike the ListViews









  • The RecyclerView.ItemDecorator class provides better support when it comes to adding borders and dividers thereby giving huge control to us
  • Hence a RecyclerView is more customisable when compared to ListView and gives greater control to the users.
    The RecyclerView is available in the support library. So we need to modify our gradle script to add the following dependency.
    1
    2
    3
    dependencies {
           compile 'com.android.support:recyclerview-v7:21.0.0-rc1'
     }


    CardView widget allows us to control the background color, shadow, corner radius, elevation etc. For using the custom attributes in XML, we need to add the following namespace declaration to the parent layout.


    The important attributes used above are:
    • card_view:cardCornerRadius : Used to set the corner radius in our layouts
    • card_view:cardBackgroundColor : Used to set the background color of the view



    Firebase is a cloud service provider. It is now under google and this service can replace your whole server side part of your application. In many tutorials we had used MySQL and PHP for our database. But if we will use Firebase we do not need any server side code or configuration. We can directly use firebase. Firebase comes with a bundle of many features.

    Features of Firebase?

    firebase features




    Thursday 23 June 2016

    NavigationDrawer Fragment overlaps on the mainactivity contentview Android Fix

    Here if we use NavigationDrawer (android.support.v4.widget.DrawerLayout;) items will be the fragments and hence in case if we have a listview in the main activity which should not be shown in case navigation drawer item is selected then we should implement listview of main activity as the FragmentList.


    If so we can replace fragments at runtime very easily



    Layout of the MainActivity will be as follows


    <android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical">
            <include
                android:id="@+id/toolbar"
                layout="@layout/toolbar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
            <FrameLayout
                android:id="@+id/container_body"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

            </FrameLayout>

        </LinearLayout>

        <fragment
            android:id="@+id/fragment_navigation_drawer"
            android:name="com.example.hp.listview.Fragment.FragmentDrawer"
            android:layout_width="@dimen/nav_drawer_width"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            app:layout="@layout/fragment_navigation_drawer"
            tools:layout="@layout/fragment_navigation_drawer" />
    </android.support.v4.widget.DrawerLayout>



    Oncreate of the main activity we attach our FragmentList as follows

    Fragment monthsListFragment = new MyListFragment();
    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
    fragmentTransaction.replace(R.id.container_body,monthsListFragment,null);
    fragmentTransaction.commit();

    Here MyListFragment is the FragmentList which is to be created

    When user selects navigationDrawer item then we replace container body which is a frame layout with the corresponding selected item fragment

    @Overridepublic void onDrawerItemSelected(View view, int position) {
        displayView(position);
    }
        private void displayView(int position) {
            Fragment fragment = null;
            String title = getString(R.string.app_name);
            switch (position) {
                case 0:
                    fragment = new HomeFragment();
                    title = getString(R.string.title_home);
                    break;
                case 1:
                    fragment = new FriendsFragment();
                    title = getString(R.string.title_friends);
                    break;
                case 2:
                    fragment = new MessagesFragment();
                    title = getString(R.string.title_messages);
                    break;
                default:
                    break;
            }
    
            if (fragment != null) {
                FragmentManager fragmentManager = getSupportFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.replace(R.id.container_body, fragment);
                fragmentTransaction.commit();
    
                // set the toolbar title            if(getSupportActionBar()!=null)
                getSupportActionBar().setTitle(title);
            }
    
    }

    Sunday 24 April 2016

    Android Studio Unresolved Dependencies for RecyclerView Drawable - Vector Fix

    This issue occurs because POM.xml corresponding to RecyclerView and Drawable Vector is Null
    Check the following

    C:\Users\Hp\AppData\Local\Android\sdk\extras\android\m2repository\com\android\support\recyclerview-v7\23.3.0\recyclerview-v7-23.3.0.pom

    Fill it with the corresponding data.Check other versions like 21.0.0 and change the version number accordingly.

    Same thing for Drawable Vector also.

    Similar issue can arise for .aar then in that case replace .aar of any other version with the affected version accordingly.




    Monday 11 April 2016

    Android Studio ShortCuts

    ctrl+shift+space  for code completion
    alt+ins for getter and setter
    ctrl+alt+b for navigation
    ctrl+w extend selection
    ctrl+alt+v refactoring
    comment and uncomment ctrl+slash and ctrl+shift+slash

    shift+f1 browser opening
    ctrl+d duplication
     ctrl+space code completion
    ctrl+p valid parameters parenthesis




    ctrl+alt+o optimise imports
    ctrl+shft+n open file
    ctrl+att+l format

    Pass a HashMap from Angular Client to Spring boot API

    This example is for the case where fileData is very huge and in json format   let map = new Map<string, string>()      map.set(this.ge...