jay's old blog

this blog will be deleted soon - please visit my new blog - https://thesanguinetechtrainer.com

Types – the core concept

When you are looking at programming (and working your way to become a developer) there are some basics you have to learn. Types, Methods and Classes. Everything else sort of builds on this.  

Types (sometimes referred to as variables) are like containers for the data that you wish to store, process, manipulate and anything else that you wish to do in your program (or project or solution or code file). To understand how types ( or variables) are like containers, let's take the example of a literal container. 

Suppose, you and your friends are going on a trip. Water is one of the basic items that you will pack with you. So, you buy a container big enough to carry enough water that will be sufficient for everybody who is part of the trip. In this case, the 'water can' is a type that can hold 'water'. Here water is the data that you are storing in a 'water can'. As the trip progresses, you will consume the water in the water can. Similarly, as your program goes through its motions, you will consume the data from the type. 

You may modify the contents of the water can (for example, you refill it when you take a stop at a hotel) during your trip. Similarly, you may decide to modify the data that is stored in this type as the program runs.  

Now, I am going to add one more detail that will make things a little more complicated but eventually simplifying things. Everytime I am mentioning the water can, I am not talking about the actual water can that is carrying the water during your trip. Rather, I am talking about the plastic that has been designed in the shape of a can with the sole purpose of carrying water.  

Similarly, when I talk of a type, I am talking about a 'data container' that has been designed with the sole purpose of storing a particular type of data. Which is also why, a type is not actually a variable. In fact, calling a type, a variable, would be wrong.  

So, what do we call the variable? What do we call the water can that is actually carrying the water. If my understanding is correct, we call the actual variable, an instance of the type. Going to our trip example, an 'instance' of the water can design is what is actually holding the water.  

Here is one more example 

