Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

12 February, 2020

Work around for Broadcast receiver not working in Chinese mobiles

If you're having trouble with your Android app not responding to certain events in Mi, Oppo, Vivo or Letv devices it's not your fault.
This could include and is not limited to, service app not working properly, push notifications not working properly, application not opening up when intended. 
It is because of the extensive battery saver and the so-called saving the user from apps spamming their activity.

Here's the funniest part about it

We wrote to someone very senior at Xiaomi. He reverted that they manually whitelist a few apps, and the rest are by default disallowed from accessing the notifications folder. This was the response. "This usually happens because of whitelisting of apps that can access notifications folder. This is a feature to ensure the user is protected from spam and also helps to ensure RAM/battery usage optimization." We asked what the process was to get an app whitelisted, and did not get a response.  

This is coming from a post about GCM push notifications not working on Mi devices here.
https://stackoverflow.com/questions/40814126/gcm-push-notifications-for-android-devices-are-not-working-on-mi-and-letv-mobile/40932178#40932178

Funny because Chinese mobile manufacturers like Xiaomi, Oppo and Vivo first flood their phones with bloatware nobody asks for and even shove their useless articles and sponsored apps to users and here we see them talking about how they want to protect the user from spam and RAM and battery consumption.

The only solution is to get extensive permissions from the user which will be done manually and cannot be programmed for easiness.
What all permissions?
First, we need a permission to auto-start the application and then the permission to display pop-up window. 
App Settings > Permissions > Auto-Start
App Settings > Other Permissions > Display Pop-up

The most convenient workaround is to ask the user to manually permit these setting and open the settings page for the end-user.
This can be done by making a settings button that opens up the settings page.

settings = (Button)findViewById(R.id.settings);
settings.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                Uri uri = Uri.fromParts("package", getPackageName(), null);
                intent.setData(uri);
                startActivity(intent);
            }
        });

Useful links if you'd like to explore more.


31 January, 2020

How to convert String To DateTime In Unity C#

How to fetch Day, Month or year from date time string?
How to get Hour, minute or second from a date time string?

Following snippet of code can be used to deal with most of the forms of date time string in Unity C#
Instead of having time in the form of
  "2020-1-31 12:10:15" 
you can also pass
"31/1/2020 12:10:15 PM"

and or any such case of Date time in string.
Then from this DateTime object you can fetch any particular detail like Year shown in example below.


System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("en-US");
DateTime tempDate = Convert.ToDateTime("2020-5-6 12:10:15", culture);
Debug.Log("Testing date time conversion: " + tempDate.Year);



This could be used to deal with date time strings of the form 
 "dd:MM:yyyy HH:mm:ss"
"yyyy:MM:dd HH:mm:ss"

20 January, 2020

How to dynamically create object using JSON data from REST API in Unity 3D

Over the years Unity has become all very powerful and not just easy. With it's easy to use interface and handy programming language C# it is one of the best possible IDE out there to make applications and not just games.

With the help of SimpleJSON and Unity Networking class you'll see how easy it is to handle web requests in Unity.

So today we are going to fetch and display data from REST API request. By displaying data I don't just mean showing the raw output of JSON but making the objects out of the response data which could be further used as per your requirement.

Let's get started.

First you need to make an API which will return some set of data. For example returning a user's friend list data will contain name, age, joining date of all their friends.
For creating an API you may follow my NodeJS tutorial

Once you have some API let's create a simple Unity application that will make a web request on Button click.
Go to a scene in Unity > Right click in the hierarchy and create a UI > Button.



Leave this be for now and let's create a script that will carry the function of this button.

In you 'Assets' folder create a new folder by the name 'Scripts' for keeping all our scripts.
Inside this folder right click and Create > C# script. Let's name this filer 'API.cs'

Inside API.cs create a method of a name of your choice which will start a coroutine upon call.

public void OnClickSendReq()
    {
        StartCoroutine(WebRequestCoroutine("parameter"));
    }


Now before we define this coroutine we first need to add support for Unity Networking.
Add 'using UnityEngine.Networking; in the beginning of the script.

