Create audio player app in 10 minutes

Create audio player app in 10 minutes

Welcome to hiewpoint, In this post you’ll learn how to use MediaPlayer Api to build a simple audio player app. By creating this app you’ll learn some basic concepts of MediaPlayer Api and AudioManager.
So what’s MediaPlayer and AudioManager? If we want our app to play video and sound then we need to use these two above mentioned.
MediaPlayer: This class is the primary API for playing sound and video.
AudioManager: This class manages audio sources and audio output on a device.Lets get started in building an app with Mediaplayer in android studio.


First setup the project with an empty activity and give it any preferred name.
In the activity_main.xml copy this below code.

Audio player app activity_main.xml

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:orientation="vertical"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/holo_green_dark"
        android:onClick="playMe"
        android:text="@string/play"
        tools:text="@string/play" />

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/holo_red_dark"
        android:onClick="pauseMe"
        android:text="@string/pause"
        tools:text="@string/pause" />

</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    app:layout_constraintTop_toTopOf="parent"
    android:layout_marginTop="24dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent">

    <SeekBar
        android:id="@+id/seekBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Volume" />

    <SeekBar
        android:id="@+id/timeline"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="TimeLine" />
</LinearLayout>

We have a playMe button and PauseMe button. Ofcourse play and pause are essential in any audioplayer app, we also have two seek bar to control the volume and timeline of audio.
Now copy these below lines of code in MainActivity.java

Audio player app MainActivity.java

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.SeekBar;
import java.util.Timer;
import java.util.TimerTask;
MediaPlayer mediaPlayer;
AudioManager audioManager;

public class MainActivity extends AppCompatActivity {
public void playMe(View view){
    mediaPlayer.start();

}

public void pauseMe(View view){

    mediaPlayer.pause();
}



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

    mediaPlayer = MediaPlayer.create(this, R.raw.myaudio);

    //Getting context from Audio Service
    audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
    int myMaxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
    int myCurrentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);

    //Setting context values to Seekbar
    SeekBar volumeRocker = (SeekBar) findViewById(R.id.seekBar);
    volumeRocker.setMax(myMaxVolume);
    volumeRocker.setProgress(myCurrentVolume);


    //Set on change listener

    volumeRocker.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 0);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    });


        //Setting a player timeline

    final SeekBar timeline = (SeekBar) findViewById(R.id.timeline);
    timeline.setMax(mediaPlayer.getDuration());

    new Timer().scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            timeline.setProgress(mediaPlayer.getCurrentPosition());
        }
    }, 0, 1000);


    timeline.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            mediaPlayer.seekTo(progress);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    });

}

}

Conclusion

So basically we first create instance of MediaPlayer and AudioManager and instantiate them in oncreate() as mediaPlayer=MediaPlayer.create(this,R.raw.myAudio);
audioManager=(AudioManager)getSystemService(Context.AUDIO_SERVICE); here we get the audio service in order to play the audio.

Inside the onClick methods of both the button consists of mediaPlayer.start() to start the audio and mediaPlayer.pause() to pause the audio.

In order to control the volume rocker we need to set current stream and max stream and assigned to two different variables. These two variables are used in seekbar(volume rocker).

volumeRocker.setMax(myMaxVolume);
volumeRocker.setProgress(myCurrentVolume);

To control the volume seekbar ,a seekbarChangeListener is added which listens to the movement of seekbar(volume rocker), inside the onProgressChanged(….) we added this audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 0);

So that when user slide the seekbar it sets that current value to it.Similar to this seekbar ,another seekbar is created which listens to the timeline of audio and it uses mediaPlayer.seekTo() method to seek the audio wherever user slides.

Output

After implementing the source code in-place and properly, Your app will appear similar to this ! however you can easily edit the background color and button color. For any doubt comment on our post or send us a message on social media to get cleared instantly. Try some more modifications in this audio player app and wait for our next article. Happy coding !

Create audio player app  in 10 minutes

Thank you for reading this post. Follow us on Instagram and Facebook.


To know more tips and tricks you can follow articles on this category :
https://blog.hiewpoint.com/off-topic/

To know about web development and WordPress follow
https://blog.hiewpoint.com/web/

To know about Android development and Android Studio follow
https://blog.hiewpoint.com/android/

Use API in android app in just 7 simple steps

Use API in android app in just 7 simple steps

In this post you will learn about API’s and how to fetch live data from the internet and provide data within your android app.

After following this post ,you would be able to implement any API within your app which would be useful for your large scale application. We will use openweathermap API in this tutorial. So let’s get started but wait do you know what is an API? If not then don’t worry I’ll explain you what is an API and I promise that you will not again search for what is an API?

What is an API

