Tuesday, 19 September 2017

RecyclerView with multiple View Type | RecyclerView with different view types | View Pager inside RecyclerView

Hello Friends,
              Today I am going to share my another android tutorial, with the help
of this we can easily create a Recyclerview with multiple different types
of view .
Also this tutorial helps you to create a View pager inside RecyclerView,


























1. MainActivity.java :

package com.developer.solutions.recyclerviewwithmultipleviewtype.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Binder;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.widget.TextView;

import com.developer.solutions.recyclerviewwithmultipleviewtype.R;
import com.developer.solutions.recyclerviewwithmultipleviewtype.adapter.MultiViewTypeAdapter;
import com.developer.solutions.recyclerviewwithmultipleviewtype.model.Data;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by Mukesh on 3/8/17.
 * himky02@gmail.com
 */
public class MainActivity extends AppCompatActivity {

    Activity mActivity;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.rv)
    RecyclerView mRecyclerView;
    Unbinder mUnbinder;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //((TextView) findViewById(R.id.tv)).setText("Welcome user");
        mUnbinder = ButterKnife.bind(this);

        ArrayList list = new ArrayList<>();
        list.add(new Data(Data.VIEW_PAGER, "Hello. This is the View Pager view type with images", 0));
        list.add(new Data(Data.IMAGE_TYPE, "A view type with Image and Textview", R.drawable.disneys_cinderella));
        list.add(new Data(Data.AUDIO_TYPE, "Hey, A view type with Button and Textview", 0));
        list.add(new Data(Data.IMAGE_TYPE, "Hi again. A view with Image and Textview", R.drawable.snow));

        MultiViewTypeAdapter adapter = new MultiViewTypeAdapter(list, this);
        final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setAdapter(adapter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
         if (mUnbinder != null) mUnbinder.unbind();
    }
}


2.MultiViewTypeAdapter.java
package com.developer.solutions.recyclerviewwithmultipleviewtype.adapter;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.developer.solutions.recyclerviewwithmultipleviewtype.R;
import com.developer.solutions.recyclerviewwithmultipleviewtype.model.Data;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Mukesh on 3/8/17.
 * himky02@gmail.com
 */
public class MultiViewTypeAdapter extends RecyclerView.Adapter {
    private ArrayList dataSet;
    Context mContext;
    int total_types;
    ArrayList slider_image_list;
    int page = 0;

    public static class TextTypeViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.ll_dots)
        LinearLayout ll_dots;
        @BindView(R.id.vp_slider)
        ViewPager mvViewPager;

        public TextTypeViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    public static class ImageTypeViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.type)
        TextView tvtype;
        @BindView(R.id.img)
        ImageView iv;

        public ImageTypeViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    public static class ButtonTypeViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.type)
        TextView type;
        @BindView(R.id.btn)
        Button btn;

        public ButtonTypeViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    public MultiViewTypeAdapter(ArrayList data, Context context) {
        this.dataSet = data;
        this.mContext = context;
        total_types = dataSet.size();
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view;
        switch (viewType) {
            case Data.VIEW_PAGER:
                view = LayoutInflater.from(parent.getContext()).inflate(R.layout.viewpager, parent, false);
                return new TextTypeViewHolder(view);
            case Data.IMAGE_TYPE:
                view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_image_type, parent, false);
                return new ImageTypeViewHolder(view);
            case Data.AUDIO_TYPE:
                view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_button_type, parent, false);
                return new ButtonTypeViewHolder(view);
        }
        return null;


    }


    @Override
    public int getItemViewType(int position) {

        switch (dataSet.get(position).type) {
            case 0:
                return Data.VIEW_PAGER;
            case 1:
                return Data.IMAGE_TYPE;
            case 2:
                return Data.AUDIO_TYPE;
            default:
                return -1;
        }
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int listPosition) {

        Data object = dataSet.get(listPosition);
        if (object != null) {
            switch (object.type) {
                case Data.VIEW_PAGER:
                    //((TextTypeViewHolder) holder).type.setText(object.text);
                    slider_image_list = new ArrayList<>();

                    //Add few items to slider_image_list ,this should contain url of images which should be displayed in slider
                    // here i am adding few sample image links, you can add your own

                    slider_image_list.add("http://cdn.collider.com/wp-content/uploads/avengers-movie-banner-scarlett-johansson-jeremy-renner.jpg");
                    slider_image_list.add("http://www.officialterridwyer.com/wp-content/uploads/2015/04/Disneys-Cinderella-2015-Movie-Banner.jpg");
                    slider_image_list.add("http://igmedia.blob.core.windows.net/igmedia/hindi/gallery/movies/raabta/main1.jpg");
                    slider_image_list.add("http://fantoosy.com/wp-content/uploads/2015/11/tamasha.jpg");
                    final SliderPagerAdapter sliderPagerAdapter = new SliderPagerAdapter((Activity) mContext, slider_image_list);
                    ((TextTypeViewHolder) holder).mvViewPager.setAdapter(sliderPagerAdapter);

                    ((TextTypeViewHolder) holder).mvViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                        @Override
                        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                        }

                        @Override
                        public void onPageSelected(int position) {
                            addBottomDots(position, ((TextTypeViewHolder) holder).ll_dots);
                            page = position;
                        }

                        @Override
                        public void onPageScrollStateChanged(int state) {

                        }
                    });
                    addBottomDots(0, ((TextTypeViewHolder) holder).ll_dots);
                    final Handler h = new Handler();
                    h.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if (sliderPagerAdapter.getCount() == page) {
                                page = 0;
                            } else {
                                page++;
                            }
                            ((TextTypeViewHolder) holder).mvViewPager.setCurrentItem(page);
                            h.postDelayed(this, 2000);
                        }
                    }, 1000);

                    break;
                case Data.IMAGE_TYPE:
                    ((ImageTypeViewHolder) holder).tvtype.setText(object.text);
                    ((ImageTypeViewHolder) holder).iv.setImageResource(object.data);
                    break;
                case Data.AUDIO_TYPE:
                    ((ButtonTypeViewHolder) holder).type.setText(object.text);
                    ((ButtonTypeViewHolder) holder).btn.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Toast.makeText(mContext, "You clicked!!!", Toast.LENGTH_SHORT).show();
                        }
                    });
                    break;
            }
        }

    }

    @Override
    public int getItemCount() {
        return dataSet.size();
    }

    //showing dots on screen
    private void addBottomDots(int currentPage, LinearLayout ll_dots) {
        TextView[] dots = new TextView[slider_image_list.size()];
        ll_dots.removeAllViews();
        for (int i = 0; i < dots.length; i++) {
            dots[i] = new TextView(mContext);
            dots[i].setText(Html.fromHtml("•"));
            dots[i].setTextSize(35);
            dots[i].setTextColor(Color.parseColor("#343434"));
            ll_dots.addView(dots[i]);
        }

        if (dots.length > 0)
            dots[currentPage].setTextColor(Color.parseColor("#A2A2A2"));
    }

}
Download the code from here

