Monday, 26 December 2016

Custom Checkbox in Android

 
Custom Checkbox in Android

It's a very common practice to use a checkbox in our app. We all know how it works. Right ??
What if we need a customize the checkbox ? Well, by saying customize a checkbox, I actually mean to set a customize background for the checkbox. Means, if a user click over an unchecked checkbox the checked checkbox should appear as a background instead of the default ticked checbox provided by android. Similar thing should be happened in the later case.

Soon or later you will need to learn this feature in order to implement for your app. So better learn it today itself. So let’s start....

1. Create an xml file (say myselector.xml) and put it inside the drawable folder(you can put it to some other location as well).

Copy and paste this ....to your newly created xml file.

checkbox_selector.xml(My xml file name)

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true"
          android:state_focused="true"
          android:drawable="@drawable/check" />
    <item android:state_checked="false"
          android:state_focused="true"
          android:drawable="@drawable/uncheck" />
    <item android:state_checked="false"
          android:drawable="@drawable/uncheck" />
    <item android:state_checked="true"
          android:drawable="@drawable/check" />
</selector>
 
Remember to replace the
android:drawable="@drawable/check" ....with your “check” image/icon
android:drawable="@drawable/uncheck" ....with your “uncheck” image/icon



2. Include “checkbox” tag in Your Activity’s xml file 

<RelativeLayout  ..............................(you can use any layout of your choice)
    android:id="@+id/checkbox"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <CheckBox
         android:id="@+id/checkBox4"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content" 
            android:background="@drawable/checkbox_selector"  
             (use your file name here)
 
         android:button="@drawable/uncheck">  
         (Uncheck has been set but you can change it)
    
</RelativeLayout>
 
If you didn’t get any error till now....You are Done !! Compile and Run your project. You should not face any difficulty in using this feature. In case you do...leave me a message below.

The same concept should be applied for the radio button as well. I have not tried with the radio buttons though. But I guess there shouldn’t be any issue. Anyways....enjoy programming !!

Sunday, 18 December 2016

UI designing in Android

Hello Everyone,

If you are an android developer then you must be aware of it’s UI designing part. It’s nothing but to design the layouts (i.e XML files). It’s the part which I used to skip all the time. I never took this seriously until last couple of days. You must be thinking what the hell happened with me ? Well, I was assigned an android project last week. I have to work upon this project from scratch. In my earlier projects I was not bothered about this designing and all things so I could concentrate only on the logical part. Unfortunately, it is not the case this time.

Since I was left with no other choice but to learn the UI design. So finally, I started learning it. So I thought sharing my learnings with you guys will be a good idea. I am  thankful to Nishant(Sir) who helped me to learn this XML things with an ease. He is a champ, and I just got lucky to work with him.

Let’s start from one of the most basic concepts, such as :

1.  What’s the difference between margin and padding ?
       Padding is for inside/within components. Eg. TextView , Button, EditText etc.
  Eg. space between the Text and Border
       Margin is to be applied for the on-outside of the components.
  Eg. space between left edge of the screen and border of your component 

Also, 
Margin is that space between the edge of an element's box and the edge of the complete box, such as the margin of a letter

It means, if we need all the four (left, right, top, and bottom) margins for any view. Then we don't need to specify all the four margins. We can use just "margin" which means margins from all the corners.  

2.  What is the difference between Linear, Relative and Frame layouts ??

LinearLayout means you can align views one by one (vertically/ horizontally).
RelativeLayout means based on relation of views from its parents and other views.
FrameLayout to load child one above another, like cards inside a frame, we can place one above another or anywhere inside the frame.
 So before picking up any layout for your design, observe the screen and you will get an idea to select the suitable layout for your screen. 


One last thing, by default, the text within any Button is set to upper-case. If you wanna change is to lower case. All you have to do is to include this line anywhere into your Button tag.


<Button    
       android:textAllCaps="false"    
  />
  
Will share some more in my coming blogs. If you wanna more clarity about anything mentioned in my blog, feel free to mail me or comment below.

Take Care and have a good day !!



Friday, 9 December 2016

Shared Preferences


Most Android apps need to save data about the application state so that users progress is not lost. SharedPreferences API in android lets us save data in key-value sets. When there is a need to save a small collection of key-values we should use Android SharedPreferences.
A SharedPreferences object points to a file containing key-value pairs and provides simple methods to read and write them. Each SharedPreferences file is managed by the framework and can be private or shared.

Step 1:
To use android shared preference we have to call method getSharedPreferences() that returns a SharedPreference instance poiting to the file that contains the values of preferences. The first parameter is the key and the second parameter is the MODE as shown below,

shared preferences = getSharedPreferences(mypreference,Context.MODE_PRIVATE);