According to Wikipedia ,In computer programming, an application programming interface is a set of subroutine definitions, communication protocols, and tools for building software. In general terms, it is a set of clearly defined methods of communication among various components. A good API makes it easier to develop a computer program by providing all the building blocks, which are then put together by the programmer.

Not yet clear what is an API? We’ll break it down for you.

So basically it is an intermediary software that allows two applications to talk to each other. For example , You want to book your air ticket from indigo. Now you may go to the indigo website and book it. But how many of  us does that? Very rarely we do that. We use third party services like MMT ,Paytm etc.. So developers use this to get data from main server or for much more additional features.

Another example ,You login/signup to different websites that gives various options to you to sign up to their website. That may include Facebook ,google signup etc…

Get your API key

To start using application programming interface services of any organization ,we need to register and get the key from them. In this tutorial we’ll use openweathermap .

Get the API key by registering to openweathermap. The key is a unique identifier to the API provider. Follow the documentation there and get started.

You need to follow the guides properly as you need to understand what the provider provides ,So that you could use it in your application to display live data.

Let’s Code

Open Mainfest.xml and give it a permission to internet service as we are going to use internet service in app.

Copy the below code in activity_mamin.xmlm

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/winter"
    tools:context="com.example.studio.myweatherapp.MainActivity">

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="24dp"
        android:fontFamily="cursive"
        android:text="Get Weather"
        android:textColor="@android:color/background_dark"
        android:textSize="50sp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/getCity"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="16dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Paris"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView2" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="24dp"
        android:background="@color/colorAccent"
        android:paddingBottom="10dp"
        android:paddingLeft="30dp"
        android:paddingRight="30dp"
        android:paddingTop="10dp"
        android:text="Get that"
        android:textColor="@android:color/background_light"
        android:textSize="20sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/getCity" />

    <TextView
        android:id="@+id/result"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="24dp"
        android:text="TextView"
        android:textSize="20sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button"
        tools:layout_editor_absoluteY="234dp" />
</android.support.constraint.ConstraintLayout>

We are going to perform network request using volley library. Why volley? Because its simple and convenient unlike using asynctask request. Using volley we don’t need to worry about UI thread etc..

 In order to perform network request we need some boiler plate codes which performs the request. We need not worry about how that code works as it is a boiler plate code .It’s just needed in order to use volley. So copy these below lines of code in a class and named it as mySingelton.java .

If you are not familiar with volley then I would recommend to first learn about volley. We already have a post on volley ,So have a look on that.

package com.example.studio.myweatherapp;

import android.content.Context;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;


public class MySingleton {

    private static MySingleton mInstance;
    private RequestQueue requestQueue;
    private static Context mCtx;

    private MySingleton(Context context){
        mCtx = context;
        requestQueue = getRequestQueue();
    }

    public RequestQueue getRequestQueue(){
        if(requestQueue==null){
            requestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
        }
        return requestQueue;
    }

    public static synchronized MySingleton getInstance(Context context){
        if(mInstance==null){
            mInstance = new MySingleton(context);
        }
        return mInstance;
    }

    public void addToRequestQue(Request request){
        requestQueue.add(request);
    }
}

NOTE: The url which will be requested using mySingleton is JsonObjectRequest  and jsonobjectrequest must have a url with api So the url must be something like this baseUrl+city+API key.

Copy these in MainActivity.java

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

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends AppCompatActivity {

    Button button;
    EditText city;
    TextView result;

    //http://api.openweathermap.org/data/2.5/weather?q=Paris&appid=5f56d525d1619d0a2cd2eac4ce55588e

    String baseURL = "http://api.openweathermap.org/data/2.5/weather?q=";
    String API = "&appid=5f56d525d1619d0a2cd2eac4ce55588e";

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

        button = (Button) findViewById(R.id.button);
        city = (EditText) findViewById(R.id.getCity);
        result = (TextView) findViewById(R.id.result);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String myURL = baseURL + city.getText().toString() + API;
                //Log.i("URL", "URL: " + myURL);

                JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, myURL, null,
                        new Response.Listener<JSONObject>() {
                            @Override
                            public void onResponse(JSONObject jsonObject) {
                                Log.i("JSON", "JSON: " + jsonObject);

                                try {
                                    String info = jsonObject.getString("weather");
                                    Log.i("INFO", "INFO: "+ info);

                                    JSONArray ar = new JSONArray(info);

                                    for (int i = 0; i < ar.length(); i++){
                                        JSONObject parObj = ar.getJSONObject(i);

                                        String myWeather = parObj.getString("main");
                                        result.setText(myWeather);
                                        Log.i("ID", "ID: " + parObj.getString("id"));
                                        Log.i("MAIN", "MAIN: " + parObj.getString("main"));
                                    }


                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }




                            }
                        },

                        new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError volleyError) {
                                Log.i("Error", "Something went wrong" + volleyError);

                            }
                        }


                );
                MySingleton.getInstance(MainActivity.this).addToRequestQue(jsonObjectRequest);

            }
        });
    }
}

