Dedicated Server
Showing posts with label android. Show all posts
Showing posts with label android. Show all posts

Android viewpager with tab layout example

In this post i will walk you through the setup of a tab layout with view pager, the final output will be something like the one shown below. We will also see how to pass data to the viewpager fragments from the activity.

viewpager with tab layout
Before we begin, couple of things that we will be following in this project are

  • The app will be built using androidx packages
  • The app will be using Java 8
  • The app will be using data binding (part of android jetpack components)

Now that we are all set to begin, let us open up android studio and create a brand new project with androidx artifacts.

androidx artifacts are configured by default when you create a new AS project
Now that your project have successfully synced with gradle, head over to your app level build.gradle and enable java 8 by adding the following code

compileOptions {
compileOptions {
targetCompatibility JavaVersion.VERSION_1_8 sourceCompatibility JavaVersion.VERSION_1_8 }
}
Also, you can enable data binding by adding the following to your app level build.gradle

dataBinding {
enabled = true}

Also add the following material dependency inorder to support tab layout

implementation 'com.google.android.material:material:1.0.0'

Now the resulting build.gradle will look like the following

Now that the initial setup is done, we will jump into the coding section right away.

First of all, in the project explorer, right click on your package directory, then create a blank fragment like shown below

create new blank fragment

Now that i have added the blank fragment, head over to your activity layout(acitvity_main.xml in my case) and convert it into a databinding layout by wrapping the root layout with <layout> tag, so that the resulting layout will be 


Now head over to your activity's java file (MainActivity.java in my case) and initialise binding variable by adding binding= DataBindingUtil.setContentView(this,R.layout.activity_main);, now you can get the binding variable for this initialisation by making slight modification to your layout file name, so in my case acticity_main becomes ActivityMainBinding. So initialise your bindining variable like this private ActivityMainBinding binding;

Now inorder to assign different fragments  in viewpager, we will need a viewpager adapter, for that go inside your MainActivity.java and add a new adapter class like shown below


If you check the activity_main.xml above, you can see that i have already added viewpager and tab layout inside it. I have also assigned the id's tab to tab layout and viewPager to the viewpager. Now is the part where view binding comes into play, can reference the viewpager and tab layout in our java code simply by using binding.viewPagerbinding.tab etc.

Now we can easily pass our viewpager to the SamplePagerAdapter and also setup our viewpager with the tablayout. Inside the SamplePagerAdapter's getItem() method you can return different fragments, which will be showing up inside your viewpager as different tabs. You can also return the titles for each tab in the getPageTitle() method

Now the complete code for MainActivity.java will be like
everything is now set and you will be able to see the tabbed viewpager if you hit the run button.
Download full source code below :

Android data binding tutorial for absolute beginners

Hi guys! In this post we will discuss how to get started with data binding in android for absolute beginners. As some of you are already aware of,  data binding is actually part of Android's Jetpack components. By implementing data binding, you can get red of a lot of boilerplate code in android development. For example, you can completely get rid of all the messy view declarations using findviewbyid, setting text using settext() method etc.

So without further ado, we will jump into the coding part right away. First of all open your android studio ide and create a brand new android studio project with an empty activity as initial setup.

Next thing you will need is to enable data binding in your android project, which can be done by adding the following in your build.gradle file.

dataBinding {
 enabled true
 }
now hit sync now button in top right corner like shown below



Now you will need to wrap the root layout of your activity(activity_main.xml) with the <layout> tag. You can do this either manually or just click the root layout of your activity's layout file to bring up the yellow bulb icon, clicking on which brings up the option "convert to data binding layout" and finally click on this option like shown below



As a result of selecting the above option, the layout will be converted like shown below



Now we can see that there is a <data> layout which is empty, so go ahead and add a <variable> tag inside it with some greeting data, say "Hello World!", so that the layout looks like :



Now the finishing touch to be made to our layout is to bind the greeting text variable to our textview, which can be done by adding @{greeting} to the textview's text attribute, also give an id to your textview, which we will later need in our layout's corresponding java file. So the final layout will look like the following :


Now that our layout setup for our data binding sample is done, let us head over to the java code. So, head over to your MainActivity.java file and initialise data binding by replacing setContentView(R.layout.activity_main); with binding= DataBindingUtil.setContentView(this,R.layout.activity_main);. As you are thinking right now, i have not yet declared the binding variable yet. Yes, I will show you how to do that.

Basically binding should be declared using a class that automatically gets generated as soon as we change the root layout of our layout file to <layout>. The so generated binding class will help us to identify various view items in our layout using the view's id.