Step 2 : Save object to shared preferences
We can save data to shared preferences using SharedPreferences.Editor class, for which we need to use edit method of the shared preference.

Editor editor = sharedpreferences.edit();
editor.putString(Name, n);
editor.putString(Email, e);
editor.commit();


Step 3 : Get data from shared preference
shared preferences.getString() method should be used to get the values for corresponding keys as shown below

if (sharedpreferences.contains(Name)) {
sharedpreferences.getString(Name, "");
}
if (sharedpreferences.contains(Email)) {
sharedpreferences.getString(Email, "");

}

So basically using these get and put methods in shared preference we can perform this save and retrieval functionality as we wish. S
haredPreferences are not the only way to store data. SQLite, AccountManager are some of the alternatives. 
 
But which one to use and when ??
Well, If you want to store some user-preference data - SharedPreferences may be a good choice.
  • If you want to store authentication data, like your user's auth-tokens - don't use SharedPreferences and take a look at AccountManager instead.
  • If you want to store business data e.g. multiple business entities, that keep some relations to each other, you want to be able to query on them and/or modify it - I'd recommend you to use Realm. Alternative is to use SQLite but in my very subjective opinion, Realm is much easier to start with.
  • If you just want to cache some JSON-based responses - take a look at caching mechanisms that your HTTP client may offer you. OkHttp for instance, has a pretty good support for that.
Speaking of loading time - SharedPreferences is pretty fast in general, but it really depends on how you use it. If you store big JSON structs in it, then read it fully just to find some specific object based on id obviously it'll take more time than using a real database for that.
Have in mind that all solutions I proposed (AccountManager, SharedPreferences, and SQLite/Realm) can perfectly work with each other in one app. Just make sure to choose the proper tool for a given problem. 



Sunday, 27 November 2016

Demonetization effect



Hello Everyone,

 I am sure everyone is aware of the meaning of the word 'Demonetization'. In short, it means 500 and 1000 Rupee notes will not be valid anymore.  Although there are some arrangements done by our Government like exchanging our old notes from any bank, withdrawal from our nearest petrol pump or Big Bazaar by swiping our debit card etc.

It needs a huge courage to make such decisions like this. I personally like this stand of our PM. Some are opposing while most of us are cheering for the decision taken by our PM on 8th November 2016. I seriously, don't know whether the inconvenience faced by many of us will be paid off or not. But I am happy to see that at least we have made an attempt. You never know, it might work also.

 Well, I was in Patiala when this news came out. I was there for my convocation and was happy to know about it. I had three notes of 500 with me and the best part was, banks were closed on 9th and 10th of November. I couldn't exchange my old notes. I had to come back to Delhi. I didn't have any idea,  how I'll manage all this. 

I was lucky enough to get a cab for Delhi where I could pay either by card or old notes. Soon after this news spread, people started searching for alternatives like Paytm, OlaMoney, etc to manage their daily expenses.

To be honest, I didn't have to stand in queues either for exchanging or withdrawal. I am thankful to my sister and friends for this, as they provided enough cash to me. But I can feel the inconvenience faced by others while standing in the queue. Everyone is going through a hard time for cash. But I feel a bit more for working class people for the simple reason that they don't get time for this in their office hours. On weekends, when they get time, the banks remain closed. 

Yesterday, I was surprised to see that I can use my Paytm even for a cup of tea which costs Rs. 10/-. I am relying on Paytm and Uber these days. I can see the vision of our PM behind this. The best part of the denomination, which I can see is to diminish the effects of "Fake Currency" which is present in a good amount in our country. 


I am happy to see that people are supporting our PM. They are not reacting. There was  no news of burning the ATMs or any accidental incident near any bank. At least I didn't hear any such news. I guess most of us is happy with the decision. While on the other hand, some are opposing too. I don't want to comment. They might have a valid reason.




Sunday, 20 November 2016

Firebase Introduction



Hello Friends,  
I spoke a lot about Android in my blogs so far. So today, I thought let’s pick something other than android. I am going to write about Firebase. I guess everyone is familiar with the basics of Firebase. If not, let me introduce firebase to you guys.
What is Firebase ?  
Firebase is a technology that permits you to make web applications with no server-side programming. It helps to make the development process quicker and easier. Also, we don't have to stress over-provisioning servers or building REST APIs with just a little bit of configuration. We can give Firebase a chance to take every necessary step such as storing data, verifying users, and implementing access rules.
It supports the web, iOS, OS X, and Android clients. Applications using Firebase can just use and control data, without having to think about how data would be stored, and synchronized across various examples of the application in real time. There is no need to write server side code, or to deploy a complex server framework to get an app started with Firebase.