Lets see what is exactly happening in the MainActivity.java

  • First we set the base url from where we want to fetch the data and API key of your registered one.
  • Then when a user enters a city name ,an url is set up as to request (GET) and get the JSON data from the url by using JsonObjectRequest ,this returns the data inn JSON Onject format something just like this,

JSON: {“coord”:{“lon”:2.35,”lat”:48.86},”weather”:[{“id”:801,”main”:”Clouds”,”description”:”few clouds”,”icon”:”02d”}],”base”:”stations”,”main”:{“temp”:283.58,”pressure”:1034,”humidity”:77,”temp_min”:282.15,”temp_max”:285.93},”visibility”:10000,”wind”:{“speed”:2.6},”clouds”:{“all”:20},”dt”:1553599943,”sys”:{“type”:1,”id”:6540,”message”:0.0052,”country”:”FR”,”sunrise”:1553578899,”sunset”:1553623857},”id”:2988507,”name”:”Paris”,”cod”:200}

  • We take the necessary data which we want and leave other. In this e xample app we take only the main inside of weather Array of objects.
  • Finally we request the volley to get the data from the server. This is achieved by using,
MySingleton.getInstance(MainActivity.this).addToRequestQue(jsonObjectRequest);

The app would have an output like this,

Thank you for reading this post. Follow us on Instagram and Facebook.


To know more tips and tricks you can follow articles on this category :
https://blog.hiewpoint.com/off-topic/

To know about web development and WordPress follow
https://blog.hiewpoint.com/web/

To know about Android development and Android Studio follow
https://blog.hiewpoint.com/android/

images

How To Fetch A Webpage Using Volley

In this post you’ll be learning about volley ,an android library and how to use it to fetch data from internet. It’s a library used for networking. Click this https://developer.android.com/training/volley to see what official android developers website tells about volley.  This is only a basic example of volley.

Follow these steps to setup the app for volley

  • After creating a empty project in Android Studio,go to the gradle       dependencies and add the volley dependencies from this link https://developer.android.com/training/volley
  • We are going to fetch a webpage on button press, for this we would need internet permissions. So under manifests define internet permission.
<uses-permission android:name="android.permission.INTERNET" />

Now lets dive into the coding part

Copy this into your activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.studio.volleyone.MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

It would look something like this,

volley

Copy this into MainActivity.java

package com.example.studio.volleyone;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

public class MainActivity extends AppCompatActivity {

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

        final String myURL = "http://www.facebook.com";

        Button myButton = (Button) findViewById(R.id.button);

        myButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);

                StringRequest stringRequest = new StringRequest(Request.Method.POST, myURL,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String s) {
                            Log.i("PAGE", "WEB " + s);
                            }
                        },
                        new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError volleyError) {
                                Log.i("ERROR", "ERROR is " + volleyError);
                            }
                        }
                );

                requestQueue.add(stringRequest);
            }
        });



    }
}

In MainActivity.java, we are assigning a click listener on button and on button pressed ,it requests the webpage. So let’s see how the request is done.

An HTTP has many methods such as GET, PUT , CONNECT ,POST… , In example app the method  to request data from server is POST.

RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);

                StringRequest stringRequest = new StringRequest(Request.Method.POST, myURL,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String s) {
                            Log.i("PAGE", "WEB " + s);
                            }
                        },
                        new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError volleyError) {
                                Log.i("ERROR", "ERROR is " + volleyError);
                            }
                        }
                );

                requestQueue.add(stringRequest);
            }
        });

The above piece of code is to request, when button is pressed. Volley.newRequestQueue is assigned to an instance of RequestQueue in which all the requests are held in a queue. Then a StringRequest requests the url with the POST method and if it is successful then onResponse() is executed else onErrorResponse  is executed.

Now after running your app , click on the button and go to logcat and from dropbox choose info and type PAGE .If the request was successful then the xml format of web page could be seen in logcat else an error occurred while fetching web page ,in that case cross check your url. It would look something like this,

volley

Thus fetching a web page using volley is done in this way. This was just a basic example of volley ,there’s more to learn about volley. Visit developers official site or just keep calm and stay tuned with us ,We will post more advanced example on volley.

Thank you for reading this post. Follow us on Instagram and Facebook.


To know more tips and tricks you can follow articles on this category :
https://blog.hiewpoint.com/off-topic/

To know about web development and WordPress follow
https://blog.hiewpoint.com/web/

To know about Android development and Android Studio follow
https://blog.hiewpoint.com/android/

5 Mistakes Every Beginner Make While Coding