Now we define our coroutine.
 IEnumerator UpdateReferredUsersList(string userId)
    {
        WWWForm form = new WWWForm();
        form.AddField("username", userId);

        using (UnityWebRequest www = UnityWebRequest.Post(APIURL, form))
        {
yield return www.SendWebRequest();
            if (www.isNetworkError || www.isHttpError)
            {
                Debug.Log(www.error);
               
            }
            else
            {
Debug.Log(www.downloadHandler.text);
}
}
}


This coroutine requires creates a web form using WWWForm and adds a form field 'username' with a value that is passed using the variable userId.

  WWWForm form = new WWWForm();
        form.AddField("username", userId);  


Then using UnityWebRequest we make a Post request on APIURL with the form.
  using (UnityWebRequest www = UnityWebRequest.Post(APIURL, form))

Then the response is handled in the next step.
Now we need to create Unity Game Objects using the data response from the API call. For that we first need to handle the data that is coming. In my case the response data is in JSON. 
To handle JSON data we'll be using a SimpleJSON. It is recommended to get it from the official website but in case you find it uncomfortable you may use a copy I uploaded to Github.

Now create a folder by the name 'Plugins' inside the 'Assets' folder and paste SimpleJSON file in there.


Now go back to editing API.cs and add 
  using SimpleJSON;
to the beginning.

Now in order to handle/parse the JSON data coming from our API response we need to create a Request object.
For this we'll be making a custom class. Add the following code to the extreme bottom of API.cs

public class RequestStatus
{
    public string status;
    public string msg;

    public static RequestStatus CreateFromJSON(string jsonString)
    {
        return JsonUtility.FromJson<RequestStatus>(jsonString);


    }

}