For each layout with <layout> tag, the binding class will be generated in such a way that its name is generated from your layout file's name itself. It will have its name as all underscores removed and converting the letters succeeding the underscores as upper case, so if your layout file has a name like activity_main.xml ,then its corresponding binding file will be ActivityMainBinding . Now inside your onCreate(), below data binding initialisation, add this binding.setGreeting("Hello World"); to complete data binding process , see below for complete code,

You can see that the setter setGreeting() has got generated automatically since we have previously declared the variable "greeting" inside out layout file . Finally run the app to see the "Hello World" text printed on your screen.

Android Recyclerview Tutorial with SQLite ROOM : using MVVM, Dagger 2

What we will be building ?








A simple note taking app, which will have option to add notes and delete it. This will be a minimal design tutorial and hence we won't be spending much time on the app UI. This tutorial will be more focused on the MVVM, dagger2 and building an overall app architecture. This app will be improved in upcoming tutorials with more features, so make sure to stay tuned for that as well.

What are we will be covering ?

We will be using Java 8 to get access to various features like lambda functions, so we will need to enable this in app level build.gradle

We will be making use of data binding, so we will need to enable this also on your app level build.gradle

We will be using Dagger2 for building our dependencies

We will be having a base activity class which will be responsible for performing redundant operations like dependency injection, data binding, setting viewmodels for activities etc. So basically this app structure is developed with more activities to be incorporated in future.

The main reason for choosing MVVM and live data is that, with this pattern database operations like insert, delete gets effortlessly simple. We just need to observe to the database changes and as a result all the UI changes is reflected on the go. There are more advantages to this pattern, we will discuss these while moving forward.

Getting started with project building :

First of all, open your android studio, in file go to new>> new project and then create a project with empty activity

Dependencies Required ?

First of all update project level build.gradle as show below. Here we have set the versions for some dependencies that we will be using in our app :

Now go ahead and update your app level build.gradle with  dependencies for recyclerview,cardview,dagger,room,livedata etc as shown below :


As shown above we have enabled databinding by adding this

dataBinding {
enabled = true}

Also enable java 8 as shown below

compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8}


Now let us jump into the coding session right away. Now, since we are making a notes app we will need to make a note model class. So in terms of SQLite ROOM, we will call this an entity. Entities in room are just another java class which is annotated with @Entity annotation. Annotating a class like this will help room in identifying it as an SQLite table. So now our room entity/table will have an notesId field which will be auto incremented on insertion, a notesTitle field and a notesDesc filed. We will be naming our table as notes_model which will be provided in brackets along with the @Entity annotation. So create a class like the following and name it NotesModel.java

Now go ahead and create a DAO class, by annotating it with @Dao. This class will basically act as an interface which will query the sqlite database as per our request. It will contain the various sql queries like insert,delete etc, now name it as NotesDao.java


Now it is time to create our database class, which should be annotated with @Database. Inside the annotation arguments, we can provide an array of entities where we can provide a list of tables/entities that we need inside our database, but for now we will be giving a single entity/table name which is NotesModel and we will keep the database version as 1 . So create the database class as follows :

It is now time to create our NotesRepository which will provide us with the live/updated database changes. It is where we define our live data methods from our db which will be later observed in activity. So create the repository as shown below and name it as NotesRepository.java

You might have noted the @Inject in the constructor which means that we will be getting these dependencies using dagger2, we will see how to create these dependencies using dagger2 later in this tutorial

Now create an abstract class BaseViewModel from which we will be extending all the viewmodel classes

Now we will need tocreate a viewmodel class for our MainActivity, so create MainActivityVM.java  like below

Now we will be creating the BaseActivity.java and make it abstract from which all our activties will be extending from. Also our BaseActivity.java will accept generic params for ViewDataBinding,BaseViewModel etc which means that the respective activities will be supplying our base activity with these params as required so that all databinding, setting viewmodels etc happens in the baseactivity itself.

We will also be using abstract methods for getting binding variable,activity layout, and viewmodel from respective activities. These abstract methods are getBindingVariable(),getLayoutId(),getViewModel() respectively.
now that we have all required attributes for databinding and dependency injection, we can create BaseActivity.java like following :


Now update your layout file which is present in res>> layout>>activity_main.xml , as shown below :

Now add a new layout file for the add new note dialog and name it custom_dialog_with_btns_view.xml


Now goto the project explorer on left hand side of your screen and right click on your package directory and create a new package named "di". This is to organize all your dagger files in this directory, it is optional to create a directory like this but it is highly recommended so that the code becomes more understandable.