5 Mistakes Every Beginner Make While Coding

Do you feel anxious and doubtful about your coding? Do you worry about how you are writing the codes?

This feeling seems to be exist in almost many of the coders/developers in their beginning phase. I also had this phase and it’s unlikely to change as we do sometimes feel insecure of our codes and it’s completely ok!

But , If you are a beginner in coding  then you should take care of some things which are very important for you to stay productive.

Hi My name is Manuj Sharma . I’m an Android and Web developer. In today’s post I will highlight  some key points to always keep in the mind while coding. I will tell you the 5 mistakes you probably doing it all the time while learning to code.

5 MISTAKES THAT YOU COULD BE DOING WHILE LEARNING HOW TO CODE.

NOT CHOOSING THE PERFECT IDE/COMPILER

Yeah it seems to be kiddish but that’s the truth. Many of  the guys code it in a compiler which is not idle. Let me make you understand by an example , Do you remember the old C/C++ language being code in Turbo C/C++? It’s not an idle compiler for that language. It’s a very old compiler but many of the universities/school still use them and that is where people go wrong. There are many other new IDE’s launched where we could code C/C++ and would save a lot of time as it would suggest you with code hints, more handy etc..

So have some research about the programming language which you are about  to get started with it and know it’s best IDE being used.

NOT CHOOSING A MENTOR

Learning on your own is a good thing and it has its own benefits but sometimes its necessary that you need a expert who could walk you through with your journey and also help you when your stuck. If you don’t want to opt for a mentor then at least learn from online tutors or courses as it will save your lot of time and thus increasing your productivity.

NOT BUILDING PROJECTS

It’s good to hear that you are learning how to code. You are solving programs on daily basis but wait are you even building projects ,applying those acquired skills to any framework? For instance if you learnt java for few months and now you know all the ins and outs of it but what you are going to do with that skill? So you need to research where JAVA could be used? The answer is simple ,you could make mobile applications , software applications and much more. So start with building projects now and apply your acquired skills. Building “projects” is the most essential part in mastering any skill.

If you feel that I can’t be building the projects only in a single stream as I want to learn other skills too, then follow my simple strategy – Build atleast 5 projects and then you are ready to go. By that I mean that 5 good projects which should involve CRUD operations and many more.

NOT BEING SOCIALLY ACTIVE IN PROGRAMMING/CODING COMMUNITY

You are coding day and night , you are building stuffs , that’s good and you should do that but wait you are just having it on your disk. How would I come to know about your stuffs and I know you’ll be thinking that those projects are mine and I don’t want to share it but then how would able to get to know about the problems in that project? How would you get more better ideas for updating the project?

You use tons of libraries and support from people online and think once that if they be like you, then how would you seek help? So if you have build projects/libraries then move it to online. There are many portfolio sites I recommend www.github.com .

By the way you could check mine on www.github.com/manujSharmaM

NOT BEING PATIENT

It’s great to your building stuffs and improving yourself much more and sometimes you  get stuck at something for a long time and feel like giving up coding and started to think that it’s not “My cup of tea”

That’s the time you have to be patient, you have to keep calm yourself. I know that it’s not that easy but remember it’s not that hard too. I have gone through these phases. I remember that I took nearly 15 days to solve a simple problem in my app that I worked on but it did solved and I was able to publish that app.

When you spend a couple hours looking at a bug that’s just a simple typo, nearly pulling your hair out, because it looks like everything should just… work… you might feel impatient.

Step away from the computer, come back after a few minutes, and start fresh. Back when I was first starting out this happened a lot more frequently than it does now, because now I’ve taught myself to slow down once I start feeling impatient and try and look at things with a clear mind. You’ll be surprised how often something that seems like a huge issue is really just a small error on your part. 🙂

“Think Twice ,Code Once!” Happy Coding.

Thank you for reading this post. Follow us on Instagram and Facebook.


To know more tips and tricks you can follow articles on this category :
https://blog.hiewpoint.com/off-topic/

To know about web development and WordPress follow
https://blog.hiewpoint.com/web/

To know about Android development and Android Studio follow
https://blog.hiewpoint.com/android/

Getting Started With Coding

How to get started with coding as a beginner?

I hope you have already gave thought about getting started with coding ,developing  and other coding releated stuffs and you guys have already  read thousands of articles on  “How to start with coding?”

In today’s post I will present you with my thoughts on how I (Manuj Sharma ,Author at Bunkerspoint.com and Web & App Developer) started with coding, developing.

Before you skip the paragraph to steps to be followed and learn from it. I would like you to see on “How I was into the programming world”. I promise that it won’t be boring to read the upcoming paragraph.

How i started with coding

