First, watch this video to learn the basics!
This will help you get ready to start building the project below, so don’t miss it!
Let’s Build our First Android App!
Goal: You will be building an app about yourself! This is will help enact your new knowledge about variables in Java and about activities in Android.
For those of you Linux and Mac users
All of our downloads are in the 7zip file format to keep download speeds fast. Make sure you download Keka for Mac or p7zip for Linux to be able to open these files.
void onCreate(Bundle savedInstanceState), under the last line inside these brackets, write these lines: y = (ImageView) findViewById(R.id.); x = (TextView) findViewById(R.id.);
*/:)Android Pro-Tip: the onCreate Method is very similar to the public void main… method in Java. Cool, right?ImageView , you should also see a line in each of these <> that says android:id= @+id/ and before the end quote @+id/ after the . in y = (ImageView) findViewById(R.id.); y.setImageResource(R.drawable.whateverYouNamedYourImage);y.setImageResource(R.drawable.mypic);x.setText(“Insert Something about yourself”);
Let's dive further into Java and into Android, with a lesson on Strings and Classes!
Below are slides for a simple project to help you learn these concepts.
Use either Eclipse or the
TutorialsPoint Online Java Compiler to do this project.
Practicing For Loops: Application #1
1) Open the TutorialsPoint Online Compiler
2) Under the class line, declare a static int called z, and set it to 0
3) Let's write our for loop. In the main method, write this:
for(int x=1; x< 9; x++){
z++;
System.out.println(z);
}
4) Click compile, then execute at the top of the screen to run your program
What did I just do?
One application for a for loop is to repeatedly do an action a certain number of times.
Each for loop has an int inside its parentheses that reflects the number of times you want the action to repeat.
With x starting at 1 and stopping right before nine, the action inside is repeated 9 times. The action repeated 9 times
is taking the integer z, which is 0, and add 1 to it 9 times. This explains why the number 9 is printed when running
the program.
Practicing For Loops: Application #2
1) Open the TutorialsPoint Online Compiler
2) Under the class line, declare a static string called word, and set it to "apple"
3) Under this line, declare another static string called newWord, and set it to ""
4) Let's write our for loop. In the main method, write this:
for(int x=1; x< word.length; x++){
newWord += word.chartAt(x);
System.out.println(newWord);
}
4) Click compile, then execute at the top of the screen to run your program
What did I just do?
Another application for a for loop is to look at each element in an object. In this case,
we are looking at every character in the string called word, and adding it to the string
called newWord.
Now that we understand classes and methods in Java, let's put our skills to the test!
Adding Classes and Methods to our Android Project
1) Open Android Studio and the project you made in Lesson 1.
2) Right click on the com.example.whateveryounamedyourproject > new > Java class
3) Name the class your first name
4) Let's add two methods to get the text and the image we need. First, let's add create a public
method called getMyImage that returns the integer value of the location of the image we used in lesson one. If you are still confused
on how to declare a method, try:
public int getMyImage() {
return R.drawable.whatyounamedyourpic;
}
5) Now, let's add create a method called getMyText, which returns a string of the text you used in Lesson 1 to describe yourself.
public void getMyText(){
return "insert text about yourself";
}
6) Let's modify our main class to reflect the use of our new class. Go to the Main Activity and declare an object of the class you created underneath where you had declared your text and image view by writing:
WhateverIsYourName s;
7) Initialize this object by writing s = new WhateverIsYourName(); in the onCreate method.
8) Change what's in the parentheses of setImageResource to s.getMyImage()
9) Change what's in the parentheses of setText to s.getMyText()
What did I just do?
You have just created a class that represents you. This class has methods that return the text about yourself, and a cool image of you.
All you did was tell your MainActivity to set the ImageView and TextView you created with XML to display the text and image from your class.
Let's get back to some Java to learn about arrays and lists, and ways to use loops to access each element.
Arrays
Eclipse:
1) Open Eclipse and create a new Java project called newProj
2) On the left side, click on the project, right click on the src folder, and click New > Class
3) Name the class main, make sure public static void main(String[] args) is checked, and click finish
4) Under the class line, declare a new array by typing:
static int[] arr;
5) Initialize and set the length of the array by typing arr = new int[how many things you want in the array]; in the main method.
6) Let's utilize a for loop to add different ints to the array. Create a for loop that starts at 0 and ends at the end of the array.
for(int x=0; x < arr.length; x++){
arr[x] = x;
}
7) Use a different type of for loop to print out each object in the array.
for(int z: arr){
System.out.print(z);
}
//basically, this loop is called a for each loop, and it looks at each type of object in a certain type of data. In the loop above, we are telling the computer to look at each int an the array we created and print it out.
8) Run your program!
TutorialsPoint Online Compiler:
1) Do steps 4-7 above
2) Hit compile, then execute
What did I just do?
You have just created an array, a book-shelf like way to store data. Arrays have a set length,
which you set when initializing it in the main method. As you can see, arrays do not have delete or add methods.
All they have is a way to set what object is at a certain index. In the array above, you set the object at index number x to be x.
Lists
1) In the same class, declare a list under the class line by typing:
List <Integer> list;
2) Initialize the List in the main method by typing:
//You cannot use int when declaring lists. You have to use Integer.
list = new ArrayList<Integer>()
3) Let's do the same thing we did with the array and add numbers from a loop. However, with lists, we need to think differently. When you create a list, it has a size of 0. Lists do not have a predetermined length. So, let's type this instead:
int b = howBigYouWantYourListToBe;
for(int r=0; r< b; r++) {
list.add(r);
}
4) Write a loop to go through all the variables in the list.
for(int a: list){
System.out.print(a);
}
5) Run it!(or hit compile, then execute in TutorialsPoint)
What did I just do?
You just created a list, and added numbers in ascending values as they approach z to the list. As you can see, lists have add and remove methods, and if you use just .add, the list adds the object in parentheses to the end of the list.
Challenge!
Create a new project. Make an array of dog names, and a list of owner names,(so make sure the array and list are of type String, not int), add values to each, and print using loops.
Today, we were going to combine all of the skills we learned to build a note taking app for Android. Before we get started, make sure you have done lessons 1 and 3. See if you followed the instructions correctly
by checking out our project on GitHub.
Errors
Some of the instructions had errors. Sorry about that! The lines that had errors are italicized, with the correct method below them.
Setting up the project with GitHub
1) Go to GitHub and create a new account
2) If you have a Mac or Windows, download the GitHub application. If you have a Linux
machine, download git.
3) Open the GitHub application, and set it up with your account.
4) Go to Android Studio and create a new project. Give it a name that's clever. Make sure its saved in a location that you can easily access, and that Phone and Tablet is selected. Otherwise, leave everything else as is.
5) Go to the location of your new project. Drag the project folder into GitHub. It will ask you to create a repository. Name it the name of your project.
6) If you are on Linux, make your project, create the repository on GitHub's website, and follow these instructions to make the online repository have what's on your computer.
What did i just do?
You have just set up your first GitHub repository. This means that your project can be accessed online,
and that other people can help contribute to your project. Having projects on GitHub is a great way to show your skills,
and the way through which many employers will check to see how much experience you have coding.
Design
1) In the main xml file, add two buttons to the bottom of the Android screen, with one on the bottom right, and another on the bottom left. Start with the right one first.
2) Double click on the button at the bottom right, and rename it "Save"
3) Double click on the button at the bottom left, and rename it "Open Recent"
4) Under text fields in the list of objects to the left of the Android screen, drag Multiline Text above the buttons on the Android screen. Make it fill the screen from the top to where it touches the buttons.
What did I just do?
You just built the XML file for your project. What you see on the Android screen in main.xml is what you are going to see when you run the app on
the emulator or on an Android device.
Add Realm to your project
1) On the left toolbar, click on Gradle Scripts, then on Build.gradle(Module:app)
2) Between the two brackets after dependencies, write this line:
compile 'io.realm:realm-android:0.80.1'
3) Once you add this line, a yellow toolbar should appear saying something like "Gradle build has been changed." Click sync.
4) Once its done syncing, click on java, then com.example.whateveryounamedyourproject, then on MainActivity.java in the left toolbar
What did I just do?
Arrays and lists are a great way to store objects temporarily. Emphasis on temporarily.
This means that the minute you quit the app, whatever you saved in those arrays or lists
is not saved cannot be seen the next time you use it. To make sure that data is saved
even after you close the app, you have to use a database, which ensures that this data is saved
onto the device for the next use. Realm is an easy-to-use database, and what we just did was
download it to our project. The neat thing is we didn't even have to go to a website!
Declaring our variables and creating methods
1) Declare an EditText under the class line, and call it someNote
*/:) Java Pro-Tip: Declarations follow this format: TypeOfObject nameOfVariable; For example, declaring an int called x would be int x;
2) Declare a Button, and call it save.
3) Declare another Button, and call it openRecent.
4) If the text on EditText and Button are red, click on the word and hit alt+enter.
5) In the onCreate method, set each the text and buttons to the ones you created in your xml file.
someNote = (EditText) findViewById(R.id.editText);
save = (Button) findViewById(R.id.button);
openRecent = (Button) findViewById(R.id.button2);
6) Under each button, let's add a listener method that manages what happens when you hit the buttons.
save.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
}
});
openRecent.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
}
});
Creating a class to manage notes
1) Right click on the com.example.whateveryounamedyourproject and click New > Java Class
2) Name it Note and click ok
3) Now, let's turn this into a Realm object class for use in our Realm database. Next to
public class Note, write extends RealmObject
4) Underneath the class line, declare an Editable called t. If Editable is red, click on it and hit alt+enter.
4) Underneath the class line, declare an Editable called t.
5) Create a constructor for Note by doing public Note(){} . Add Editable x as one of the parameters(which means inside the parantheses)
5) Create a constructor for Note by doing public Note(){} .
6) Set t equal to x inside this constructor
6) Create a new public String method called setT that is void. Add String x as one of its parameters(in the () of the declaration). In the { } of the method, set t equal to x.
7) Create a new public Editable method called getText. Make it return t.
7) Create a new public String method called getT. Make it return t.
What did I just do?
You just created an object class, specifically a Realm object class. This tells Realm what type of
objects are going to appear in its database. Also, we added a constructor so that when you create a note, you have to
have to add text to it. Now, we can use this class in our MainActivity to create a new note every time save is hit,
and add it to the Realm database.
Creating the Realm and RealmList
1) Under the class line, declare a Realm by typing:
Realm realm;
2) If Realm is red, click on it and hit alt+enter.
3) Declare a RealmList in the same place by typing:
RealmList<Note> rList;
3) Declare a RealmResults in the same place by typing:
RealmResults<Note> rList;
4) Initialize both the Realm and the RealmList by typing:
realm = Realm.getInstance(this);
rList = new
rList = realm.where(Note.class).findAll();
Tying it all together! Using the button methods with Realm
1) The way data is saved to Realm is putting what Realm objects you want created between a beginTransaction and commitTransaction. Let's
lay down these two methods by typing this in the onClick method for the save button:
realm.beginTransaction();
realm.commitTransaction();
2) After the beginTransaction and before the commitTransaction, let's create a Note object with the text from our text field and add it to our Realm and RealmList.
Do this by typing:
Note n = new Note(someNote.getText());
n = realm.createObject(Note.class);
rList.add(n);
Note n = realm.createObject(Note.class);
n.setT(someNote.getText().toString());
rList.add(n);
3) Now that we have the saving bit down, lets figure out what happens in your openRecent method.
In the click listener method for openRecent, let's set text field to the text from the last note added saved by typing:
someNote.setText(rList.get(rList.size()-1).getText());
someNote.setText(rList.get(rList.size()-1).getT());
4) Now, run this app in an emulator! Go back to Lesson 1 if you don't remember how.
What did I just do
A realm is a type of database, and a note is an object with text that represents the note you write on your device.
A list is a simple way of storing and accessing data. In this lesson, we linked the three to add the functionalities of
saving a note and opening a recent one. We created the Note class to have a model for saving and getting
info about a note, intialized and added to the realm to add Note objects to the database, and intialized and implemented a
a RealmResults, which is a list of all the objects in the realm.
Adding these changes to GitHub
1) If you have a Mac or Windows, open the GitHub application, click on this project from the toolbar on the left,
and type in the commit "Created Project" and in the description, a little description of how this project works.
2) Otherwise, go to the terminal, type cd Desktop or wherever was the main file you saved your project in, and more cds after that point to open folders inside this folder, until you get to your project's location
3) Type git status to see all the files you need to add.
4) Type git add filename.extension for each file that shows up in red.
5) Type git commit "some message you want to see for what you did"
6) Type git push
Challenge
Add another feature to your notepad.
Are you at Hart's coding club?
What if you wanted to add another screen to your Notes app? And what if you wanted to save these notes
to Google Drive? Today, we will do both, by using intents and the Google Drive API.
Using intents in our Android app
So far, all of our applications have used one activity, which is basically one screen, and consists
of an XML file that contains all the elements that will be seen when the app is run, and a Java file
that describes how these different elements should function. Therefore, adding another screen
means creating another activity and a way for the activity we already have to access this. That is the job
of an intent, which is what we will be using in the onClick method of the save button.
Let's implement intents!
1) Right click on the src file, click new, and click activity
2) Make it a blank activity, and call it saveActivity
3) Make the layout name activity_save, the title Save, the hierarchial parent your mainActivity, and that Launcher Activity is unchecked
4) Go to the XML layout by going to the res file
5) Add a text view to Android screen, double-click it, and change the text to "Note Saved."
6) Go to the onClick method for the save button in the MainActivity.class file and declare a new intent that goes to your new activity by writing:
Intent saveIntent = new Intent(this, saveActivity.class);
If Intent is red, click it and hit alt+enter.
7) Now to go to the saveActivity.class file. In the onCreate method, receive the intent from your other activity by writing:
Intent thisIntent = getIntent();
Challenge
Create an intent for the Open Recent method that opens the latest note in another activity.