Now right click on the di directory, and create a new abstract class and name it ActivityModule.java

In the above class you might have noticed the annotation @Module  which means that this class is a module and in this case this module will be used to provide various activities in our app like MainActivity. All the future generated activities must be defined here.

Now in the same directory - di, we will need the custom annotation ViewModelKey to generate our ViewModelModule.java . So first create interface ViewModelKey.java as follows

Now in the di directory, create another abstract class with @Module annotation and name it as ViewModelModule.java . This module class will provide all the ViewModels in the project. All the ViewModels should be defined here


Create another @Module annotated class AppModule.java which has included module as ViewModelModule.class as follows

Now you will need to design the view for note item, so go to res>>layout, right click on layout directory and click create new layout resource file and name it notes_item_view and add below contents to it

In the above layout for the recyclerview adapter, we have used data binding to set text into the textview. Basically, inorder to perform data binding, we need to make the root layout as "<layout>", also you will need to import the NotesModel and assign it to a variable as shown below.
<data>
<import type="com.example.recyclerviewsqliteroomcrud.persistance.NotesModel"/>
<variable
name="itemModel"
type="NotesModel" />
</data>
Now create a recyclerview adapter like shown below, also you will need to bind the above layout with this adapter in the viewholder

Now update your MainActivity.java  like show below



As shown above we have injected the MainActivityVM. Also we have returned the viewmodel(MainActivityVM) and layout file(activity_main) to the BaseActivity so that we can perform databinding and viewmodel setup inside the BaseActivity itself. This process will apply to all future activities that may be created in the app.
Now we will need to create a component class which will be used along with the earlier created module classes to generate the dependencies using dagger. So create AppComponent.java as shown below :


Now as a final step,we will need to generate the application class which will initialize dagger to build the necessary dependencies. So create BaseApplication.java

As soon as you copy the above file you may notice that DaggerAppComponent is given in red and shows error. This is because dagger has not yet generated the dependencies, inorder to do that click on File>>Sync project with gradle files . If everything goes well, the error will be gone and you may then organize the project structure as shown below(optional)


Finally, go to AndroidManifest.xml and update the application name as .BaseApplication as shown below





You may also checkout the below video tutorial which shows how and example with recyclerview,mvvm,dagger2,retrofit2

startactivityforresult example in android



startActivityForResult method helps to send data to another activity, get data from another activity or even wait for the result from another activity to perform certain action/ process the result data.

The process involved are,

  • Consider there are two activities - MainActivity.java and SecondActivity.java, the main activity calls the second activity and waits for the result like shown below, 
Intent intent=new Intent(MainActivity.this,SecondActivity.class);       
startActivityForResult(intent, 2);

  •  Now the SecondActivity performs the required operations(if any) and returns the result like shown below
Intent intent=new Intent();      
intent.putExtra("MESSAGE","your message to FirstActivity ");                   
setResult(2,intent);

  • Now we should override the onActivityResult method inside MainActivity which gets automatically invoked once the results from the SecondActivity are returned. It is overidden like shown below
          @Override  
          protected void onActivityResult(int requestCode, int resultCode, Intent data)  
          {
                 super.onActivityResult(requestCode, resultCode, data);  
                   if(requestCode==2)  
                         {
                            String message=data.getStringExtra("MESSAGE");   
                         }
          }  

  • Finally you can now access the message send from the SecondActivity using the  String "message" 
Now let us look into a working example. In this example, we will be passing a message from an editext field inside the SecondActivity.java to a texview field in MainActivity.java . So first of all create a new android studio project and make the following changes to your activity_main.xml file
As shown above we have created a button to call the second activity and also added a textview to display the result from second activity. Now we need to call the second activity and wait for result as shown below :
As shown above we have used startActivityForResult to start the second activity so that we we will get the result from the second activity in the callback method - onActivityResult
Now create new activity and name it as SecondActivity.java . Create an edittext field to type the message and also add a button to send the message
Now you may update the SecondActivity.java like this

setting up a multiplayer game environment using socket connection in android and node.js

You may download the complete project source code here



First of all create an new android studio project. Now right click the project from project explorer window and goto the project location by clicking "reveal in finder". Insider your project directory, create a new folder "server".

Now right click on the server folder and click "New terminal at Folder" or just open up a new terminal window and cd down to your "server" folder location

Now that you have terminal window opened for your server folder, type the command npm init and hit enter

npm init 

npm init command