I remember that  I was just scrolling  the play store apps to see what was trending in the market and  i saw a calculator app having more than 10M downloads and I was like how is this possible.

As our android phone already comes with  pre-installed basic apps like calculator and yet people are downloading these apps as they were little different and also easy to use from the app which already comes pre-installed in the phone. So I thought that I should also start making apps now and generate revenue from apps. But previously i used to thought that an app needs to be in large scale and all but initially that was not the case.

So I started researching about developing in android and  i came to know that I should learn JAVA(A programming language) in order to develop apps in Android Studio(An IDE to build apps). I was little bit familiar about programming  but I was not that much into it.

So I started with the basics of JAVA programming and within a month I was able to code and do stuffs in that programming  language ,then I moved to Android Studio and started learning about building apps and it took a hell out of me to build an app and also a lot of patience  and now it’s been a year developing  android apps. So now I’ll  tell you how this was all possible for me to learn these.

Here are some of my advices you could follow

  • If you have no idea about coding and you want to start with it then just start with any programming language asap and don’t wait. “Just get started.” I suggest you to check out this article
    https://hackr.io/blog/best-programming-languages-to-learn-2019-jobs-future to get some idea about the top trending programming languages.
  • Learn the language properly and train yourself for it. Learn from tutorials , mentor or any source but always learn from someone ,of course you could learn on your own but learning from an experienced one can save your time. Here are some of my recommendations to learn programming from online courses
  • Learn Code Online
  • Udemy
  • Udacity
  • Projects are very essential for a programmer to learn anything . Projects help you to understand the coding faster and it trains you to solve the problem. Do projects ,so that you would be able to apply your skills to it. I usually do minimum of 5 projects when I am learning something new.
  • Implement the coding skill you learnt to a framework/libraries or development .Like I learnt java and then I started implementing to it by developing apps. In this way you will enjoy  programming.
  • Wait- Have patience ,it takes time. Yes you will have hard times , you will get stuck, you may feel like giving up. But wait there and try to understand and have patience and one day you will be a better coder . If you are not able to solve any problem then remember that your friend Stack Overflow is there to help you.
  • Be in the coding community .Follow some coders on youtube who encourages coding and teach you to be a better coder. I am a fan of Hitesh Choudhary and I would recommend you to check out his channel. It’s amazing.

Finally  I want to say you that no coder or developer says that I know everything about  coding and I could do with out anyone help. Remember a developer cannot develop a website without or an app any help . You could only gain more experience in it and be more confident in it. I have seen many developers or coders getting stuck at a problem and they are seeking help from others online and it’s completely fine to do this. Don’t feel bad for it.

“Think like a coder, Be like a coder.”

“Think Twice ,Code Once!” Happy Coding.

Thank you for reading this post. Follow us on Instagram and Facebook.


To know more tips and tricks you can follow articles on this category :
https://blog.hiewpoint.com/off-topic/

To know about web development and WordPress follow
https://blog.hiewpoint.com/web/

To know about Android development and Android Studio follow
https://blog.hiewpoint.com/android/

film

How to build a video player android app in minutes.

In this post you’ll learn how to build a video player android app using VideoView .By creating this app you’ll learn some basic concepts of VideoView ,MediaController.

The MediaController consists of components such as play video , pause video , forward and rewind etc.

Lets get started in building an app with video player.

First setup the project with an empty activity and give it any preferred name.
Copy this lines of code in activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.studio.myvideoapp.MainActivity">

    <VideoView
        android:id="@+id/videoView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="16dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
  • This xml file basically consists of videoView which is used to stream the video.

Adding video path to resource file

Create a raw folder under resource file and insert the video file which you want to play video in app. If you don’t know how to create a raw folder in android studio then you could follow the steps to create raw in our other post and learn more in detail about raw in android studio.

Now copy these lines of code in MainActivity.java

package com.example.studio.myvideoapp;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.VideoView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Basic of video
        //1. get video view
        VideoView videoView = (VideoView) findViewById(R.id.videoView);

        //2. point to video resource
        videoView.setVideoPath("android.resource://" + getPackageName() + "/" + R.raw.introvideo);

        //add media Control
        MediaController mediaController = new MediaController(this);

        mediaController.setAnchorView(videoView);

        videoView.setMediaController(mediaController);

        //run it
        videoView.start();

    }
}

Lets see what exactly happens in the MainActivity.java

First we get the videoView by findViewById() method.
Then we point that videoView to a videoPath bu=y using setVideoPath() method . We get the path from our raw folder.
Then we add a MediaController by instantiating the MediaController and set the AnchorView and lastly setMediaController on videoView.


Now we could start playing the video by videoView.Start() method.
NOTE: Now this video will play as soon as the app opens. That’s because we used start () method in onCreate().
The app would look something like this,

survey-2316468_1280

