Saturday, 14 January 2017

Recyclerview with checkbox android example | checkbox in recyclerview android

Checkbox in Recyclerview Android | Recyclerview with checkbox android

Hello warriors..how are you guys ?? I hope you all are doing something great..So i m back after a long time with a cool and very helpful topic of internet Recyclerview with checkbox android. few month ago i was working on a project and i faced a very weird problem in recyclerview with checkbox ,checkbox unchecked when i scroll recyclerview and i know a lot of developer facing this problem at initial stage so in this post i am going to share with you solution of this problem.


I hope all of you know how to create Recyclerview with checkbox in android i am going to discuss only about android recyclerview checkbox scroll problem for this i have created a simple recyclerview with checkbox with 500 item.

So here is my activity_main.xml :-

here is my MainActivity.java :-

Finally here is my adapter class :-


To solve this problem you need to do follow three steps:
  • Create a HashMap in your adapter class of <Integer,Boolean> type.
  • Update HashMap inside checkChangeListener of Checkbox inside your ViewHolder.
  • Check whether checkbox is already checked or not inside onBindViewHolder.

All these steps are included in my adapter class. i hope this post will help you to solve android recyclerview  checkbox scroll problem if this is helpful for you don't forget to give your feedback in comment.you can download complete code from below download button.

https://codeload.github.com/kundansviet/Recyclerview-with-checkbox/zip/master


Friday, 24 June 2016

Android Image loading using Library Universal Image loader (UIL) | Image loading from Internet

Hello guys in this post i am going to share with you best library for image loading in android called Universal Image Loader , a lot libraries are available like Picasso,glide..for image loading from internet and SD card but I always prefer to use universal image loader.


So in this post i will make a Recyclerview of images and all images will be downloaded from  internet for that i will use ten static image url to download image and will show it in Recyclerview.

Like every post i will make module of steps and then we will follow that to complete this tutorial.

  1. Create a new project in your Android Studio. Go to File>>New>>New project.
  2. Add Universal Image Loader library and Recyclerview to build.gradle of app module.
  3. Add Internet permission in manifest file.
  4. Initialize Universal Image Loader inside MainActivity.
  5. Add Recyclerview in your activity_main.xml file.
  6. Create single row ui for your recyclerview.
  7. Create Adapter for Recyclerview if you are not familiar with recyclerview than must follow my post of Recyclerview.
  8. Set image into image of Recyclerview using Universal image loader.
  9.  Set Layout manager and adapter to Recyclerview inside MainActivity.

1.Open your android studio and create a new project. Go to File>>New>>New project like below image.



2.Open build.gradle file of app module and add two dependency to it one for Universal Image Loader and another for Recyclerview in simple way just copy and paste these two dependency.


compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
    compile 'com.android.support:recyclerview-v7:24.0.0'

3.Since app will download image from internet so we need to add permission in manifest file here is manifest file.

4. To use Universal Image Loader in application we need to initialize it in our MainActivity so here is the code to Initialize Universal Image Loader in MainActivity. copy and paste below code in onCreate() of MainActivity.


1
2
 ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this).build();
        ImageLoader.getInstance().init(config);


5.Since we are listing all image in Recyclerview so we need to add Recyclerview in our activity_main.xmkl file here is my activity_main.xml.