Hope this will helps some one.
Enjoy Coding....

Saturday, 27 May 2017

Android Retrofit With RX Java Sample | Android Retrofit Example

Hello Friends,

This is an simple example of How we use Android Retrofit With RX .  I hope this
will helps you to start using Retrofit and  RX together.



1. MainActivity.java

package android.com.retrofitwithrxsample;

import android.com.retrofitwithrxsample.adapter.DataAdapter;
import android.com.retrofitwithrxsample.model.Country;
import android.com.retrofitwithrxsample.model.Result;
import android.com.retrofitwithrxsample.network.RequestInterface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;

import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

import java.util.ArrayList;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import com.newrelic.agent.android.NewRelic;

/**
 * Create by: Mukesh Yadav
 * www.androiddevelopersolutions.com
 */
public class MainActivity extends AppCompatActivity {

    private static String BASE_URL =  "http://services.groupkt.com/";
    private RecyclerView mRecyclerView;

    private CompositeDisposable mCompositeDisposable;

    private DataAdapter mAdapter;

    private ArrayList mAndroidArrayList;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mCompositeDisposable = new CompositeDisposable();
        initRecyclerView();
        loadJSON();
    }

    private void initRecyclerView() {

        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        mRecyclerView.setHasFixedSize(true);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
        mRecyclerView.setLayoutManager(layoutManager);
    }

    private void loadJSON() {
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        // set your desired log level
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
        // add your other interceptors …
        httpClient.addInterceptor(logging);  
        RequestInterface requestInterface = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .client(httpClient.build())
                .build().create(RequestInterface.class);           
        mCompositeDisposable.add(requestInterface.getAllCountry()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(this::handleResponse,this::handleError));   
    }

    private void handleResponse(Country response) {
        if(response != null &&
                response.getRestResponse() != null &&
                response.getRestResponse().getResult() != null &&
                response.getRestResponse().getResult().size() >0) {
            mAndroidArrayList = (ArrayList) response.getRestResponse().getResult();
            mAdapter = new DataAdapter(mAndroidArrayList);
            mRecyclerView.setAdapter(mAdapter);
        }
    }

    private void handleError(Throwable error) {

        Toast.makeText(this, "Error "+error.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mCompositeDisposable.clear();
    }
}



You can Download the comple code From here: RetrofitWithRxSample

Hope this will helps you.
Enjoy Coding...... :)

Saturday, 22 October 2016

Mobile World : Pixel Phone By Google | Google Pixel

Hello Friends,

Google Pixel smartphone was launched in October 2016 which comes with a 5.00-inch touchscreen display and a resolution of 1080 pixels by 1920 pixels at a PPI of 441 pixels per inch.