Create A List View Using Custom Adapter

Hello ,welcome to Bunkerspoint. In this post, we will see how to make a List view using custom adapter. This topic may be a bit intimidating so we will keep it easy by using text view only.

In this session we are going to create an app using list view which will display two text views called name and number using Array adapter.

  • open your android Studio app.
  • Click on new project-> give any name as you like.
  • Choose an empty activity-> click on next.
  • Don’t change any settings -> click on finish.
  • project may take some time to build and sync itself.
  • Copy the following code mainactivity.xml file. In the below given code, we create list view and assign it a id called “custom_list”.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ListView
        android:id="@+id/custom_list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

      />

</RelativeLayout>
  • copy the following code into list_item.xml. In list_item.xml ,we create two text views and assign each of them an id so that when list is created we could use ids to display the data into list.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_margin="24dp">


    <TextView
        android:id="@+id/number"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:paddingLeft="10dp"
        android:layout_margin="10dp"
        android:textSize="20dp"
        tools:text="1"/>

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="5"
        android:paddingLeft="20dp"
        android:layout_margin="10dp"
        android:textSize="20dp"
        tools:text="maharana"/>

</LinearLayout>
  • Create a new class called Acttivity(any name you want I kept mine as Acttivity) which will use to define your class and store the data in it. We created two objects of String data type.

We created a constructor to extract values from array adapter and return it in getmName and get mNumber methods. So ,that it is displayed. Copy the following code into Acttivity.java class.

package com.example.bunkersdemo2;

public class Acttivity {

    private String mNumber;

    private String mName;



    public Acttivity(String vNumber,String vName){

        mNumber=vNumber;
        mName=vName;

    }


    public String getmNumber() {
        return mNumber;
    }

    public String getmName() {
        return mName;
    }
}
  • create a new class called Acttivity adapter(name whatever you want) and extend it ArrayAdapter(in my case ArrayAdapter).Now we create our own custom constructor which takes two arguments ,context (it will be used to inflate the layout file)and list(to populate the items in the list). The list we are using is ArrayList.

Then we call a method called getView method. we create a variable called listItemView to convertView. If listItemView is null then we inflate the listItemview using the LayoutInflater.inflate(). We use getitem() method to get the position of the object. We update the text views using findviewbyid() and update the data of object in list_item xml using the id number and name and return the listItemView.

package com.example.bunkersdemo2;

import android.app.Activity;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.ArrayList;

public class ActtivityAdapter extends ArrayAdapter<Acttivity> {


    public ActtivityAdapter(Activity context, ArrayList<Acttivity> activity) {
        super(context, 0,activity);
    }



    @Override
    public View getView(int position,  View convertView,  ViewGroup parent) {
        View listItemView = convertView;
        if(listItemView == null) {
            listItemView = LayoutInflater.from(getContext()).inflate(
                    R.layout.list_item, parent, false);
        }

        Acttivity currentActivity=getItem(position);


        TextView number = (TextView)listItemView.findViewById(R.id.number);
        number.setText(currentActivity.getmNumber());


        TextView name = (TextView)listItemView.findViewById(R.id.name);
        name.setText(currentActivity.getmName());

        return listItemView;
    }
}
  • copy the following code into MainActivity.java file. We are done creating Adapter and list item xml .So in mainactivity.java file. we create array list called activity and enter the Acttivity objects which will be displayed. We get a reference to the list view and attach it to the adapter in the list view using findviewbyid () method. Add some items in the arrayList by add() method.
package com.example.bunkersdemo2;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

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

        ArrayList<Acttivity> activity = new ArrayList<Acttivity>();

        activity.add(new Acttivity("1", "Maharana"));
        activity.add(new Acttivity("2", "Shruti"));
        activity.add(new Acttivity("3", "Maharaj"));
        activity.add(new Acttivity("4", "Maharani"));
        activity.add(new Acttivity("5", "Maha"));
        activity.add(new Acttivity("6", "Marna"));
        activity.add(new Acttivity("7", "Mahana"));
        activity.add(new Acttivity("8", "Maharana2"));
        activity.add(new Acttivity("9", "Maharana3"));
        activity.add(new Acttivity("10", "Maharana4"));
        activity.add(new Acttivity("11", "Maharana5"));
        activity.add(new Acttivity("12", "Maharana6"));
        activity.add(new Acttivity("13", "Maharana7"));
        activity.add(new Acttivity("14", "Maharana8"));
        activity.add(new Acttivity("15", "Maharana9"));
        activity.add(new Acttivity("16", "Maharana0"));


        ActtivityAdapter adapter= new ActtivityAdapter(this,activity);
        ListView listView=(ListView) findViewById(R.id.custom_list);
        listView.setAdapter(adapter );

    }
}

OUTPUT