6.Create single row of Recyclerview ,since we are going to show only image so its very simple layout here is my single_row.xml.
7.Create Adapter for Recyclerview if you are not familiar with recyclerview than must follow my post of Recyclerview. So I am listing some steps follow these to complete your adapter class.

  • Create a java class name it anything in my case this is ListAdapter
  • Create another class inside ListAdapter class name it ListHolder.
  • extends RecyclerView.Adapter<ListAdapter.ListHolder> to ListAdapter where Adapter is of ListHolder type.
  • Implement all method of Recyclerview.Adapter .
  • Create a Constructor wtih single parameter of Context type.
  • Create four instance, one for Context,one for ImageLoader,one for DisplayImageOptions and one for LayoutInflater like below code.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
    private ImageLoader imageLoader;
    private DisplayImageOptions options;
    private LayoutInflater inflater;
    private Context context;
    String[] images = {"https://2.bp.blogspot.com/-qdVGBrZpNEo/Vzs7Dyba8eI/AAAAAAAANXg/oQGukisNydIcTA733Q8qNX1xryCNrP1-gCLcB/s640/AndroidNotification.png",
            "https://2.bp.blogspot.com/-MtTDhb_9QGw/Vr9OXfE0hqI/AAAAAAAAMZo/e9Advd4xPmY/s1600/Googleplus.png",
            "http://3.bp.blogspot.com/-hEsy8I3DVrA/ViFFalr14kI/AAAAAAAAL74/nfZd4behDE0/s1600/material-tabs.png",
            "https://4.bp.blogspot.com/-fzCN1en9BXY/VslDs985vvI/AAAAAAAAMbU/JycBEflEJcI/s1600/sqlitedemo.png",
            "https://3.bp.blogspot.com/-0CvhPeUCDes/VtGVTINSNhI/AAAAAAAAMc8/CzGr-nlqgS8/s1600/FacebookIntegration.png",
            "http://2.bp.blogspot.com/-DpC34QctSsI/Vh6JZjWY-0I/AAAAAAAAL5c/-UgJEDKYays/s1600/pushNotification.png",
            "http://4.bp.blogspot.com/-8u_hqbGb30g/VjR9WflhCNI/AAAAAAAAMFs/namqhGH1AE0/s1600/material_mcs1_original.png",
            "http://1.bp.blogspot.com/-5nkpiqWiPkg/Vj9jWk0IyiI/AAAAAAAAMIQ/uEBdjXr3jCY/s1600/TwitterloginAndroid.png",
            "http://3.bp.blogspot.com/-oY46UYNjKFk/Vike7jlX05I/AAAAAAAAMBA/OjeJp6BAio8/s640/studio-hero.jpg",
            "http://4.bp.blogspot.com/-UgboLypyx9s/Vq5LeA35rbI/AAAAAAAAMXs/4fGJQPURYwg/s1600/seekbarinandroid.png"};
in above code i have also created an array of static image urls.
  • Now inside inside constructor initialize all instances created above.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
 public ListAdapter(Context context) {

        this.context=context;
        inflater=LayoutInflater.from(context);

        imageLoader = ImageLoader.getInstance();

        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.place_holder)
                .showImageForEmptyUri(R.drawable.place_holder)
                .showImageOnFail(R.drawable.place_holder)
                .cacheInMemory(true)
                .cacheOnDisk(true)
                .considerExifParams(true)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .build();


    }
  • Inside onCreateViewHolder inflate single_row.xml and return ViewHolder object like below code.

1
2
3
4
5
6
7
 @Override
    public ListHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view=inflater.inflate(R.layout.single_row,parent,false);
        ListHolder holder=new ListHolder(view);
        return holder;
    }

  • Now inside ListHolder class Create instance of ImageView and initialize it inside Constructor of ListHolder class like below code.

1
2
3
4
5
6
7
 class ListHolder extends RecyclerView.ViewHolder {
        ImageView imageView;
        public ListHolder(View itemView) {
            super(itemView);
            imageView = (ImageView) itemView.findViewById(R.id.image);
        }
    }

  • In this step set image to ImageView using Universal Image Loader and also set size of list in getItemCount method.

1
2
3
4
5
6
7
8
9
 @Override
    public void onBindViewHolder(ListHolder holder, int position) {
        imageLoader.displayImage(images[position], holder.imageView, options);
    }

    @Override
    public int getItemCount() {
        return images.length;
    }

in above code you can see imageLoder is used to set image in ImageView. and we completed code for Adapter class here is my complete code of ListAdapter class.

7.Now this is our last step very simple initialize and Rycylerview inside MainActivity and set LayoutManager and Adapter to it. here is my MainActivity.java

we have complete this tutorial , still having any problem feel free to comment and don't forget to give your feedback because it always motivate us to write new things , you can download complete code from below download button. in our next post we are going to show how to set image in to list from sdcard using Universal Image Loader so keep visiting.

https://codeload.github.com/kundansviet/Image-Loading-in-List-Using-Universal-Image-Loader/zip/master

Saturday, 18 June 2016

Android Broadcastreceiver Tutorial | Broadcastreceiver in Android Example

Hey warriors whats going on guys , In this post I am going to share with you very cool functionality of android system called BroadcastReceiver in android. A broadcast receiver (short receiver) is an Android component which allows you to register for system or application events. All registered receivers for an event are notified by the Android runtime once this event happens. so without making more gossips I am going to start with coding.


I am going to create a sample for location broadcast ,it will generate a notification when user will turn on/off  GPS. you can check list of all system Broadcast here .So I am going to make module of steps to complete this tutorial.

  • Create new project in your Android studio. Go to File>>New>>New project
  • Add Broadcast Receiver to your manifest file.
  • Create Receiver class to receive your Broadcast.
  • Generate notification in onReceive of Receiver class you can do anything else. 
1.Create new project in your android studio Go to File>>New>>New project like below image.



2.Add Broadcast Receiver to your manifest file. Since I am making Broadcast for location so i am adding Intent filter for location. add below code to your manifest file inside application tag.