You know soap? That you use to take bath or wash dishes (obviously you won't use the same soap to do both. That would be wrong) at your home. At the soap factory, there would be a metal template in the shape of the soap. Liquid soap will be poured into this template. Then, once it has cooled down, soap will be formed and packed. Later, the same template (probably hundreds of them) will be used to make the next batch of soaps.  

Here, the template (usually made of metal in the shape of the soap that is being made) is the type. Using this type, a number of actual soaps or instances are created. Each instance is identical to each other, they may be used by different people at different times during their operation. They are identical because they are all based off the same template i.e. type. Each soap, and hence the instance, will share common properties like color, shape and density. 

Similar to the above example, when you are building a program, you will be using a lot of 'instances' of different types. These instances are also referred to as objects or properties or variables. While each of these terms 'can' be used interchangeably, they are more suitable in a particular context. What I am trying to say is, these words – variable, instance, object, property – similar but not identical.  

Check out this github link where I use a simple type (int) and a few instances of said type to do simple addition. 


Follow me on twitter, facebook and instagram for more updates. Thanks!

Very basics of debugging

Even if you are just starting out, you will need to know some basic debugging tools. In this post, I will list out some of the things that have helped me greatly and are invaluable in my everyday stuff. Note that, this is for beginners (as with the majority of content on this blog) and I have left advance stuff like Call Stack out of this post. 

Debug.WriteLine 

A lot of folks don’t like Debug.WriteLine. Especially, experienced developers. For me though, Debug.WriteLine is an extremely easy tool. It is a little time consuming but it's like an internal log. Also later, when I want to build a logging system, it is easy to retool it to something else as well. 

When you create a new project, normally 'using System.Diagnostics;' won't be there in the beginning of your code file. So, add 'using System.Diagnostics;' at the top of your code file to use Debug.Writeline. 

Here is an example of Debug.WriteLine. 

Debug.WriteLine("Main - The value of hello is -  " + hello3); 

There is no rule that you have to write your Debug.WriteLine contents like I have done above. However, it's a format I prefer. If you observe closely, my print statement (the stuff inside the "") has three parts. 

  • Main – this indicates the method in which the debug line is placed. This is especially useful when you have hundreds of methods and want to know exactly which method is putting out this particular debug message. 

  • A pleasant statement – in this case, I want to show the value of a variable called hello. So I have written an easy to read line here. 

  • The variable in question – I have included the variable in question. 

  • I also use a '-' to divide the three parts.  

 

Remember that you can have your debug message as long as detailed as you want. However, don’t go overboard with it. Keep it simple and short. 

Breakpoints 

The bread and butter of any coder are breakpoints. Breakpoints are literal points that you place to 'break' the flow of the program. Putting a breakpoint is easy. You locate a line where you want the execution to 'break'. Then you right click and select 'insert breakpoint'. 

Here is a photo for that.  

When you debug your project, you need to know what is going on with your variables, objects, what values do they currently hold and so on. All this information is available for you. 

You will also be using these two buttons quit often. 

  • F10 – go to the next step 

  • F11 – did deeper into the next step. F11 is something you use when you want to follow the program and see what it is really doing. For instance, let us say that the current step involves a call to a method. If you want 'deep dive' into the method itself, you will use F11. However, if you don’t care what exactly is happening in that method, you press F10 and you will be stepping over to the next step.  

Continue 

Even a simple program can have many steps that it performs. That means, if you have placed a breakpoint at an early part of the program, you will be pressing F10 for a long time until the program reaches its end point. 

So, what I normally do is I use multiple breakpoints, at places which are important. Then, when I encounter a break point I will only use F10 or F11 until I have looked or observed what I want. After that I will press F5 (which will resume normal execution) until the next breakpoint is encountered. Then, I will do F10 until I get what I want and then hit F5. I keep doing this. This way I am making the most of breakpoints but not wasting my time with useless F10 or F11 pressing. 

Watch 

As you breakpointing and F10ing and F11ing and Continuing, you will want to keep an eye on multiple variables or objects. This is easy. Just right click on a variable (after you have stopped because of a breakpoint) and then 'add to watch'.  

After that, as the program continues to flow, you can see all those variables and objects that you have added to watch, along with their values.


Follow me on twitter, facebook and instagram for more updates. Thanks!

Pursuing an important certification

 We wrote about this previously and the exam in question is 70-483. 

Taking this as a opportunity, I have decided to Blog about their progress . Further, I will also blog about topics that might be useful to them, clarify doubts they have and include that could be useful to them. In addition to this, anybody who might be doing something could also find use from the efforts of these students, including future study nildana students who wish to do the same. 

Good luck to them, and me too.


Follow me on twitter, facebook and instagram for more updates. Thanks!

Version Control and Git – Part Two

Hopefully, you read our earlier post about Version Control and you have some idea what it is all about. I listed out a few problems of using the 'crude' form of version control.  

Obviously, there is a fantastic solution to all that, and that is Git and Git for Windows. Let me first talk about my understanding of Git, and then move on to the Git for Windows tool. They are both two separate things that work together to help you with fantastic version control. Also, the concept of version control is not unique to Git. There are so many open source and self-hosted and hosted solutions of git that are available. Those things aren't really part of the discussion here and you should explore those later.  

However, the general concepts of git and git for windows is what you would need for everyday usage from a developer perspective.  

So, git is the software that enables complete version control. What does that 'complete' mean?  

  • Create repositories – When you begin working with version control, you will hear about 'repo' or 'repository' or 'respositories' all too frequently. This repo is the folder where you have asked git to start monitoring. It could be pretty simple, like you have one folder which has just one html file. You create a repo at that folder, and git will start monitoring that one single file in that folder.  

  • Monitor changes – git will constantly monitor the folder (and all files and subsequent folders and the files in them, recursively) for any changes that you make. You add a single line, or a single character and you bet the git has noticed it. 

  • Commit changes – this is the best part about using git. Once you have made significant changes to your project and you want to safeguard this (like those compressed folders I talked about in the previous blog), you will do a commit. Further, when you commit, you have the option to write notes about why you are committing.  

  • Push changes – ah! The confusion may come here. You see, when you commit changes, the changes have been noted, sort of a like telling git that you have reached a milestone. However, the real magic of backing up this code online happens when you push these changes. So, commit happens locally and a 'push' pushes these commits online.  

  • Branches - this becomes useful when you are working as part of a team. There is usually something called as a main branch. Every commit goes by default to this main branch. However, if everybody is working on the same branch, that won't be nice at all. Ideally, each developer will work on his own branch (and make commits and pushes to indicate development progress) and keep his development effort separate from the rest.  

  • Pull Request – A pull request is made when the developer (with his own branch) wants some of his commits to be integrated to the main branch. That is when the developer raises a pull request for his branch. Usually it is essential to include a reviewer in the pull request, so that another developer may review the pull request, look at the commits and then finally merge the code. 

  • Merge the Branch – When the pull request (with all its commits) looks good, then the reviewer will merge this branch with that of the main branch. This means, when the next stage of the development starts, a new branch (with all the commits of all the developers and their branches and their commits that have been accepted) can be created by each developer and start working on the next phase of the project.  

 

These are the cool stuff that git enables. There are probably more stuff it does but these are the ones that matter the most to me in my daily developer life. 

Before I jump into 'git for windows', you need to understand something. Git needs to be installed on a server. This could be self-hosted (meaning you have your own server on which you install git) or hosted (you get git servers from another company like github or bit bucker or from a cloud service that comes bundled with git software such as Microsoft Azure or Amazon Web Services and so on). Once you have your own git server installed, you will be able to create projects, user accounts and the usual management stuff.  

Of course, the development does not happen on the git server. The git server is that 'online' space where all your code (and its changes) are stored. You need something, a client for the server to interact with. There are dozens of clients that you can use and the one that I prefer is git for windows. As the name suggests, there is git for other platforms like Linux, Unix and other operating systems that support application development.  

Git for windows, provides two ways to work with your git server. There is the 'git bash' and 'git GUI'. Although it is tempting to use the git GUI, I would forbid any up and coming developer to endure the 'learning curve' of using the command line version of git for windows, that is 'git bash'. It presents you with a unix/linux type command line interface with which you can do all the above stuff that you can do with git. Of course, git for windows also comes with shell integration so that you can git bash (or git GUI, but you should really not use the GUI git) on the folder you are planning to use with a simple right click.  

Next, I will create a simple project and run through all the git commands explaining all the different things that git can do, as described above. find that post here.

Follow me on twitter, facebook and instagram for more updates. Thanks!

Version Control and Git – Part One

Despite being a developer for a long time now, I ignored version control at my own peril. That is not to say that I never felt the need for version control. In fact, even way back when I was building my own code for my final year project (It's funny that even in a big college like SJCE where I did my engineering, most of my friends were content to just pay for their final year project and just let it be. If my sources who will remain anonymous will confirm, even today this trend of buying the final year project still continues to be the norm in most engineering colleges which is straight out sad but is a story for another day) I felt the need for version control.  

Essentially, this is what I used to in my earlier days of development. Suppose I am building a simple calculator. As always, I would go ahead and design the entire project using a combination of notes and drawings. Once I am happy with my design, I will take a break and then redesign things after running it through some use case scenarios (which are once again drawings filled with flowcharts, user inputs and outputs). After the design is finalized, I will break it up into stages and then start building the software. 

Now, here is how things can go horribly wrong. Suppose I complete building the stage 1 of my calculator. Everything is working fine, and testing is complete and I am extremely happy. Then, I start work on stage 2 and then I add some new code. Boom and Kaboom, the application is no longer working. Further, I cannot remember all the changes I made. Which means, not only is stage 2 out of the window, all the good work done on Stage 1 is also gone. Essentially, I have no other way but to start from scratch.  

Now, after something like this happened a few times, I decided to do 'crude' backups. What I would do is go back to the solutions folder (or the project folder) and then compress Iit. Give it a name (usually a combination of the date and time of compression) and then proceed further development. This way, if something goes wrong, I have back up and that means, I don’t have to start from scratch.  

So, suppose my calculator projects has six stages, when the entire project is completed, there would be six compressed folders. Each of them representing a fully working 'stage' of the application. In other words, each of these compressed folders are 'versions' and I am able to control the development of the project. Control, in the sense that, if something were to go wrong (and in software development something will always go wrong), I am still in control of the project. So, we could say that is 'Version Control'. 

The whole compressed folder thing is a very crude form of version control. While it prevents complete destruction of the project, it is version control in its most basic level. It does not help me in any way to collaborate with my friends.. It does not help me keep track of changes. Also, the entire process of zipping folder is time consuming and not the most efficient way of doing things. Then, if you want your code to be safe, you will have to manually upload it a cloud storage.  

The solution to that is Git, and we will talk about that in the next post.

Follow me on twitter, facebook and instagram for more updates. Thanks!


Developers! Overcome these artificial physical boundaries

As a trainer, one of the things that I like my students to do is get rid of 'physical limitations' that can reduce your actual productivity. As I work as a developer in addition to my training duties, here are some stuff that make me better. 

Wireless Keyboard and Mouse 

In a modern workplace, it is fairly difficult to find desktop machines being used by developers. From a purely maintenance perspective, it makes sense for the IT department to give out portables/laptops. Same goes to college students. It simply makes sense that your daily programming device is a portable.  

However, I find that your speed improves much more if you club this with a wireless keyboard and mouse. The thing about the built in keyboard on the laptop, is that, it's crammed. The standard size of laptops is 15 inches, so your keyboard is no bigger than 14 inches. You also don’t get that tactile feedback when typing. The built in trackpad is good for occasional browsing but for heavy duty usage (which is a given whe you programming) the mouse is the only way to go. 

I must also insist that the keyboard and mouse be wireless. You can have a basic wireless keyboard/mouse for 800 rupees (13 dollars) and never ever buy wired keyboard/mouse please.  

Shortcuts 

Almost every IDE that you use has short cuts. In fact, they are sites dedicated entirely to shortcuts. Then, there are windows shortcuts that can turn you into a powerhouse developer.  

For instance, when switching tabs, use Ctrl Tab. When switching between windows, use Ctrl Window. Then, there are page down, page up, ctrl + arrow keys, and Home and End keys. These keys will take some getting used to. In fact, if you are only now starting to use shortcuts, you will feel that the entire procedure is actually slowing you down. It will takes a while for you to remember the actual shortcut. You will begin to think, the mouse is better. 

However, once you get past the steep learning curve, the shortcuts get built into the muscle memory and you will be saving minutes every day.  

Also, using short cuts makes you look really cool. It does, and trust me on this. 

Comments and Regions 

There is no other to way to say. Your chose IDE will support regions and commenting. Please take a few minutes to write the necessary comments and divvy up the code into regions. Sure, when you are on a roll and coding away on all cylinders, you may feel that the comments and regions are holding you back. 

The truth is, coding is simply a small portion of your role as a 'software developer'. Always aim to be a 'developer' and not just a 'coder' or a 'programmer'. Software development involves a lot of other things like testing and fixing bugs. It also involves adding new features at some later point. Consider that most software is built by teams. These comments and regions ensure that your code becomes readable. 

Sure, writing comments and using regions will consume some time. In fact, I have spent more time writing comments and adding regions when compared to the actual code itself. However, when issues arise (and they always will) it becomes that much easier to narrow down to the actual problem location. This also leads to less time taken to fix issues. 

From a long term perspective, when another developer takes over your projects (developers, as with any other professionals are constantly changing jobs, shifting roles and so on), she will be that much happier when she sees the comments and regions.


Follow me on twitter, facebook and instagram for more updates. Thanks!

android training – Episode 7 – page navigation



Hello and welcome back. May name is Jay, and I am your trainer for today. We are going to assume that you already went through Episode 1 to 6.

We are jumping into development now. That means, the page will be heavy with screenshots. I have tried my best to use low sized images so that you can load this even on a 2G connection. If you are having issues loading any of our tutorial pages, contact us. You will find the contact information, at the end of the blog.

You can download the code for this project, from GitHub, right here – https://github.com/Jay-study-nildana/sn_tr_activity_nagivation_2

If you don’t know about GitHub, check out our blog post here – http://blog.studynildana.com/post/study-nildana-and-github

Topics Covered In This Episode

In this episode, we will look at doing the following.

  • Navigating from one activity to another activity
  • Send data from one activity to another using ‘Bundle’ object

In this app tutorial, we will show you how to go from one app page (or activity) to another app page (or activity). This is a basic level of skill needed in building apps because most apps require you to move between activities/app pages. Further, we will also show you how to send simple data from one activity to another activity using this object called as ‘Bundle’. It is useful for simple data operations.

Of course, if you want to send huge sets of data between activities, a better option would be to use SQLite but that is something we will talk about some day in the future.

As always, here is how your new project should look. If you are not sure how we got something like this, refer our training episodes 1 to 6. I want to draw your attention to the circle. That is where all the layouts (the xml part of an android activity) are located. We are looking at navigating to another activity, so we need to add a new activity.




I just want to add here that an android activity is actually a combination of two pieces.

  • Activity – First Piece – The xml page that forms the UI part and is where we put buttons, TextView and all the visual stuff. This will have an extension of “.xml”. For example, MainActivity.xml
  • Activity – Second Piece – The java page that forms the code part where all the backend action takes place. This will have an extension of “.java”. For example, MainActivity.java

Okay, coming back, there are so many ways to add a second activity. We will do something like this, and follow the pictures in sequence. Start off by “right clicking” the “layout” on the project directory, then selecting “new” and then selecting “activity” and then selecting “blank activity”.





After you do that, you will see something like this. Don’t do anything extra. Leave everything as it is, and hit “Finish”.




Now, you have a new activity called “Main2Activity” which adds two files to your project. One .xml and One .java file, as explained before. Here is the picture to show where they are located.




Now, I am going to do the following.

  • Add some basic text in both the activities. This has already been covered in earlier episodes.
  • Add a button in the first activity. On pressing this button, the app will go from first activity to the second activity. Adding buttons is also covered in earlier episodes.
  • In the button, I will add code that will allow me to go to second activity. This I will explain in detail.

So, here is my OnClick function for the button. This is how it looks before I add the code that will perform page navigation.

            @Override
            public void onClick(View view)
            {
                //This is where I will write my code that will move the app from this activity to the next one

            }//end of OnClick function

In order to perform page navigation, I need to use Intents. Someday, I will write a detailed blog post about Intents. For now, understand that Intents (short for Intentions) are something that will use whenever you wish the app to do something for you. Right now we “Intent” to navigate to the second activity.

So, I will fist create an Intent, and assign it a purpose. Check out the code snippet, and the code comments to understand what is happening. This is how it will look after I have added the code that will perform page navigation.

            @Override
            public void onClick(View view)
            {
                //This is where I will write my code that will move the app from this activity to the next one
                //I now create a intent object, and then provide it with the application context and the class
                //of the activity i want to go to
                Intent in = new Intent(getApplicationContext(),Main2Activity.class);

                //after assigning the intent, I will then start it.
                startActivity(in);

            }//end of OnClick function

Now, let me run the app, and see if the page navigation is actually happening. Here is how app looks upon launching.




And it has come to the second page/activity, after pressing the button




Alright then! Our app is doing simple page navigation. Basic navigation is of no use, if we cannot send some data. Next, we will send a simple sentence (string) from the first page/activity to the second page/activity. To do so, as informed before, I will use a Bundle. You see, a bundle uses a simple database that is based on the key/value principle of storing data.

Perhaps someday, we will write a detailed blog post about key/values. Till then, the basic concept is that when storing data, we will first create a ‘key’ and then assign some value to it. Later, we use the ‘key’ and then extract that value from the Bundle.

Here is the code that will use the Bundle, a key and its value. Follow the comments to understand what is happening. In this code, I am sending the words “page navigation tutorial from study nildana” from the first activity to the second activity. Please note that this code is in the “MainActivity.java” file.

                //I now create a intent object, and then provide it with the application context and the class
                //of the activity i want to go to
                Intent in = new Intent(getApplicationContext(),Main2Activity.class);
                //after assigning the intent, I will then start it.

                //I wish to send a string that contains the sentence "page navigation tutorial from study nildana"
                //so created a string variable that will hold this sentence
                String sentence_to_send = "page navigation tutorial from study nildana";

                //Now, putting this String variable into the bundle that will go with the intent
                //Remember the key and value thing we talked about in the blog?
                //Here the key is on the left side and the  name is 'sentence_from_first_activity'
                //The corresonding value is the variable 'sentence_to_send'
                in.putExtra("sentence_from_first_activity",sentence_to_send);

                //now, when this intent is started, the bundle we sent will go to the next page.
                startActivity(in);

Now, I need to move to the second activity, and collect this bundle. Then, I need to collect the string/sentence I want, using the key I used in the first activity. Check out the code snippet and the comments to understand what is happening. Please note that this code is in the “Main2Activity.java” file, which is the target of this intent.

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

        //first I need to create a bundle object to collect all the extras
        //here i have creaed a bundle and also collected all the sent values
        Bundle b = getIntent().getExtras();
        //now I will use the key that was used in the first activity to collect my string value
        //the collected string value has been stored in the variable called 'temp'
        String temp = (String) b.getCharSequence("sentence_from_first_activity");

        //now I will set the text of the TextView object that is already in this activity

        TextView textView = (TextView) findViewById(R.id.textView_second_activity);
        textView.setText(temp);
    }

Now, let me see if the app actually sends the string by running the app.




And, look at that. The information did come through the bundle.




Well, there you go. We now have a simple app that will navigate from one page to another. It will also carry some data with it. As always, don’t forget to download the code from our GitHub repository right here - https://github.com/Jay-study-nildana/sn_tr_activity_nagivation_2

Next episode, we are going to show a simple calculator that will use all the concepts that we taught you from Episode 1 to Episode 7. In fact, one of study nildana students will be building that app. 

Follow me on twitter, facebook and instagram for more updates. Thanks!

android training – Episode 6 – input and output

Hello and welcome back. May name is Jay, and I am your trainer for today. We are going to assume that you already went through Episode 1 to 5.

We are jumping into development now. That means, the page will be heavy with screenshots. I have tried my best to use low sized images so that you can load this even on a 2G connection. If you are having issues loading any of our tutorial pages, contact us. You will find the contact information, at the end of the blog.

You can download the code for this project, from GitHub, right here – https://github.com/Jay-study-nildana/sn_tr_inputoutput

If you don’t know about GitHub, check out our blog post here – http://blog.studynildana.com/post/study-nildana-and-github

Topics Covered In This Episode

In this episode, we will look at doing the following.

  • Using ‘EditText’ widget to collect input
  • Using ‘TextView’ to show output - This has already been taken care of in an earlier episode and hence will focus more on EditText this time.
  • Using a simple ‘Button’ widget. This is new to you, so we will spend additional time on this. 

As usual, we will not just focus on using these widgets. In this input and output project/tutorial, I will build a simple app that accepts the name as an input, and then says “Hey, (entered name)! Welcome to training at study nildana”, when the button is pressed.

The idea is, if you can understand basic input and output like this, you can probably start doing more things. To take our usual example app, alert nildana, we are generating a secret key based on the information entered by the user. In your app, you could collect some other type of input and show some output based on the app design you are aiming for.

Further, we also spend some time on using a button. A lot of times, you want to trigger an action based on user action. If you remember, any app you use, you are almost always getting things by tapping on something. For instance, you enter the username/password and then press the ‘login’ button. You select a number of photos and then hit ‘send’ to send it to someone else. That means, you are always using one or the other kind of button all the time.

Taking Care of Design UI

As your project starts, your project should look something like this. As with the previous episodes, I have made the app full screen and removed the menu on the top right corner. Use my earlier episodes to see how you can do this.




There are three parts in the above image.

  • Two circles with the heading ‘1’. That is where I am dragging an ‘Edit Text’ widget from the palette on the left and putting it on our design view. This is the same procedure you used in the previous episodes to add TextView widgets. As with TextView, we have a special post on EditText as well. Check out that blog right here –
  • The circle with the heading ‘2’ is where you can see the same EditText we just added. You will notice a small exclamation symbol. That is because we have not set a ‘input type’. Check out our specific blog on TextView to find out what this is all about.
  • The circle with the heading ‘3’ is where you will find properties. This is where I can set the properties, and right now all I want to do is give this widget a proper name, also called as ‘id’. As with variable and function names, we should be using meaningful names for the id too. If you are not sure why or what is the importance of meaningful names, check out our blog on that topic, right here –
After setting the input type (to text) and the id (to editText_input_user), the same picture will look something like this.





Next, I will need a TextView, to display the output. The TextView has already been dealt with in previous episodes, but you can always refresh yourself by visiting this link about TextView –

Here is the picture after adding TextView. You will notice that Android Studio is flagging me, or warning me about something. I have marked it with a circle.




The error is about “hardcoded strings”. Hardcoded strings are string values (English words, sentences or anything else you type in double quotes i.e. string constants) that are directly typed into the widget. As a rule, more like programmer good habits, it is better to use string resources that are stored in “strings.xml” file. Find out more about string resources and the strings.xml right here, at this blog –

I have gone ahead and added the string resource, and that error is now gone. I have added a new string resource called ‘input_user’ and to that resource, I inserted a value called ‘output will come here’.




So, the input and the output box is here, it is time to include a button. As usual, we have a specific focus blog post on ‘Button’ widget that you can find here –




And, I set the button a title (in the text property) and set an id. Here is the picture to reference that.




At this point, we have the three widgets that we need to get going. The EditText to collect the input. The TextView to display the output and lastly, the button to make the words appear. To make this happen, we need to move to the code file or the “.java” file of the activity we are working on.

Taking Care Of Code

I really hope you have downloaded the code from GitHub, or you are at least looking at the code directly on the website. Follow the comments that populate the code. Otherwise, you won’t understand what is happening.

Now, I need a function that will “listen” to button taps in the entire activity. For that, I type something like this picture, and android studio will prompt me automatically if I wish to create this function.





Once I let it create the method, the code snippet should look something like this. Feel free to copy this code to your project, if you are having difficult or run into errors.


    private void button_listener()
    {

    }//end of button_listener

Now, in this button listener, I want to do the following.

  • Connect the button widget (in the UI) with a button object in the code.
  • Get the button object, and connect that to an onclick listener.
  • Then, inside this listener function, collect input (from EditText) and then display output (on TextView)

Here is where I am creating a Button object.

    //creating the Button object

    Button button_for_hey_there;

When you try to add the above, Android Studio will prompt you to automatically include a library that is needed for this code to work.




You will see prompts like this whenever you include a code that needs some missing library. When you see this, as the prompt suggests, use “Alt and Enter” and Android Studio will do the rest for you. Of course, you don’t do this, you will run into errors. So, don’t skip the “Alt and Enter” step.

Now, connecting this button object to the button UI widget

        //connecting the button object to the button in the UI page
        button_for_hey_there = (Button) findViewById(R.id.button_hey_there);

Now creating the listener. Do remember that the listener will be automatically created for you or you can copy paste the above code.

Finally, you should have something like this, the full code.

        //creating the onclick listener
        button_for_hey_there.setOnClickListener(new View.OnClickListener()
        {
            //this is the OnClick function where we need to put all the things that are supposed to happen when the user taps the button

            @Override
            public void onClick(View view)
            {

            }
        });

Do you see that onClick code?




Whatever code you put inside that function, will be executed when the button “button_hey_there” is tapped by the user.

In this code, I am going to connect the EditText object to the EditText UI element in the UI page.

                //connecting the editText object with the editText widget in the UI
                //this will be the persons name
                EditText editText_collect_user_input = (EditText) findViewById(R.id.editText_input_user);

Now, I am going to collect whatever the user has entered in that widget.

                //collecting the string that the user has entered
                String temp_collected_name = editText_collect_user_input.getText().toString();

Now, I am going to create an output string.

                //creating an output string
                //I want an output something like - "Hey, Jay! Welcome to training at study nildana
                //for those who are new to Java, '+" here acts like a concatenation operator, adding up strings together
                String output_string = "Hey, " + temp_collected_name + "! Welcome to training at study nildana";

Now, connecting the TextView object to the TextView UI in the UI page.

                //connecting the textView object with the textView
                TextView textView_output = (TextView) findViewById(R.id.textView);

Finally, I am going to ‘set’ the output string to the TextView on the UI page, through the TextView object.

                //setting the output string to the textView_output object
                textView_output.setText(output_string);

Here is the final code, of the entire file. If you put this code into your java file, it should do what we plan to do with this lesson.

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity
{
    //creating the Button object

    Button button_for_hey_there;

    //the OnCreate function is the first function to be called when the current activity starts
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //to make the button work, we need a function called that will "listen" to buttons being clicked.
        //you can call this function anything you want
        //I am calling it "button_listener" you can call it "amazon" if you want.
        //just make sure you put it in the OnCreate function, right here

        button_listener();
    }//end of onCreate

    private void button_listener()
    {
        //connecting the button object to the button in the UI page
        button_for_hey_there = (Button) findViewById(R.id.button_hey_there);

        //creating the onclick listener
        button_for_hey_there.setOnClickListener(new View.OnClickListener()
        {
            //this is the OnClick function where we need to put all the things that are supposed to happen when the user taps the button

            @Override
            public void onClick(View view)
            {
                //connecting the editText object with the editText widget in the UI
                //this will be the persons name
                EditText editText_collect_user_input = (EditText) findViewById(R.id.editText_input_user);

                //collecting the string that the user has entered
                String temp_collected_name = editText_collect_user_input.getText().toString();

                //creating an output string
                //I want an output something like - "Hey, Jay! Welcome to training at study nildana
                //for those who are new to Java, '+" here acts like a concatenation operator, adding up strings together
                String output_string = "Hey, " + temp_collected_name + "! Welcome to training at study nildana";

                //connecting the textView object with the textView
                TextView textView_output = (TextView) findViewById(R.id.textView);

                //setting the output string to the textView_output object
                textView_output.setText(output_string);

            }
        });

    }//end of button_listener

}//end of class MainActivity

Now, let’s run the app and see if we achieved our goals here. How it looks when app is launched.




Here is when the app is accepting input.




Here is the final input.