In this post, you have seen how to create a arraylist using custom adapter and how to implement it in your app. you can try and implement in different examples to understand. If you want more information you can go to documentation here. It is always a good practice to read the documentation.
Thank you for reading and keep following bunknerspoint.

getting started with android studio

LISTVIEW IN ANDROID

Hello, welcome to bunkerspoint ,this topic is based on list view in android with example. So what’s list view in android? In android developers official website it says,“A list view is an adapter view  that does not know the details, such as type and contents, of the views it contains. Instead list view requests views on demand from a ListAdapter  as needed, such as to display new views as the user scrolls up or down”.

In simple, a list view is a view that contains list items and display them in vertical scrollable, which allows user to scroll the list items up and down vertically. ListView uses adapter to bind data from it to display in ListView. Think of an adapter as a middleman between Adapter view and any other view such as ListView , GridView etc.

USING ADAPTER IN LISTVIEW

ListView is a subclass of AdadpterView and they can be populated by binding to an Adapter. An Adapter retrieves data and represents those data. There are some common adapters which are frequently used such as ArrayAdapter, BaseAdapter, CursorAdapter etc..


In this tutorial, we are going to make use of ArrayAdapter. We are going to see how to implement listView in android studio using ArrayAdapter.
After following this tutorial, you would have the following output.

Lets begin with creating activity_main.xml

Create a lisView inside the activity_main.xml and give it a id of listView.

<?xml version="1.0" encoding="utf-8"?>
<!-- Layout for the main screen -->
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/listview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="16dp"
    android:paddingLeft="16dp”
    android:paddingRight="16dp"
    android:paddingTop="16dp" />

Create a new layout resource file and name it as list_items

<!--  Single List Item Design -->
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/textview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp"
    android:textSize="16dp"
    android:textStyle="bold" >
</TextView>

In mainActivity.java add this code snippet.

package com.bunkerspoint.android.listView;

import android.os.Bundle;
 import android.support.v7.app.AppCompatActivity;
 import android.widget.ArrayAdapter;
 import android.widget.ListView;
 import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
    ArrayList<String> arrayList = new ArrayList<>();
    arrayList.add("Manuj");
    arrayList.add("Pratik");
    arrayList.add("Yash");
    arrayList.add("Yatendra");
    arrayList.add("Yagnesh");
    arrayList.add("Mayur");
    arrayList.add("Manuj");
    arrayList.add("Raju");
    arrayList.add("Yadav");
    arrayList.add("Dhoni");


    ArrayAdapter<String>arrayAdapter = new      ArrayAdapter<String>(this,android.R.layout.simple_expandable_list_item_1,arrayList);
    // Get a reference to the ListView, and attach the adapter to the listView.
    ListView listView = (ListView) findViewById(R.id.listview_flavor);
    listView.setAdapter(arrayAdapter);
 }
}

The above code snippet creates a listView with list items as shown below.

HANDLE CLICK LISTENERS IN LISTVIEW

The above code snippet only shows the list item but listview are useless when we are not able to click those list items. So below code snippet will let you handle click events in listView so that you could be able to use it in your projects.

listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {

        String selectedItem=arrayList.get(position);
        Toast.makeText(getApplicationContext(), "Person Selected : "+selectedItem,   Toast.LENGTH_LONG).show();
    }
});

Place this code snippet in MainActivity.java inside the onCreate()methd.

Let me explain whats happening in the MainActivity.java.
So, we instantiated ArrayList of type String and named it as arrayList and then added the items in it.

Then we created a ListView and ArrayAdapter which taken in as String and named it as arrayAdapter and we set the adapter to listView by listView.setAdapter()method.

To handle click events in our listView, we used the onItemClickListener and said it what we want to do when a user clicks on any item. In this case we toast the items upon click.


In this post, you learnt about how to create a listView and use it to populate list items in it by using ArrayAdapters. The ArrayAdapter in this tutorial uses a string type and not custom implementation and also the ArrayAdapter uses Android Studio’s default (provided layout of simple_list_item_1) adapter. So if you want to learn more about how to implement a CustomAdapter then check it out at our website
https://blog.hiewpoint.com/category/android/

cash-collection-currency-47344

MONETIZE YOUR ANDROID APP WITH ADS

Hello, welcome to bunkerspoint. We know that how much time it takes to build a good working legit app and you are ready to show-off the world. But wait don’t you think your efforts should payback to you? In this post we’ll talk about how to monetize your Android app with Google Admob. Admob is a mobile advertising company managed by Google.

WHAT MONETIZING APP DOES:

When your app is monetized with any advertising company it would be, it allows to display their ads in your app and the company pays for those ads which are live in your app.