The Google Pixel is powered by 1.6GHz quad-core Qualcomm Snapdragon 821 processor and it comes with 4GB of RAM. The phone packs 32GB of internal storage cannot be expanded. As far as the cameras are concerned, the Google Pixel packs a 12.3-megapixel primary camera on the rear and a 8-megapixel front shooter for selfies.

The Google Pixel runs Android 7.1(Nougat) and is powered by a 2770mAh non removable battery. It measures 143.80 x 69.50 x 8.60 (height x width x thickness) and weighs 143.00 grams.

The Google Pixel is a single SIM (GSM) smartphone that accepts a Nano-SIM. Connectivity options include Wi-Fi, GPS, Bluetooth, NFC, 4G (with support for Band 40 used by some LTE networks in India). Sensors on the phone include Proximity sensor, Ambient light sensor, Accelerometer, and Gyroscope.

The Google Pixel smartphones come in three colors with rather descriptive names - Quite Black, Very Silver, and the limited edition Really Blue.





Google Pixel detailed specifications

GENERAL
Release date October 2016
Form factor Touchscreen
Dimensions (mm) 143.80 x 69.50 x 8.60
Weight (g) 143.00
Battery capacity (mAh) 2770
Removable battery No
Colours Very Silver, Quite Black, Really Blue
SAR value NA

DISPLAY
Screen size (inches) 5.00
Touchscreen Yes
Resolution 1080x1920 pixels
Pixels per inch (PPI)  441

HARDWARE
Processor 1.6GHz  quad-core
Processor make Qualcomm Snapdragon 821
RAM 4GB
Internal storage 32GB

CONNECTIVITY
Wi-Fi Yes
Wi-Fi standards supported 802.11 a/ b/ g/ n/ ac
GPS Yes
Bluetooth Yes, v 4.20
NFC Yes
Infrared No
USB OTG No
Headphones 3.5mm
FM No
SIM Type Nano-SIM
GSM/ CDMA GSM
3G Yes
4G/ LTE Yes
Supports 4G in India (Band 40) Yes

SOFTWARE
Operating System  Android 7.1

CAMERA
Rear camera 12.3-megapixel
Flash Yes
Front camera 8-megapixel

SENSOR
Compass/ Magnetometer Yes
Proximity sensor Yes
Accelerometer Yes
Ambient light sensor Yes
Gyroscope Yes
Barometer Yes
Temperature sensor No


Keep In touch for latest mobile world related updates.

Enjoy :)

Thursday, 15 September 2016

Android black screen before splash appear | Black screen on app start | How to avoid black screen in android while app is loading?


Hello Friends,
          Have you facing the delay issue on app launch and black/white
screen will be appearingfor few seconds. Here is the solution of this
issue.

1. Inside styles.xml add below style:
     
     <style name="Theme.AppCompat.Light.NoActionBar.FullScreen"
    parent="@android:style/Theme.Black.NoTitleBar">
   <item name="windowNoTitle">true</item>
   <item name="windowActionBar">false</item>
   <item name="android:windowFullscreen">true</item>
   <item name="android:windowContentOverlay">@null</item>
   <item name="android:windowIsTranslucent">true</item>
</style>

2. Inside your AndroidManiest.xml file add above style to your  Splash Activity:
    <activity
    android:configchanges="orientation|
    keyboardHidden|screenSize"
    android:label="@string/app_name"
    android:name=".SplashScreenActivity"
    android:screenorientation="portrait"
    android:theme="@style/Theme.AppCompat.Light.NoActionBar.FullScreen">
       <intent-filter>
        <action android:name="android.intent.action.MAIN">
            <category android:name="android.intent.category.LAUNCHER">
            </category></action></intent-filter>
 </activity>


Hope, this will helps someone.
Enjoy Coding... Cheers.. :)



Wednesday, 22 June 2016

App crashed on launch | Android Studio App crashed on launch | App crashed on launch- Android 4.4

Hello friends,

Today I found the strange issue while making an signed/released Apk.

My app getting crashed when app launched on Android 4.4, 4.2 and other devices
and Its working fine with Debug build. After spending lots of time I found that the
issue is with Android studio 2.0 or higher.

The reason of crash is in Android studio 2.0 and higher Google added a new feature
of Instant Run which makes your development/emulation faster.The Instant run is
enabled in latest android studio. We need to make it disable while making a signed
release build.

Steps to Disable:
1. Open the Settings or Preferences dialog: On Windows or Linux, select File > Settings
    from the main menu. On Mac OSX, select Android Studio > Preferences from
    the main menu.
2. Navigate to Build, Execution, Deployment > Instant Run.
3  Unchecked the box next to Enable Instant Run to hoot swap code/resource
    changes on display. 