1
2
3
4
5
 <receiver android:name=".MyReciever">
            <intent-filter>
                <action android:name="android.location.PROVIDERS_CHANGED" />
            </intent-filter>
        </receiver>
In above code .MyReciver is java class i have created to listen broadcast. here is my manifest file.

3.Create a new java class to receive broadcast I am creating this class MyReciever and extend BroadcastReceiver class then it will ask you to implement method onReceive(). like below code.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
public class MyReciever extends BroadcastReceiver {

    
    @Override
    public void onReceive(Context context, Intent intent) {
       
    }

  

}

4. Inside onReceive() I am using code to check gps is on or off because broadcast only notify that location provider is changed so you to write code to check gps is on or off then generate notification. If you don't know How to create notification in android then check my tutorial notification in android. Here is my complete code of MyRciever class.

Finally we have completed this tutorial you can download complete demo code from below download button. Turn on/off you your gps and you will receive notification.if this post was helpful for your don't forget to comment below because its always motivate us to write new things.

https://codeload.github.com/kundansviet/BroadcastReceiverDemo/zip/master

Friday, 20 May 2016

Android Notification Example | Android notification tutorial

Hey warriors whats going on guys , hope you all are doing great in android since in all previous post we were focusing on advance topics of android but Now I have decided to complete all basic tutorial for beginners. So in this post I am going to teach you how to create simple as well as advance Notification in android ,Notification is beauty of android app ,think your app is not running in foreground and you want to notify your user for any reason what will you do ?? of course you will use notification man.


 According to android developer page
 "A notification is a message you can display to the user outside of your application's normal UI. When you tell the system to issue a notification, it first appears as an icon in the notification area. To see the details of the notification, the user opens the notification drawer. Both the notification area and the notification drawer are system-controlled areas that the user can view at any time" .

So lets start with coding , like every post i will make module of steps and we will follow them to complete this tutorial.

  • Create a New project in Android studio File>>New>>New project.
  • Add three button in to activity_main.xml.
  • Initialize all three button and an Instance of NotificationManager   in MainActivity.java.
  • Create method for all three type of notification.
  • Call each notification on different button click.

1. Create a New project in Android studio Go to File>>New>>New project like below picture.


2.Open your activity_main.xml and add three button for open all three type of notification. here is my activity_main.xml.

3.Initialize all three button and an Instance of  NotificationManager   in MainActivity.java. Notification manager take instance of Notification builder and launch notification, here is my code to initialize all button and notification manager. I am also adding clcikListener to all three button so it will ask you to implement onClickListener so implement in MainActivity.java .

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
public class MainActivity extends AppCompatActivity implements View.OnClickListener {


    Button btn_not_simple, btn_not_expand, btn_not_btn;
    private  NotificationManager mNotificationManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mNotificationManager=(NotificationManager) this.getApplicationContext().getSystemService(this.NOTIFICATION_SERVICE);
        btn_not_simple= (Button) findViewById(R.id.btn_not_simple);
        btn_not_expand= (Button) findViewById(R.id.btn_not_expand);
        btn_not_btn= (Button) findViewById(R.id.btn_not_btn);

        btn_not_simple.setOnClickListener(this);
        btn_not_expand.setOnClickListener(this);
        btn_not_btn.setOnClickListener(this);

    }


4.Create method to generate notification, Since i will post code for all three type but i will discuss only one type of notification in detail. I am going to discuss How to create simple notification in Android, So here is my method createSimpleNotification().

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
 void simpleNotification(){

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

 // Creating a artifical activity stack for the notification activity
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        // Adds the back stack for the Intent (but not the Intent itself)
        stackBuilder.addParentStack(MainActivity.class);
    // Adds the Intent that starts the Activity to the top of the stack
        stackBuilder.addNextIntent(resultIntent);

        // Pending intent to the notification manager
        PendingIntent resultPending = stackBuilder
                .getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

        // Building the notification
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher) // notification icon
                .setContentTitle("I'm a simple notification") // main title of the notification
                .setContentText("I'm the text of the simple notification") // notification text
                .setContentIntent(resultPending); // notification intent

        // mId allows you to update the notification later on.
        mNotificationManager.notify(10, mBuilder.build());
    }


In above method you can see first of all i have created a intent instance , this intent will be used when you will click on notification then intent will call MainActivity.java class, you can call any activity according to need.

Next i am creating instance of TaskStackBuilder , By using TaskStackBuilder I am Creating a artifical activity stack for the notification activity The stack builder object will contain an artificial back stack for thestarted Activity.This ensures that navigating backward from the Activity leads out of your application to the Home screen.