MONETIZE YOUR ANDROID APP:

  • Sign up for admob. You need to have a gmail account in order to register in admob
  • Go to Apps and add app. If you have already published your app in playstore then click yes and search your app by name,developer name etc .else if you hadn’t published your app then click no and enter your app name and add the app to admob.
  • Enter your app name and choose your os.
  • After adding the app, go to app’s overview and add ad unit and select any of the ad type(Banner, Interstitial, Rewarded)
  • Suppose you select Banner then give AD unit name a name and select the ad type you want like video, text etc.
  • Let the Automatic refresh be Google optimized and keep the rest of the settings same.
  • Select create AD UNIT and your done with creading the AD UNIT. Now you’ll need to connect your app to admob.

CONNECT YOUR APP TO ADMOB:

You need to connect your android app with the admob in order to show live ads in your app. Connecting android app to admob is pretty easy by Firebase. Firebase helps in analyzing your app easily. If you haven’t signed up for Firebase then sign up for it and login to Firebase and create a project, give it a name and add integrate the app to firebase by clicking Add App and follow the instructions on Add Firebase to your Android app. After these settings is done, link your project with Admob in firebase navigating to Integrations under settings or you could also link to Firebase project through Admob.

LIVE ADS IN YOUR APP:

To live the ads in your app, you need to add the admob dependency in your android app. In Android Studio, click on Assistant and select firebase. Now
You could easily follow the instructions from there on how to create ads in app and adding dependency etc. For instance we are going to show you how to create banner ads in your app using firebase but without assistant.

So firstly login to Firebase and then follow these simple steps.

  • Add the necessary firebase dependencies such as core, admob, analytics.
  • Copy these line of codes in your activity/main.xml

        <com.google.android.gms.ads.AdView
            xmlns:ads="http://schemas.android.com/apk/res-auto"
            android:id="@+id/adView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_alignParentBottom="true"
            ads:adSize="BANNER"
            ads:adUnitId="ca-app-pub-3940256099942544/6300978111">
        </com.google.android.gms.ads.AdView>

Add this piece of code in MainActivity.java

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;

public class MainActivity extends AppCompatActivity {
    private AdView mAdView;

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

        MobileAds.initialize(this,
            "ca-app-pub-3940256099942544~3347511713");

        mAdView = findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);
    }

Thats it , now you’ve monteized your app and you are ready to display ads in your app.


Note: Always use test Ad ID while you are testing your application, you should never use original Ad ID in your application when in testing/developing phase. If you do so you might get blocked from AdMob.
You could find the App’s id and ad unit id under App’s settings in Admob.
Follow more detailed instructions on how to create ads for interstitial, rewarded in the below link.
https://firebase.google.com/docs/admob/android/quick-start

java vs kotlin

WHY CHOOSE JAVA OVER KOTLIN FOR BEGINNERS

Hello, welcome to Bunkerspoint. In this post we are going to discuss in detail about java and kotlin.

Programmers who want to become Android Developers are in a dilemma to choose Android Studio with Java or Kotlin. Since Google announced Kotlin as the official language for Android Development, many of the beginners arises with a question that whether to start with  java or kotlin for Android Development.

JAVA VS KOTLIN:

Java is a very popular procedural programming language  used for software development, application development and much more. It is object-oriented, secure and platform independent ,on the other hand Kotlin is a modern functional programming language. It is object oriented and has full support for java interoperability. It runs on the JVM and uses java libraries and tools. Kotlin was developed for Android Developers as the need of modern language in Android Development.

So you’ll be thinking that Kotlin offers great features for android developers as it was designed for the needs of Android Developers  so why shouldn’t i learn Kotlin and develop android apps written in Kotlin but if you are a absolute beginner in Android Development then learn java first.

WHY LEARN JAVA FIRST:

When you start learning Android Development you’ll need guides ,tutorials etc. Since java is an old popular language and its community is large you’ll get more help from java android tutorials, resources etc. whereas Kotlin community is still growing so kotlin android tutorials ,resources etc. would be less and you may not get that much help.

  • Java has large number of resources and libraries.
  • Has a lot of core features.
  • It is open source.
  • Java has a lot of open source Frameworks and Classes which helps developers.

Kotlin also have same features but for beginners java would be perfect because of large community and resources to learn and make most of it.

WHEN TO SWITCH FROM JAVA TO KOTLIN:

After building few projects in Android Studio using java ,do switch from Java to Kotlin and build some projects in Kotlin to understand the difference between both the languages. Even more you would also come to know which language better suits you for developing android apps.

CONCLUSION

Java over Kotlin is  a suggestion for beginners but intermediate/professional developers may have already switched from java to kotlin because kotlin is less verbose compared to java , null safety unlike java has null pointer exception and much more. Every language has its merits and demerits.Developers would choose a language based on the performance and need of a particular language.