Why Firebase ?
It is a versatile backend with a lot of good uses.
  • It cuts down development time and avoids messing with servers and data storage.
  • It is Scalable. If you want your application to scale well, you can trust that Firebase will handle all your data without missing a single step.
  • It provides cloud service, so there isn't any setup involved.
  • Data is stored as native JSON, so what you store is what you see.
  • Data is safe because Firebase requires 2048-bit SSL encryption for all data transfers.
  • Data is reflected and backed up to multiple secure locations, so there are minimal chances of data loss.
  • It integrates nicely with frameworks like Angular JS. So it's very useful and allows you to create an app in a very short time.

     Some of it's critical advantages includes,
    • Realtime update without using GCM.
    • Can start for free (only need to start paying once we hit 50 connections)
    • Built-in support for authentication services like Facebook, Google, and Twitter
    I'll continue this discussion in my coming blogs. If you find any difficulty in understanding this or wanna more clarification regarding any specific point. Feel free to write it down in the comment section. Enjoy the day !

 

Sunday, 13 November 2016

CountDown Timer in Android




A countdown timer is a device which is designed to count down to a particular event. They range in design from simple mechanical devices like those used in the kitchen to electronic versions designed to be downloaded and installed on a desktop. Numerous websites also use a countdown timer to mark the days, hours, minutes, and seconds until a major event, and some websites also generate countdown timer codes for installation on personal websites.

I am going to share the logic of designing a countdown timer in Android. Designing the countdown timer is not so difficult. The below code will create a countdown timer for 5 minutes.


void TimerStart(long remainingTime) {
CountDownTimer myTimer= new CountDownTimer(300000, 1000) {
// adjust the milli seconds here
public void onTick(long millisUntilFinished) {
text1.setText(""+String.format(FORMAT,
TimeUnit.MILLISECONDS.toHours(millisUntilFinished),
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) - TimeUnit.HOURS.toMinutes(
TimeUnit.MILLISECONDS.toHours(millisUntilFinished)),
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES.toSeconds(
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)))); }
public void onFinish() {
text1.setText("done!"); } };
myTimer.start();
}



But if I closed my app after using it for 30 seconds and reopen it after 2 minutes, it will start it’s countdown from 5 minutes. Ideally, it should subtract the time elapsed since I reopen the app. How to handle this ?? Well, Don’t worry !...I have a solution.


Let's take an example of running the countdown Timer for 24 hours.

Step 1 :  Calculate the timerEndTime(in milliseconds), i.e when the timer is going  to stop. You can do this by adding 86400000(number of milliseconds in 24 hours)  to the starting time of the countdownTimer.

Step 2 : Calculate the currentTime(in milliseconds)   i.e when you open the      application. You can do this by using the method called,    Calendar.getInstance().getTimeInMillis() 

Step 3 : Calculate the remaining time to the countdown timer by
             (timerEndTime – currentTime)

Step 4: Pass this value to the countDownTimer method
i.e TimerStart(timerEndTime - currentTime)

You are Done !!! 

Please comment below if you face any problem in the implementation of the above-discussed steps. 

Sunday, 6 November 2016

Use of Local History in Android Studio


As we all know, Android Studio is widely used tool for the development of any android application along with Eclipse. I personally use Android Studio and never used Eclipse. So I don’t know whether the feature which I am going to tell you today is available with Eclipse too or not.

More often we write code, make some changes(depending upon the situations) then build again in order to update the changes that we made. We then close the project and we are done. Let’s assume we have made some 100 of changes at different time slots and rebuilt the project after each change. We have closed the android studio as well. Now, after a week or so if reopen the same project. Can we track all the changes that were made in the project at different point of time?

Okay let me explain....say, I started my project on 1st October at 10:00 AM and it was running perfectly. I added some new lines of code at 11:00 AM and rebuilded the project it was also running perfectly. I repeated the same action at each hour. Finally at 8:00 PM I closed the project along with android studio. I repeated same work flow For the next 20 days.

Assume that I didnt backup my project. Can I switch my project to the same state as it was on 15th October at 02:00 PM ?? Well, the answer is Yes we can. It’s because of a feature included in the android studio called “Local History”.

In order to use this feature , select your activity file which you wanna roll back to any perticular date or time. Right click to the selected activity. Select “Local History”----->”Show History” from the context menu. You can see all the saved states on the left side and current state of your project on the righ side. It will also show the total number of changes that were made from that point till the date with the line number. Just click on the “>>” symbol to undo all those changes to your current project. you are done !! Enjoy the day !!

It actually helped me a lot so thought of sharing this with you all.....!!
Have a good day !!


Sunday, 23 October 2016