Next i am creating Pending intent using stack builder.After that using NotificationCompat i am creating notification using following methods:
  • setSmallIcon(): used to set icon of notification
  • setContentTitle(): used to set Title of notification
  • setContentText(): used to set actual text of notification
  • setContentIntent(): used to add pending intent to notification.

After all this using Notification manager launch notification.

So as discussed above i am not going to explain each type of notification but i have included all type in code, here is my MainActivity.java


you can download sample code from below button.if this post was helpful for you don't forget to give your feedback in comment because its motivate me to write new post.


https://codeload.github.com/kundansviet/NotificationMaster/zip/master

Monday, 16 May 2016

Runtime permissions android m example | Runtime permission in android marshmallow

Helllllooooooooo warriors finally after a long time I am back with very important topic necessary for every android application called Run-time permission in Marshmallow. As we know that Google changed permission management in Marshmallow. So if you want your app in Marshmallow you need to handle all permission at run-time. I will not write more talking stuff so Lets start.



In this post i am going to make a sample app to capture image from camera and set in Imageview. for that we need camera permission and I am going handle that permission at run-time. So like every post I will make a module of steps and then we will follow that to implement.

  1. Create a new project in Android studio, File>>New>>New project.
  2. Open Manifest file and add camera permission to it.
  3. Open activity_main.xml and two image to it one for captured image and one for camera click.
  4. Open MainActivity.java and Register both imageview and add setOnClickListener to camera click imageview.
  5. Create a method to check permission for camera.
  6. Implement ActivityCompat.OnRequestPermissionsResultCallback in MainActivity.
  7. Override onRequestPermissionResult() method.
  8. Create method to launch camera.
  9. Override onActivityResult() method to get image from camera and set it to imageview.
  10. Inside onClick of camera imageview call  checkCameraPermission() method ,if permission is granted then launch camera else call  requestCameraPermission() method to open permission dialog.
  11. Inside onRequestPermissionResult() check permission, if it is granted then launch camera else show a Toast.
Now we will follow each stop listed above to complete this tutorial.

1.Create a new project in Android studio, File>>New>>New project  like below image.


 2.Open Manifest file and add camera permission to it ,simply open your manifest file and add below code inside application tag.


        <uses-permission android:name="android.permission.CAMERA" />

like below image.


3.Open activity_main.xml and two image to it one for captured image and one for camera click. here is my activity_main.xml.

4.Open MainActivity.java and Register both imageview and add setOnClickListener to camera click imageview, like below code.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
 private ImageView iv_camera, iv_pic;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        iv_pic = (ImageView) findViewById(R.id.iv_pic);

        iv_camera = (ImageView) findViewById(R.id.iv_camera);

        iv_camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                
            }
        });

    }


5.Create a method to check permission for camera like below code .

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
 /**
     * Method to check permission
     */
    void checkCameraPermission() {
        boolean isGranted;
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            // Camera permission has not been granted.

            requestCameraPermission();


        } else {

            takePicture();

        }
    }

In above code takePicture() method is for launching camera using intent and code is here.

1
2
3
4
5
6
7
/**
     * Method to launch camera after permission accepted from user
     */
    void takePicture() {
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        startActivityForResult(intent, 0);
    }

6.Implement ActivityCompat.OnRequestPermissionsResultCallback in MainActivity like below code.
1
public class MainActivity extends AppCompatActivity implements ActivityCompat.OnRequestPermissionsResultCallback 

7.Override onRequestPermissionResult() method.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
 @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_CAMERA) {
            // BEGIN_INCLUDE(permission_result)
            // Received permission result for camera permission.
            Log.i(TAG, "Received response for Camera permission request.");

            // Check if the only required permission has been granted
            if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // Camera permission has been granted, preview can be displayed

                takePicture();

            } else {
              //Permission not granted
                Toast.makeText(MainActivity.this,"You need to grant camera permission to use camera",Toast.LENGTH_LONG).show();
            }

        }
    }

in above method I am checking for request used at time of requesting permission , if code match and permission is granted then call takePicture() method to launch camera else show a message using toast.

8.Override onActivityResult() method to get image from camera and set it to imageview like below code.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {


        if (resultCode == Activity.RESULT_OK && requestCode == 0) {

            //this is your bitmap image and now you can do whatever you want with this

            Bitmap picture = (Bitmap) data.getExtras().get("data");

            iv_pic.setImageBitmap(picture);


        }
    }

in above method i am taking image as bitmap and setting it to imageview.

Now here is my complete MainActivity.java class.
you can download sample app from below download button.

https://codeload.github.com/kundansviet/Runtime-permission-in-Marshmallow/zip/master

Still Having any problem feel free to comment below.