Now back to our coroutine inside the else block web request error checking add 

                int i = 0;
                while (i >= 0)
                {
                    string userExists= JSON.Parse(www.downloadHandler.text)["data"][i]["username"].Value;

                    if (
userExists  != "")
                    {
                                                   ListUserData(JSON.Parse(www.downloadHandler.text)["data"][i]["first_name"].Value,
                            JSON.Parse(www.downloadHandler.text)["data"][i]["username"].Value,
                            JSON.Parse(www.downloadHandler.text)["data"][i]["email"].Value
                        i++;
                    }
                    else
                    {
                        i = -1;
                    }
                }

This block of code will loop through all the data under 'data'  you might have to modify 
  JSON.Parse(www.downloadHandler.text)["data"][i]["username"].Value; 
according to the response of you API.

Now to create objects using the response data we called a method with the values of individual set of data.
In this method ListUserData we will instantiate a prefab that will hold the data of individual set.

Create a new method within the else block

                void ListUserData(string username, string email)
                {
                    Debug.Log("Listing users data by instantiating prefab!");
                    GameObject listingObject= Instantiate(userlistPrefab, userlistContainer);
                    UserListing userListing= 
listingObject.GetComponent<UserListing>();
                    userListing.PopulateUserData(username, email);

                }


Now this method will instantiate a prefab 'userlistPrefab' as a child object of 'userlistContainer'. 
We don't just want to instantiate an object but want the data to be displayed on this object. For this we will create a new class 'UserListing' which defines the listing object structure and will have a method 'PopulateUserData' for updating the values of the object.

Head back to Unity and inside Assets > Scripts > Create a new C# script UserListing.

Now inside UserListing 

using UnityEngine.UI;
public class UserListing : MonoBehaviour
{
    [SerializeField]  private Text username;
private string email;

public void PopulateUserData(string usernameInput, string emailInput)
    {
        username.text = usernameInput;
        email = emailInput;
    }
}


Now let's create our userListingPrefab to which UserListing class will be applied to.
To create a prefab head back to the scene in Unity and create an Empty GameObject 'UserScrollRect' inside the Panel.
There must a Panel under the Canvas already if you created a button in the very beginning of this tutorial.
If it is not there create a button now and redo the above step.
In the Inspector tab of UsersScrollRect click Add Component and add a Scroll Rect(script).
Uncheck Horizontal.



Now create a child object to UsersScrollRect by the name UserDataContainer which will hold all the prefab object we'll create next. Stretch and set position UserScrollRect according to your need. 
Add Vertical Layout Group (Script) to UserDataContainer.


Under UserDataContainer create a child object, preferably a UI > Image
Stretch it according to your need and Add a UI > Text Object to it. This will be carrying the username from the script.
Add UserListing script to UserListing Object.


Drag and drop Username text object in the blank field against Username in the script properties. In my case it says Name Text as this screenshot was taken later. So I hope this will not confuse anyone.

Once added drag and drop the UserListing object from Hierarchy to Prefabs folder in Project tab.

Create a new Empty Game Object, let's name it 'WWW' and attach API.cs we created above.
Add 
    [SerializeField] private GameObject userListingPrefab;
    [SerializeField] private GameObject UserInformationPanel;


to API.cs and drag and attach the prefab we created.
For the UserInformationPanel game object we have to add UserDataContainer we created above.

Open the inspector tab of our button and add  OnClickSendReq to be executed on click.


You might have to set up the objects hierarchy according to your need. I'll leave that to you.

Feel free to leave a comment if you need any help with this.








13 January, 2020

How to upload your project to Github

So you're writing all kind of codes now and you want to collaborate with other developers in your team or just simply want to back up your precious code.

There are a number of ways to do it. You could simply just a make a zip out of your project and upload it to one of the cloud storage you got. Or you could do use something that is meant for storing codes. One such service is all popular Github.

I'll leave the explanation of Github for some other day and get into business right away.

What we want to do?
We want to upload our project to a repository on Github so that anyone else or just ourselves could download it later on, or sync with our different computers.

How?
Following steps will guide you through it.

Step 1. First we need a Github account.
Go sign up here https://github.com/ and come back for more.

Step 2. We need to setup our computer such that we don't have to provide our username password every time we sync our project.
This is done using Secure Server Host(SSH)
We generate a SSH key and pass it to Settings > SSH Keys > Add Key on Github.

Before we generate SSH key let's first check if we don't already have one. Download and install GitBash if not done already.

Enter

$ ls -al ~/.ssh

to list all the keys. Source: https://help.github.com/en/github/authenticating-to-github/checking-for-existing-ssh-keys

if you see any key listed like

$ github_rsa github_rsa.pub id_rsa  id_rsa.pub known_hosts

That means you already have a ssh key. If this is your case skip to next step.
If you don't have a key, let us generate one.

You'll need a program called SSH-Keygen or OpenSSH.
Once downloaded and installed open CMD and run the following command.

$ ssh-keygen -t rsa -b 4096 -C "yourEmail@example.com"

After this you'll see something like this

Generating public/private rsa key pair.
$ Enter file in which to save the key (/home/username/.ssh/id_rsa):[Enter Name or leave blank]

You may enter a name for your SSH key or leave it blank for the default.
You may add a passphrase to this key if you want. I left it blank for a sake of easiness.

You'll see something like this after this step

Your identification has been saved in /home/username/.ssh/id_rsa.
Your public key has been saved in /home/username/.ssh/id_rsa.pub.
The key fingerprint is: /////something here/////
yourEmail@example

You've successfully generated you SSH key.
Source: https://help.github.com/en/github/authenticating-to-github/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent

Step 3. Now we need to copy this key and provide it to our Github Settings.
To copy your key run following command in CMD

$ pbcopy < ~/.ssh/id_rsa.pub

Where 'id_rsa.pub' is the name of the SSH key. In case you changed it in Step 2. you'll have to change it here as well.

Step 4. No head over to https://github.com/login
 Click on your profile picture on top-right and go to Settings.
 Under settings you'll find SSH and GPG keys, click that.
 Then in the next page that loads click "New SSH key" paste your key and save.

Step 5. Open Gitbash in the project folder you want to create a repository of.

> enter
$ git init

> enter
$ git all --all

> enter
$ git commit -m "Pushing to Git Repo"

Step 6. Now head over to Github and create a new repository.
https://github.com/new
Enter name of you repository, set private or public and click "Create Repository"
Copy the repository address and head back to GitBash we left in Step 5.

Step 7. We have our Git Repository address copied to our clipboard.

> enter
$ git remote add origin

> right click
$ git remote add origin git@github.com:userName/projectTitle.git

> enter
git push origin master

That's it. Now head over to your Github profile and check out your newly created repository.





09 January, 2020

How to make NodeJS MongoDB REST APIs for CRUD operations


We'll use NodeJS Express framework for developing the web-interaction part and Mongoose for saving data to MongoDB. We'll be saving just two details name, and email of a user. Since I'll be logging in users with their email id only which is validated by Facebook in Facebook Social Login.

Install NodeJS and make a folder where your application will run from. This folder is production NodeJS server equivalent on Windows PC.

Step 1: Having installed NodeJS now open Command Prompt Window in the folder.

Quick Shortcut > Open the folder and click and type 'CMD' or 'cmd' in address bar.

Step 2: Initialize the application with a package.json file.
Run following command in the command prompt window,
$ npm init

name: (userdb)
version:
description: enter description
entry point: server.js
test command:
git repository:
keywords:
author: Your Name
license: 

Check details and type 'yes' to proceed.

Now our package.json is initialized and can be found in our project folder.

Note that we defined the entry point of our application as server.js so we'll make a file with the name 'server.js' had we left that blank the default name would have been 'index.js'

Create new file next to package.json by the name 'server.js', leave it blank for now we'll come back to it later.

Step 3: Installing dependencies
Now we'll install support for Express, body-parser and Mongoose for application to use it.
Run folowing commands in CMD
$ npm install express body-parser mongoose --save

Using '--save' at the end saves all the dependencies in the package.json file.

Now if you'll take a look at our project folder you'll see another folder by the name 'node_modules'.

Now let us setup our web server by editing the 'server.js' we created in Step 2.

Step 3: Open 'server.js' and define the main entry point to our application.

server.js

const express = require('express');
const bodyParser = require('body-parser');

// constant app will represent our application
// since app is based on express
const app = express();

//parses requests of content-type - application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({extended: true}))

//parses requests of content-type -application/json
app.use(bodyParser.json())

//defining a route to our application
app.get('/', (req, res) => {
res.json({
"message": "Nothing here, try making some API request."
});
});

//listening to requests
app.listen(3000, () => {
console.log("Server running at port 3000!")
});

Here, Express is a web framework that we are using to build REST APIs and body-parser is a module that parses the requests and creates req.body object that we can use in out routes.

Then we define a route to our application that addresses get request to the naked url and responds with a message. We'll alter this message with more helpful data later.

Finally we listen on port 3000 for incoming connection requests.

Let's fire up out server by calling

$ node server.js

You may visit http://localhost:3000/ to check whether it is running or not.

Step 4: Now let us configure our database.
Let's create new folder 'config' in out apps root folder where we'll be keeping all our configuration information separate.
Inside the 'config' folder create a new file 'db.config.js' with following contents-

module.exports = {
url: 'mongodb://localhost:27017/db0'
}

Now to import this 'db.config.js' file in 'server.js' and use it with 'mongoose'

//database congiguration
const dbConfig = require('./config/db.config.js');
const mongoose = require('mongoose');

mongoose.Promise = global.Promise;

//connection to database
mongoose.connect(dbConfig.url, {
useNewUrlParser: true
}).then(() => {
console.log('Connected to database');
}).catch(err => {
console.log('database connection failed...');
process.exit();
});

Re-run the server to check if the database is being connected.

$ node server.js

To remove the deprecation warning
"(node:8076) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor."

Just add ', useUnifiedTopology: true' after 'useNewUrlParser: true' so our 'server.js' is now

server.js

const express = require('express');
const bodyParser = require('body-parser');

//database congiguration
const dbConfig = require('./config/db.config.js');
const mongoose = require('mongoose');

mongoose.Promise = global.Promise;

//connection to database
mongoose.connect(dbConfig.url, {
useNewUrlParser: true, useUnifiedTopology: true
}).then(() => {
console.log('Connected to database');
}).catch(err => {
console.log('database connection failed...');
process.exit();
});

// constant app will represent our application
// app is based on express
const app = express();

//parse requests of content-type - application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({extended: true}))

//parse requests of content-type -application/json
app.use(bodyParser.json())

//defining a route to our application
app.get('/', (req, res) => {
res.json({
"message": "Nothing here, try making some API request."
});
});

//listening to requests

app.listen(3000, () => {
console.log("Server running at port 3000!")
});

Re-run the server warning should be gone now.

Quick Tip: The MongoDB database we just created can be viewed using MongoDB Atlas Applcation and passing the address 'mongodb://localhost:27017/db0' which we defined in 'db.config.js' file.

Step 5: Now we have our NodeJS application running with database connected. To save data to our MongoDB we will define a structure that will be followed for the data. We call this model. You can define more that a single type of model.

Create a new folder in the root directory of our application as 'app' and another folder inside 'app' as 'models'. Inside 'models' create a file by the name 'user.model.js'
Now we define what our user's properties are. Inside 'user.model.js' enter content-

user.model.js

const mongoose = require('mongoose');

const UserSchema = mongoose.Schema({
name: String,
email: String
}, {
timestamps: true
});

module.exports = mongoose.model('User', UserSchema);


Since I'll be logging and registering users using their Facebook login I defined only two string fields 'name' and 'email' which can be easily requested from Facebook login.

Also adding 'timestamps: true' will add two field 'createdAt' and 'updatedAt' which can be useful in their own way if required.

Step 6: Now we will define various routes for the APIs.
Create a new folder inside 'app' by the name 'routes'. Inside this folder we'll create a file 'user.route.js' with the content-

user.route.js

module.exports = (app) => {
var controller = "../controllers/user.controller.js";
const users = require(controller);

//create a new user
app.post('/registeruser', users.create);

//get all users' information
app.get('/allusers', users.listAll);

//get single user with userId
app.get('/users/:userId', users.findOne);

//update a user with userId
app.put('/users/:userId', users.update);

//delete a User with userId
app.delete('/users/:userId', users.delete);

}

Note that we have defined a variable controller which points to an address of 'user.controller.js' file which we will define in next step.
Before that let's first include 'user.route.js' in our 'server.js' file.
Add the following lines of code before 'app.listen()' method inside 'server.js'

//require Users routes
require('./app/routes/user.route.js')(app);


Step 7: Now let's define our 'user.controller.js' that our 'user.route.js' depends on.
Create a new folder by the name 'controllers' inside 'app' folder. Inside this create a new file 'user.controller.js' with following contents.

user.controller.js

const User = require('../models/user.model.js');

//register a new user
exports.create = (req, res) => {

};

//get all users' data
exports.listAll = (req, res) => {

};

//find single user with userId
exports.findOne = (req, res) => {

};

//update a user's information base on userId
exports.update = (req, res) => {

};

//delete user with userId
exports.delete = (req, res) => {

};

Now we will implement these individual methods

For registering a new user

//register a new user
exports.create = (req, res) => {

//validate the request
if (!req.body.email) {
return res.status(400).send({
message: "User email id cannot be empty"
});
}

//register a user
const user = new User({
name: req.body.name || "not defined",
email: req.body.email
});

//save the user information in database
user.save().then(data => {
res.send(data);
}).catch(err => {
res.status(500).send({
message: err.message || "Something went wrong while registering new user.."
});
});
};


For getting all users' data

//get all users' data
exports.listAll = (req, res) => {
User.find().then(users => {
res.send(users);
}).catch(err => {
res.status(500).send({
message: err.message || "Something went wrong while getting all information"
});
});
};

For getting single user's information

//find single user with userId
exports.findOne = (req, res) => {
User.findById(req.params.userId).then(user => {
if (!user) {
return res.status(404).send({
message: "user not found with id " + req.params.userId
});
}
res.send(user);
}).catch(err => {
if (err.kind === 'ObjectId') {
return res.status(404).send({
message: "User not found with id " + req.params.userId
});
}
return res.status(500).send({
message: "Error getting user data with userId: " + req.params.userId
});
});

};

Updating a user's information

//update a user's information base on userId
exports.update = (req, res) => {
//validate request
if (!req.body.email) {
return res.status(400).send({
message: "Email ID cannot be left blank"
});
}
//find user by userId and update its name and email
User.findByIdAndUpdate(req.params.userId, {
name: req.body.name || "not defined",
email: req.body.email
}, {
new: true
}).then(user => {
if (!user) {
return res.status(404).send({
message: "User not found with userId " + req.params.userId
});
}
res.send(user);
}).catch(err => {
if (!user) {
return res.status(404).send({
message: "Error updating user with id " + req.params.userId
});
}
return res.status(500).send({
message: "Error updating user with id " + req.params.userId
});
});
};


Deleting a user based on userId

//delete user with userId
exports.delete = (req, res) => {
User.findByIdAndRemove(req.params.userId).then(user => {
if (!user) {
return res.status(404).send({
message: "User not found with id " + req.params.userId
});
}
res.send({
message: "User deleted successfully!"
}).catch(err => {
if (err.kind === 'ObjectId' || err.name === 'Not Found') {
return res.status(404).send({
message: "User not found with id " + req.params.userId
});
}
return res.status(500).send({
message: "Could not delete user with id " + req.params.userId
});
});
});


In order to test you API you can use Postman. Screenshot attached below for registering a new user.



http://localhost:3000/allusers will retrieve all the data from database.

In the next part I'll be making a login and registering pages and push the database and server to production.

You can find the whole project on GitHub
https://github.com/ixabhay/ludoDB
This also contains lots of content that is up there in the post including a way to register a user and check their information for login.
Hope it helps.

10 June, 2019

Making Sensor Lights in Unity 3D

Lighting in Unity 3D can some times get tricky. I just spent hours into making sensor lights only to come up with a very obvious solution.
At first, I was using baked maps which were the primary reason for my trouble.

I know it's kind of obvious but I need to state it for anyone who is struggling with the same.

Don't use Baked Lightmaps if you want real-time illumination.

As simple as that. I even considered lighting up the environment by real-time switching different lightmaps. Thanks to the complexity of such task I didn't do it.

Finally, the solution was to use simple point lights. To give the lights better look I used emissive materials.

Here are the results.

    

Here's how I did it.


  • Created an empty Gameobject Light Controller and under that created two small cuboid, LightsOn and LightsOff and a point light called Bulb here.
  • Added a box collider in Light Controller and ticked Is Trigger.
  •  
Here's the script attached to the Light Controller.


public class LightsOn : MonoBehaviour
{
    public GameObject lightOn, lightOff, light;
    private bool lightsOn = false;

    private void OnTriggerEnter(Collider other)
    {
        if(other.tag == "Player" || lightsOn == false)
        {
            lightOn.SetActive(true);
            lightOff.SetActive(false);
            light.SetActive(true);
        }
    }

    private void OnTriggerExit(Collider other)
    {
        if (other.tag == "Player" || lightsOn == true)
        {
                lightOff.SetActive(true);
                lightOn.SetActive(false);
                light.SetActive(false);

        }
    }

}


What this script does is, take checks if the Player enters the trigger collider and enables lightsOn object and bulb(light) and disables lightsOf object and bulb(light) and vice versa.

I also created two emissive materials with the following the property. They're just new material with albedo set to white and HDR Color set to white in lit up light(cuboid object above) and Black in dim light.

 

In case my naming of objects and variables is causing any confusion, there is two sources of light in this, cuboid and a point light. Originally I wanted to just light up the room using cuboid with emissive material but that doesn't work in real time lighting as they need to be baked. So I ended up using a point light to illuminate the room in real time and cuboid with emissive material to make it look better.

Hope this helps anyone looking into sensor lights. In case of any query feel free to comment below.


18 June, 2017

Java Programming Basics to Brilliance Part 3

This post is a progression to previous post Java Programming Basics to Brilliance Part 2.



Before we make things complicated lets first get to know what is an array and how we can use it.

Quoting from Google,
array
əˈreɪ/
noun
  1. 1.
    an impressive display or range of a particular type of thing.
    "there is a vast array of literature on the topic"
verb
  1. 1.
    display or arrange (things) in a particular way.


In Java, an array is an object which holds a specified number of similar number, strings or objects. This depends on the type of array you are making.
The size of an array is set when it is initialized.
For e.g.
 int listOfNumbers[] = {1,2,3,12,2};

This is one way of making an array with values in it.
Now recall how everything in Java is nothing but an object. Considering that you can also make a blank array as follows:

String myHeroes[] = new String[5];

Now the above line of code initialized a blank array of String type of length 5.
Note that this array is of type String, so you cannot feed values other than String into it.
Let's feed some values into this array.

myHeroes[0] = "Lanaya";
myHeroes[1] = "Lina";
myHeroes[2] = "Rylai";
myHeroes[3] = "Mercurial";
myHeroes[4] = "Lyralei";

Now that we have an array of numbers listOfNumbers and an array of string myHeroes now obviously if we want to make use of this array we need a way to access these values. 
To do that we loop through the array and do whatever we want accordingly.
But before we loop through an array take note of how the length of array myHeroes is 5 but we added values up to myHeroes[4] only. This is simply because array index starts from 0 not 1 and that makes the size of array as 5.

To further clear up the confusion you can use 
arrayName.length; to find out the length of the array.

For e.g.

         System.out.println(myHeroes.length);


Now back to looping.
The simplest and easy to understand form of loop is a for loop. And once you understand for loop there another version of it called foreach loop which is really handy and saves lots of confusion.

for loop

for(int i=0; i<10; i++){
            System.out.println(i);
}

This simple loop will print numbers 1 to 9. How?

You can see the above for loop defined as follows

for(initial values; condition checking; update){
//loop body that executes if condition check is true
}

Now the update part of for loop need not necessarily be increment only. You can instead decrease the values, divide, multiply etc.
Rest should be pretty much self explanatory.
Lets use this loop to print the list of heroes we made.

         for(int i=0; i<myHeroes.length; i++){
            System.out.println(myHeroes[i]);
}

Notice how we ran the loop for values starting with to to just less than the length of array. Explained above.

Now a rather simplified version of for which is foreach loop.
For the array myHeroes[]
we can print the array values using for each as follows:

 for(String i: myHeroes){
            System.out.println(i);
        }

Think of foreach loop as defining a variable i that will be holding values from the array one by one.

To better understand this looping consider following lines of code

for(typeOfValuesInArray variableName: arrayName){
variableName; //this will access all of the values inside the array one by one in the order
}
Having done all that lets move to a fairly complex yet very useful part of Java called Collection.

Collection.

Collection are a way for storing objects in Java.
Collection provide necessary features which help in ordered storage of data and easier manipulation of the same.
There are various collection interfaces in Java predefined and you can create you own collection as well.
Namely, there is
List,
ArrayList, Vector,
Queue,
LinkedList, PriorityQueue,
Set,
Sorted Set, TreeSet, HashSet, LinkedHashSet,
Map,
HashTable, HashMap, LinkedHashMap, and TreeMap.

Various Collections

Various Map Collection

Unless you are giving some exam there is no absolute need for remembering all the names.
For the sake of this tutorial and get going with Java Programming I will be using just the ArrayList with reference of List collection and might cover others in future.

Consider the program below:

import java.util.ArrayList;
import java.util.List;

public class ListExample {




public static void main(String[] args) {

List<Dog> dogsList = new ArrayList<Dog>();

String dogName;

int dogId;

for(int i=0; i<10; i++){

dogName = "Dog"+Integer.toString(i);

dogId = i;

dogsList.add(new Dog(dogId, dogName));

}

for (Dog dog : dogsList) {

System.out.println(dog.getDogId());
System.out.println(dog.getDogName());

}

}

}





Different type of collection have different properties and usefulness in their domain. Deciding the right collection depending on the requirement is something that affects your application thoroughly. I will leave that you as it requires research depending on the requirement and even I'm not all aware of all of the collections. 

That's all for now. If you go through these 3 tutorials on Java you are likely to get through anything. I'm not entirely sure what will be next in this but in case I do write it will be updated here.
Keep Coding...

Featured Post

Content Writing VS Content Marketing: How are Both Different From Each Other?

Regardless of how long the businesses have been introduced to digital marketing, it is often seen that they confuse the terms of marketing. ...