how to use global variable in android



                                        
Last week I was required to save one of the values for all the activities in my android app. Since I am a beginner so what I was actually looking for was : 
How to save value across several Activities and all parts of your application context ?
 We can certainly achieve this by creating static variable but it is not the good way as it influences towards memory leaks. The way in Android is to associate your variable with the Application context. Every Application has a context, and Android guarantees that Application context will exist as an instance across your application.
 
Then  finally I got the solution which I wanna share here...

The way to do this is ......
create a class and extends with android.app.Application, and specify your class in the application tag in your AndroidManifest.xml file. Android will create an instance of that class and make it available for your entire application context. You can get object of your class on any activity / broadcast receiver / service in application context(environment) by Context.getApplicationContext() method.


Tuesday, 11 October 2016

Image handling in android



I was working on image handling techniques last week. All I wanted to upload and download the images for my app. There were situations where I can easily handle the uploading and downloading of the images. But then there were also some situations when this technique wasn’t working at all. Well, to be specific, when I was taking images from gallery then it was working very fine which was not the case with images captured by Camera.

In some cases, such as selecting images from Gallery, the below code works fine.


Uri uri_gallery = data.getData();

StorageReference filepath = “your firebase location path”
filepath.putFile(uri_gallery).addOnSuccessListener
(new OnSuccessListener<UploadTask.TaskSnapshot>()
{
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot)
{
String downloadUriGallery = taskSnapshot.getDownloadUrl().toString();
Uri downloadUri = taskSnapshot.getDownloadUrl();
Picasso.with(ChatRoomActivity.this).load(downloadUriGallery).into(imageView);
}
}


But for capturing image from camera needed a different approach. Then I learned about use of bitmap.


if(data.getData()==null)dd
{
bitmap = (Bitmap)data.getExtras().get("data");
}
else
{
try
{
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), data.getData());
}
catch (IOException e)
{
e.printStackTrace();
}
}



Uri uri_camera = getImageUri(getApplicationContext(),bitmap);
StorageReference filepath =”your Firebase storage path” ;
filepath.putFile(uri_camera).addOnSuccessListener
(new OnSuccessListener<UploadTask.TaskSnapshot>()
{
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot)
{
String downloadCamera = taskSnapshot.getDownloadUrl().toString();
}

}


public Uri getImageUri(Context inContext, Bitmap inImage)
{
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}


So Finally, I was able to handle images taken from Camera as well for my app. You can always leave a comment below if you too have issues related to handling the images for your project. I will try to fix that issues with best of my knowledge.

Thursday, 29 September 2016

Use of Debugger in Android Studio



Debugging in Android Studio


Last night I was struggling with my code, which stopped running suddenly(that too without prior notice....not fair.  right ??) I was like clueless at that moment. I had no options left but examining the code thoroughly for the third time. I did the same, and the result remained same as well. Yeah...I couldn’t find the bug even after giving it a third try. That's why I love handling compile time errors rather than these runtime or logical ones. At least with compile time errors there is a learning, while in later case it's all your carelessness(in most of the cases). Well, when I had no alternatives left, I thought let’s try debugging this project. Yes....you heard it right...I had never used debugger before. Trust me guys....It's an awesome thing to be used. At least in my case, It helped me a lot. If you are also a beginner like me, then don’t waste your time in debugging projects by yourself(like I did). Learn how to use “Debugger” instead. It will save both your time and energy.

Of course use of log messages is an another way of debugging your project. But once you will use the debugger, you will get the difference. I personally used to love using log messages but it requires some extra efforts which debugger does that for us with just a click only.


To start debugging, click Debug in the tool bar. Android Studio builds an APK, signs it with a debug key, installs it on your selected device, then runs it and opens the Debug window.

If your app is already running on a connected device or emulator, you can start debugging as follows:
  1. Click Attach debugger to Android process .
  2. In the Choose Process dialog, select the process you want to attach the debugger to.
    By default, the debugger shows the device and app process for the current project, as well as any connected hardware devices or virtual devices on your computer. Select Show all processes to show all processes on all devices; the display includes any services that your app created as well as system processes, for example.
    From the Debugger menu, you can select a different debug type. By default, Android Studio uses the Auto debug type to select the best debugger option for you, based on whether your project includes Java or C/C++ code.
  3. Click OK.
    The Debug window appears. In this case, notice the two tabs to the right of the Debug window title: one tab is for debugging native code and the other for Java code, as indicated by -java.





Separate debugging sessions have separate tabs and different port numbers, which are displayed in parentheses in the tab.
4. To end a debugging session, click the tab for the session, and then click Terminate .


Note: The Android Studio debugger and garbage collector are loosely integrated. The Android virtual machine guarantees that any object the debugger is aware of is not garbage collected until after the debugger disconnects. This can result in a buildup of objects over time while the debugger is connected.


You can find complete Documentation here