Android app pass data between activities

Passing Data types like String, Integer, Float, double is quite easy in android so we don’t need any special class for this. But for Android pass model from intents using Serializable from intents we need Serializable class.

What is Modal Class

Model can be applied to a class which represents your application’s data model, and will cause instances of the class to become observable, such that a read of a property of an instance of this class during the invocation of a composable function will cause that component to be “subscribed” to mutations of that instance. Composable functions which directly or indirectly read properties of the model class, the composables will be recomposed whenever any properties of the the model are written to.

What is Serializable?

It is a standard Java interface. So you can just implement Serializable interface and add override methods.

There are pros and cons of this class. It is comparatively slow and easy to integrate.

To immplements simple Data types we can just pass ‘Xyz’ by key ‘name’.

Intent intent = new Intent(MainActivity.this, DataActivity.class);
intent.putExtra("name","Xyz");// for string variable 

And in data activity to fetch the data by key ‘name’.

Intent intent = getIntent();
intent.getStringExtra("name");// to fetch data

But for passing objects or model class we need serialization.

So let’s get started on how Android app pass data between activities.

For this section I have created MainActivity, DataActivity and UserModel to achieve the task.

MainActivity.java

To send the model class from MainActivity to DataActivity class by using Serializable class.

package com.example.sampleproject;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

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

        ((Button)findViewById(R.id.click_me)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UserModel mUser = new UserModel();
                mUser.setId(1);
                mUser.setName("Xyz");
                mUser.setMobile("99919290XX");

                Intent intent = new Intent(MainActivity.this, DataActivity.class);
                intent.putExtra("name","Xyz");
                intent.putExtra("user", mUser);
                startActivity(intent);
            }
        });

    }
}

DataActivity.java

To fetch the model class from main activity.

package com.example.sampleproject;

import android.content.Intent;
import android.os.Bundle;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.util.Log;
import android.view.View;

import java.io.Serializable;

public class DataActivity extends AppCompatActivity {

    private String TAG = "DataActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_data);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        Intent intent = getIntent();
        if (intent != null) {

            Serializable s = intent.getSerializableExtra("user");
            UserModel mUserModel = (UserModel) s;
            if(mUserModel!=null) {
                int id = mUserModel.getId();
                String name = mUserModel.getName();
                String mobile = mUserModel.getMobile();
                Log.d(TAG, "id: "+id);
                Log.d(TAG, "name: "+name);
                Log.d(TAG, "mobile: "+mobile);
            }else {

            }
        }
    }

}

UserModel.java

Model which is shared between the MainActivity and DataActivity class.

You can also add child model or list of UserModel class just you have to implements that model by Serializable.

package com.example.sampleproject;

import java.io.Serializable;

public class UserModel implements Serializable {

    private int id;
    private String name;
    private String mobile;


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

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    public String getMobile() {
        return mobile;
    }
}

Output of Android app pass data between activities:

The output of this code will look like this.

id: 1.
name: Xyz.
mobile: 99919290XX.

You can also see this post where I have passed a model class between activities by using intents from here.

Tagged : / / / /

Shuffle deck of cards java

For Shuffle a deck of cards dynamically using java simply just fill array with random numbers between 0 to 51 and then remove one by one when the card is drawn we have here suit between 0 to 3 and rank between 0 to 13.

Now, To create a function to Shuffle a deck of cards dynamically using java.

Create an array of suit from 0 – 3 and rank from 0 – 12. Then add it to an array of deck of length 52 and shuffle the deck array randomly.

public static int[] cardShuffle() {

    // create a deck of 52 cards
    int[] suit = {0, 1, 2, 3};
    int[] rank = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
            11, 12
    };
    int SUITS = suit.length;
    int RANKS = rank.length;

    int N = 52;
    int M = 12;

    int[] deck = new int[N];
    // initialize deck
    for (int j = 0; j < SUITS; j++)
        for (int i = 0; i < RANKS; i++)
            deck[SUITS * i + j] = rank[i] + suit[j] * 13;

    // create random M cards
    for (int i = 0; i < M; i++) {
        int r = i + (int) (Math.random() * (N - i));
        //String t = deck[r];
        int t = deck[r];
        deck[r] = deck[i];
        deck[i] = t;
    }
    return deck;
}

Now function for drawn N cards from the above deck of cards. Suppose you have 3 user each one should contain 4 cards so pass the numberOfCardsDrawn to 3×4 = 12. Then easily you can distribute each one 4 cards.

public static int[] drawCards(int[] deckOfCards,int numberOfCardsDrawn) {
    int[] drawnCards = new int[numberOfCardsDrawn];
    for (int l = 0; l < numberOfCardsDrawn; l++)
        drawnCards[l] = deckOfCards[l];
    return drawnCards;

}

Now just call both the function for the desired result.

    public static void main(String []args){
    int numberOfCardsDrawn = 12;

    int[] deckOfCards =  cardShuffle(); // shuffle cards
    int[] drawCardsFromDeck = drawCards(deckOfCards, numberOfCardsDrawn); // draw cards

    for (int i = 0; i <drawCardsFromDeck.length ; i++) {
        System.out.print(drawCardsFromDeck[i] + ", ");
    }

 }

Then finally take the cards and print by using system out Sample output of the above code snippet

Output: 19, 4, 49, 14, 47, 1, 39, 18, 48, 40, 41, 12

Github link for the code ShuffleCards.java .

Note : Output will be different each time because of the random function used in the program. You can also see other post from here.

Tagged : / / / / /