Now you will be made to enter the project specific details in which you will need to enter details as shown above (just use the default values for all fields). Click "enter" and then type "yes" input to the dialog "is that OK". Now that you have successfully generated the package.json file, if you goto your server directory you can see that the package.json file has been generated.

Our initial setup for project is now done.
Now we will need to install socket.io by typing the following command and hitting enter


npm install socket.io --save
Here you can see that , the above command adds the modules to package.json file

Similarly, we will need to install express also


npm install express --save
Now we can jump into some coding part, first of all create a new file inside "server" directory named index.js and add the following code to it


The following code makes the node server to listen for events on port 8080

server.listen(8080,function()
{
console.log("Server is now running...");
});
so when our android client makes a request to port 8080, the server can respond accordingly. This will be covered in detail in upcoming sections.

The 'connection' event indicates that whenever a client makes a connection to the server, the server logs 'Player Connected!' along with the client id. Also whenever a player disconnects, the 'Player Disconnected!' message will be logged.

 now open up your android studio, you will have the following project structure
server directory present inside the android project directory

From now on, we can use android studio's terminal window for invoking our server. First of all click in terminal option in the bottom and "cd" down to server directory. Run the following commands

  • cd server
  • node index.js
running the server

If everything goes well, you can see the message "Server is running...". Please be sure that you get this message correctly in order to proceed further.

Now we will look into some client side code in android, so go to your android app's app level build.gradle file and add the following dependency


compile "io.socket:socket.io-client:0.6.2"

Now go to your AndroidManifest.xml file and add the internet permission as shown below :


Now go to your app's MainActivity.java file and add the following code to it



socket = IO.socket("http://192.168.1.2:8080"); 

also make sure that you declare with the right socket io package like this

import io.socket.client


here you should replace above ip with your ip address and keep the port as 8080 itself, you can use ipconfig to find your ip if you are using windows or in mac you can go to system prefernces >> network

Now make sure that your server is running and is showing the message "Server is running..", and then run the android studio project

As soon as the app starts running in your emulator/device, check the android studio terminal window, it should display something like "Player Connected!ABoIjzSQIeXSD2VZAAAA". It shows that player with specific id has joined. See below image


player connected

Now if you close/quit your android app, the server should output "Player Disconnected!" like shown below


player disconnected

Download file from url in android using retrofit

Downloading files from a url is a common use case these days for a countless number of apps. The files to be downloaded can be of smaller size or bigger size depending on the app requirements. We will be checking how to download a bigger sized file in this tutorial.

We will be using retrofit 2 as our network client in this tutorial.

So first of all, go ahead and add the following dependencies in your newly created android studio project. Be sure that you add the dependencies in your app level build.gradle file and not the project level build.gradle file :

implementation 'com.squareup.retrofit2:retrofit:2.3.0' 
implementation 'com.squareup.okhttp3:okhttp:3.10.0'

How to create a frame animation with character sprite in android ?

As it is obvious from our title, we will be creating a simple frame animation using a very few lines of code.

First of all go here and grab some character sprite images that you would like to animate. I have chosen the following set of images.



you can download the above set of images >> Download it here

Now go ahead and create a new android studio(or choose an IDE of your choice) project. Now, if you extract the above resource which i have provided, you could find a folder called running in which there are 6 frame images as shown in the image above . Copy all the images to your drawable folder like this



Now right click on your drawable folder and then new >> Drawable Resource File. Name it as running_anim. Now the drawable directory will look like this



Now open up running_anim.xml and add the following code to it

<animation-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/frame1" android:duration="100"/>
    <item android:drawable="@drawable/frame2" android:duration="100"/>
    <item android:drawable="@drawable/frame3" android:duration="100"/>
    <item android:drawable="@drawable/frame4" android:duration="100"/>
    <item android:drawable="@drawable/frame5" android:duration="100"/>
    <item android:drawable="@drawable/frame6" android:duration="100"/>
</animation-list>

Here we have added the 5 images which should be animated in sequence. The duration for which each image has to stay in the frame can also be mention here by using android:duration


Now go to your res >> layout folder and open activity_main.xml add the following code

<?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">

    <ImageView
        android:id="@+id/sprite_image"
        android:src="@drawable/frame1"
        android:layout_width="match_parent"
        android:layout_height="200dp" />

</RelativeLayout>

The above imageview sprite_image is where we will run the animation


Now that all the design part is complete, let us see how to run the animation using some java code. Now goto your MainActivity.java file and then add the following code

public class MainActivity extends AppCompatActivity {

    private ImageView sprite_image;

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

        sprite_image=(ImageView)findViewById(R.id.sprite_image);
        sprite_image.setImageResource(R.drawable.running_anim);
    }
}