What is Instant Run??
Instant Run: This feature is supposed to dramatically improve your workflow by letting you quickly see changes running on your device or emulator. It lets you see your changes running “in a near instant,” which means you can continuously code and run your app, hopefully accelerating your edit, build, run cycles. When you click on the Instant Run button, it will analyze the changes you have made and determine how it can deploy your new code in the fastest way. Instant Run works with any Android Device or emulator running API 14 (Ice Cream Sandwich) or higher.


Hope this will help someone.
Enjoy Coding.... :)

Saturday, 20 February 2016

Unity | Unity Read SMS Plugin | Unity Pluging : Read all incoming sms


Hello Friends,
              I read a lot that people facing problem in register and un-register the incoming
sms broadcast from Unity. Also reading incoming sms in Unity app .

     

              So, today I am going to share my first blog on Unity. This post helps you
to read all android incoming sms in your unity app.  Also you can easily register
and un-register the broadcast base on need.

In this tutorial I am going provide you a Unity Plugin(i.e:smsreader.jar) which
communicate b/w your unity app and android native callbacks. Below are the
steps to use it in your unity app :


1. Note: The package name which you have to use to access the plugin method is
               com.affle.smsreader

    Permission:  Add below permission inside your unity app manifest.xml file.
         <uses-permission android:name="android.permission.RECEIVE_SMS"/>
         <uses-permission android:name="android.permission.READ_SMS" />



2.  The plugin contains to static method which will be call from unity app :
          A. registerBroadcastReceiver() :  When your unity app launch we first need to
              call this method for registering the broadcast receiver. Below is code snapshot.
              These two methods and class are there in plugin we just need to add that
               plugin as a jar and call it.
            
        /**
  * This method register the Broadcast receiver
  * @param view
  */
 public static void registerBroadcastReceiver() {
    if (broadCastReceiver == null) {
  broadCastReceiver = new IncomingSms();
    }
    UnityPlayer.currentActivity.registerReceiver(broadCastReceiver,
  new IntentFilter("android.provider.Telephony.SMS_RECEIVED"));
 }

          B. unregisterBroadcastReceiver() : Whenever you want to stop reading incoming
               sms call this method or when your unity app goes in background.
 /**
  * This method un-register the Broadcast receiver
  * @param view
  */
 public static void unregisterBroadcastReceiver() {

  if (broadCastReceiver != null) {
   UnityPlayer.currentActivity.unregisterReceiver(broadCastReceiver);
   broadCastReceiver = null;
  }
 }

3. IncomingSms.java:
package com.affle.smsreader;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log;

import com.unity3d.player.UnityPlayer;

public class IncomingSms extends BroadcastReceiver {

 final SmsManager sms = SmsManager.getDefault();

 public void onReceive(Context context, Intent intent) {

  // Retrieves a map of extended data from the intent.
  final Bundle bundle = intent.getExtras();

  try {

   if (bundle != null) {

    final Object[] pdusObj = (Object[]) bundle.get("pdus");

    for (int i = 0; i < pdusObj.length; i++) {

     SmsMessage currentMessage = SmsMessage
       .createFromPdu((byte[]) pdusObj[i]);
     String phoneNumber = currentMessage
       .getDisplayOriginatingAddress();

     String message = currentMessage.getDisplayMessageBody();

     if (UnityPlayer.currentActivity != null) {
      UnityPlayer.UnitySendMessage("TextMessageListner",
        "OnMessageReceived", "" + message);
     }
    } // end for loop
   } // bundle is null

  } catch (Exception e) {
   Log.e("SmsReceiver", "Exception smsReceiver" + e);

  }
 }

}


Download the plugin from here : SmsReader.jar
Hope this will help some one.
Enjoy....
Happy Coding ... :)

Wednesday, 17 February 2016

Android 3 Easy Steps to generate SHA1 and MD5 fingerprint| SHA-1 fingerprint of keystore certificate | Using Android Studio generate SHA-1 fingerprint

Hello Friends,
      Today, I am sharing few easy steps to generate SHA1 and MD5 fingerprint using
android studio.No need of terminal command, we can generate it in Android Studio
same as we did in Eclipse-->window---> preferences--->Android---->Build .

Here Are Steps with screen shot:

Easiest way :
  1. Open Android Studio
  2. Open Your Project
  3. Click on Gradle (From Right Side Panel, you will see Gradle Option)
  4. Click on Refresh (Click on Refresh from Gradle, you will see List Gradle scripts of your Project)
  5. Click on Your Project (Your Project Name form List (root))
  6. Click on Tasks
  7. Click on android
  8. Double Click on signingReport (You will get SHA1 and MD5 in Run Bar)

Screen 1.

Screen 2.



Screen 3.



All Done.


Hope this will help some one.
Enjoy Coding.....
Cheers :)

 

Copyright @ 2013 Android Developer Blog.