As shown in the code above just set image resource of the ImageView as the  running_anim.xml that we created using the 6 images in the beginning. Now if you go ahead and run the project, you could see the following output



Parse a json array inside another json object in android with free source code download




We will be using retrofit,gson for parsing, so go to your app level build.gradle and add the following as dependencies

implementation 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
please add the latest dependency versions for retrofit, converter-gson

Hi, in this tutorial, we will parse the below json. Check this json here >> https://navneet7k.github.io/sample_object_array.json

Here you can see that the cars_array is wrapped inside another json object, so we will need two model/pojo classes


1) Automatic model class/pojo class generation using http://www.jsonschema2pojo.org/


You can make use of jsonschema2pojo to covert json to java object online. This is a really effective tool which even supports various annotation types like jackson, gson, moshi etc.
Specify Target language as Java, Source Type as JSON and annotation style as Gson
  • Now click preview and copy the generated java files
Now copy the contents of the class and add it in android studio project

Now rename the generated classes like shown below and add it inside your android studio project

SampleResponse.java

public class SampleResponse {
    @SerializedName("id")
    @Expose
    private String id;
    @SerializedName("type")
    @Expose
    private String type;
    @SerializedName("cars_array")
    @Expose
    private List<CarsArray> carsArray = null;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public List<CarsArray> getCarsArray() {
        return carsArray;
    }

    public void setCarsArray(List<CarsArray> carsArray) {
        this.carsArray = carsArray;
    }

}


CarsArray.java

public class CarsArray {
    @SerializedName("id")
    @Expose
    private String id;
    @SerializedName("name")
    @Expose
    private String name;
    @SerializedName("desc")
    @Expose
    private String desc;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }
}


MainActivity.java

private void parseJson() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://navneet7k.github.io/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        RequestInterface request = retrofit.create(RequestInterface.class);
        Call<SampleResponse> call1=request.getJson();
        call1.enqueue(new Callback<SampleResponse>() {
            @Override
            public void onResponse(Call<SampleResponse> call, Response<SampleResponse> response) {
                Toast.makeText(MainActivity.this,"Success! response for first item >> \n car :" +response.body().getCarsArray().get(0).getName()+"\ndesc :"+response.body().getCarsArray().get(0).getDesc(),Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(Call<SampleResponse> call, Throwable t) {
                Toast.makeText(MainActivity.this,"Failure",Toast.LENGTH_SHORT).show();
            }

        });
    }

RequestInterface.java

interface RequestInterface {
    @GET("sample_object_array.json")
    Call<SampleResponse> getJson();
}


Download free source code

Parse json object in android with free source code download




We will be using retrofit,gson for parsing, so go to your app level build.gradle and add the following as dependencies

implementation 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
please add the latest dependency versions for retrofit, converter-gson

Hi, we will be parsing the below json in this tutorial. Check this json here >> https://navneet7k.github.io/sample_object.json

Clearly, the json is of the form {..} and we can parse it as an object from android
Now inorder to generate model class/pojo class for above json, you may either create it automatically using http://www.jsonschema2pojo.org/ or generate it manually

1) Automatic model class/pojo class generation using http://www.jsonschema2pojo.org/

You can make use of jsonschema2pojo to covert json to java object online. This is a really effective tool which even supports various annotation types like jackson, gson, moshi etc.
Specify Target language as Java, Source Type as JSON and annotation style as Gson
  • Now click preview and copy the generated java files
Now copy the contents of the class and add it in android studio project

Now copy the above generated contents into SampleJson.java as shown below

SampleJson.java

public class SampleJson {
    @SerializedName("title")
    @Expose
    private String title;
    @SerializedName("description")
    @Expose
    private String description;
    @SerializedName("name")
    @Expose
    private String name;
    @SerializedName("id")
    @Expose
    private String id;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
}


MainActivity.java

private void parseJson() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://navneet7k.github.io/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        RequestInterface request = retrofit.create(RequestInterface.class);
        Call<SampleJson> call1=request.getJson();
        call1.enqueue(new Callback<SampleJson>() {
            @Override
            public void onResponse(Call<SampleJson> call, Response<SampleJson> response) {
                Toast.makeText(MainActivity.this,"Success!",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(Call<SampleJson> call, Throwable t) {
                Toast.makeText(MainActivity.this,"Failure",Toast.LENGTH_SHORT).show();
            }

        });
    }

RequestInterface.java

interface RequestInterface {
    @GET("sample_object.json")
    Call<SampleJson> getJson();
}


Download free source code