Android Studio Loading Animation Between Activities

Progress Dialog is dialog showing a progress indicator and an optional text message or view.

The methods of Progress Dialog being used in this tutorial are:

ProgressDialog.setTitle() – Used to set title of dialog box

ProgressDialog.setMessage() – Used to set dialog message being displayed

ProgressDialog.setProgressStyle() – Choose the style of indicator

ProgressDialog.dismiss() – Dismiss the progress dialog

For this example there is Two Main Activities. One is called MainActivity.java and the other MainActivity2.java

The function of this app is the user click on the ‘next’ button and the Main Activity is switched to the second activity. During the switch a Progress Dialog is displayed to signal the change in activates.

MainActivity.java
public class MainActivity extends AppCompatActivity {
    Button  next;
    ProgressDialog progress;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        progress = new ProgressDialog(MainActivity.this);
        next = (Button) findViewById(R.id.btn_main);

        next.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                switch (v.getId()) {
                    case R.id.btn_main:
                        progress.setTitle("Progress"); // setting title
                        progress.setMessage("Please Wait Loading..."); // creating message
                        progress.setProgressStyle(ProgressDialog.STYLE_SPINNER); // style of indicator
                        progress.setIndeterminate(true);
                        progress.show();
                        new Thread() {

                            public void run() {
                                try {
                                    Thread.sleep(2000);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                                Intent i = new Intent(MainActivity.this, MainActivity2.class); // Switching to Second Activity 
                                startActivity(i);
                                progress.dismiss();
                            }

                        }.start();
                        break;
                }

            }
        });
    }
}
activity_main.xml
<androidx.constraintlayout.widget.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=".MainActivity">

    <Button
        android:id="@+id/btn_main"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="159dp"
        android:layout_marginLeft="159dp"
        android:layout_marginTop="364dp"
        android:layout_marginEnd="159dp"
        android:layout_marginRight="159dp"
        android:text="Next"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Check out more tutorials HERE!

Android Studio Tutorial SeekBar

SeekBar is an extension of ProgressBar that adds a draggable thumb. The user can touch thumb and drag left or right to set the current progress level or various other task. In this example, the seekbar will be used to display a percentage. As the user moves the SeekBar left to right the percentage value…

Python Ethereum Block Chain Interaction with Web3

This tutorial will show how to interact with the Ethereum blockchain using Python. To start, the Python library Web3 will need to be installed. The Web3 library allows you to interact with a local or remote Ethereum node, using a HTTP or IPC connection. Using Web3 you will be able to create smart contracts on…

Python chr()

The chr() function returns a character that represents the specified unicode. Syntax chr(i) The chr() method takes only one integer as argument.The range may vary from 0 to 1,1141,111(0x10FFFF in base 16).The chr() method returns a character whose unicode point is num, an integer.If an integer is passed that is outside the range then the method returns…

Android Studio Tutorial SeekBar

SeekBar is an extension of ProgressBar that adds a draggable thumb. The user can touch thumb and drag left or right to set the current progress level or various other task.

In this example, the seekbar will be used to display a percentage. As the user moves the SeekBar left to right the percentage value being displayed will change from 0 to 100.

User interaction is captured using the SeekBar.OnSeekBarChangeListener

The SeekBar.OnSeekBarChangeListener has three methods :

onProgressChanged – Notification that the progress level has changed.

onStartTrackingTouch – Notification that the user has started a touch gesture.

onStopTrackingTouch – Notification that the user has finished a touch gesture.

Step 1 :

Create a new Android Studio project

Step 2 :

In the XML file select the SeekBar from the Widgets palette. Also add a TextView, this will be used to display the percent.

Step 3 :

open up the java file and then define the SeekBar and TextView variable, use findViewById() to get the SeekBar and TextView.

Step 4 :

Use the SeekBar.OnSeekBarChangeListener event and use the method OnProgressChanged to capture the change in progress

Step 5 :

Run app, as the SeekBar is dragged from left to right the percentage should change in the TextView

Example Source Code

MainActivity .java

public class MainActivity extends AppCompatActivity {

    NumberFormat percentFormat = NumberFormat.getPercentInstance();// percent format
    TextView percentTextView; // Shows percent
    double percent = 0; // setting initial percentage


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

        percentTextView = (TextView) findViewById(R.id.percentTextView);

        SeekBar percentSeekBar = (SeekBar) findViewById(R.id.percentSeekBar);
        percentSeekBar.setOnSeekBarChangeListener(seekBarListener);

    }
    void calc() {
        percentTextView.setText(percentFormat.format(percent));
    }
    final SeekBar.OnSeekBarChangeListener seekBarListener =
            new SeekBar.OnSeekBarChangeListener() {
                // update percent, then call calculate
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress,
                                              boolean fromUser) {
                    percent = progress / 100.0;// set percent based on progress
                    calc();
                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {
                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {
                }
            };
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".MainActivity">

    <SeekBar
        android:id="@+id/percentSeekBar"
        android:layout_width="186dp"
        android:layout_height="24dp"
        android:layout_marginStart="201dp"
        android:layout_marginTop="357dp"
        android:layout_marginEnd="169dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/percentTextView"
        android:layout_width="79dp"
        android:layout_height="29dp"
        android:layout_marginStart="166dp"
        android:layout_marginEnd="166dp"
        android:layout_marginBottom="80dp"
        android:text="TextView"
        app:layout_constraintBottom_toTopOf="@+id/percentSeekBar"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Check Out Latest Tutorials Here!

Android Studio Loading Animation Between Activities

Progress Dialog is dialog showing a progress indicator and an optional text message or view. The methods of Progress Dialog being used in this tutorial are: ProgressDialog.setTitle() – Used to set title of dialog box ProgressDialog.setMessage() – Used to set dialog message being displayed ProgressDialog.setProgressStyle() – Choose the style of indicator ProgressDialog.dismiss() – Dismiss the…

Python callable()

The callable() method checks if a object is callable. Callable objects are True if object is callable and False if object is not callable. Syntax & Parameters callable(object)  The callable() method takes one argument, an object and returns one of the two values: returns True, if the object appears to be callable.returns False, if the…

Python bytes()

bytes() returns an immutable bytes object, made up of a sequence of integers in the range 0 <=x < 256. The returned bytes sequence is immutable. A mutable bytes sequence can be used instead by calling is bytearry() . Syntax bytes(]]) bytes() takes three optional parameters: source – initialize the array of bytes. Can be String…

Python Ethereum Block Chain Interaction with Web3

This tutorial will show how to interact with the Ethereum blockchain using Python.

To start, the Python library Web3 will need to be installed. The Web3 library allows you to interact with a local or remote Ethereum node, using a HTTP or IPC connection. Using Web3 you will be able to create smart contracts on the Ether blockchain using Python. You can also pull data from current blocks on the block chain and view information like a block’s hash , gas used and nonce. Here is the documentation for Web3 , it is a pretty cool library so definitely check it out.

Once Web3 is installed you will need a Infura account. Infura is a Ethereum node that allow users to interact with Ether blockchain using a API. Blockchain applications need connections to peer-to-peer networks, the Infura network help users quickly connect to the blockchain.

After you create your Infura account you will need to create a project in Infura. The most import item needed is the Project ID. How it works is the Web3 library uses the Infura project’s URL, which is how the Python code can interact with the Ether blockchain.

Set Up Connection

Variable eth_node is where you set your project link. To test if you are connected use infuraConnection.isConnected() if True is returned then connected, False would mean you are not connected.

from web3 import Web3

# Link Project and connecting to Infura
eth_node = 'https://mainnet.infura.io/v3/   #INPUT YOUR PROJECT ID HERE# '

infuraConnection = Web3(Web3.HTTPProvider(eth_node)) 

print("Connection to API :", infuraConnection.isConnected()) #Testing connection 
Get Block

Here you can grab the most recent mined block from the chain

def get_block():
     block = infuraConnection.eth.get_block('latest')
     return print(block)

get_block()

Output :

AttributeDict({'
difficulty': 6127037748199915, 
'extraData': HexBytes('0x486976656f6e2065752d68656176792d322054756258'), 
'gasLimit': 14962851,
 'gasUsed': 14953158,
 'hash': HexBytes('0xcf9e653ef7449329006a762f46552ce1938c9fe64c2eb855283978c6dfb3fed9'), 
 'nonce': HexBytes('0x65ba54d4f3295ee1'), 
'number': 12718638,
 'parentHash': HexBytes('0x49df4d887658e1336aecc785d25caf236633bd20f67325323b1346a87f0679a6'),
 'receiptsRoot': HexBytes('0xd286b411db6d6e8f0d1d95dc91d47cf11650621cfa54413a05eb5dcded7238cb'), 
'sha3Uncles': HexBytes('0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347'),
 'size': 89246, 
'stateRoot': HexBytes('0x4ca51044501148e8e5275c9548133b7bc65d6f381252815e8777aa98d8a2db1d'),
 'timestamp': 1624831185,
 'totalDifficulty': 26819475510492419903587,
 'transactions': [HexBytes('0x32a45c359cdbb2020914e45f5f960d4d232bf7c3fe52bfc654f3719744ac4c81'), 
.................
Get Block Number

The command eth.block_number is used to get the most recent block number

def get_block():
   block = infuraConnection.eth.block_number
   print(block)

get_block()
Get block Hash
block = infuraConnection.eth.block_number  #Get recent Ether block number

if block != 0:
    block_info = infuraConnection.eth.get_block(block).get('hash').hex()  #Grab hash value from block 
    print(block_info)

Output:

0xcf9e653ef7449329006a762f46552ce1938c9fe64c2eb855283978c6dfb3fed9

Python bytearray()

The bytearray() method returns an array of bytes. Syntax bytearray(]]) source – source to initialize the array of bytes string – Converts the string to bytes using str.encode()integer – Creates an array of provided size, all initialized to nulliterable – Creates an array of size equal to the iterable count . Iterable integers must be…

Python breakpoint()

The breakpoint() function is a debugging function that is built into Python 3.7 . Use this built in function by adding breakpoint() where you suspect the error or are wanting to check for bugs. The pdb (Python Debugger) is a interactive source code debugger for Python programs. Python Debugger Commands : Ex. Output Once code…

Python bool()

The bool() function converts a value to a Boolean expression, True or False . If no parameter is given, by default the Boolean returns False. Boolean returns True if the parameter or value is True. Syntax bool([x]) x – is the value being evaluated by standard truth testing procedures. Example Output

Python chr()

The chr() function returns a character that represents the specified unicode.

Syntax

chr(i)

  • The chr() method takes only one integer as argument.
  • The range may vary from 0 to 1,1141,111(0x10FFFF in base 16).
  • The chr() method returns a character whose unicode point is num, an integer.
  • If an integer is passed that is outside the range then the method returns a ValueError.

Example

Creating a String use ASCII characters.

print(chr(67),chr(79),chr(68),chr(69),chr(32),chr(73),chr(84))

Output

C O D E   I T

Python callable()

The callable() method checks if a object is callable. Callable objects are True if object is callable and False if object is not callable.

Syntax & Parameters

callable(object)

 The callable() method takes one argument, an object and returns one of the two values:

  • returns True, if the object appears to be callable.
  • returns False, if the object is not callable.

Example

def callIt(): 
    return 1 
  
# CReating object 
ex = callIt 
print(callable(ex))

#Not Callable 
x= 1
print(callable(x))

Output

True
False 
class Foo:
  def __call__(self):
    print(callable(ex))

ex = Foo()
ex() #calling callable 

Output

True

Python bytes()

bytes() returns an immutable bytes object, made up of a sequence of integers in the range 0 <=x < 256.

The returned bytes sequence is immutable. A mutable bytes sequence can be used instead by calling is bytearry() .

Syntax

bytes(]])

bytes() takes three optional parameters:

  • source – initialize the array of bytes. Can be String or Integer
  • encoding  – if the source is a string, the encoding of the string
  • errors  – the action to take when the encoding conversion fails

Example

Creating empty array of bytes

x = bytes(3)
print(x)

Output

b'\x00\x00\x00'

Introducing a String

str = "CodeIt"

# encoding 'utf-8'
ex1= bytes(str, 'utf-8')

#encdoing 'utf-16'
ex2= bytes(str, 'utf-16')

print(ex1)
print(ex2)

Output

b'CodeIt'
b'\xff\xfeC\x00o\x00d\x00e\x00I\x00t\x00'

Python bytearray()

The bytearray() method returns an array of bytes.

Syntax

bytearray(]])

source - source to initialize the array of bytes
  • string – Converts the string to bytes using str.encode()
  • integer – Creates an array of provided size, all initialized to null
  • iterable – Creates an array of size equal to the iterable count . Iterable integers must be between 0 <= x < 256
  • Without an argument an array size will be set to 0
encoding - if the source is a string, the encoding of the string. Ex. utf-8,ascii
errors - action to take when the encoding conversion fails

Examples

byte array from string

s = "String example"

ex = bytearray(s, 'ascii')
print(ex)

Output

bytearray(b'String exapmle')

Creating byte array from integer

#integer creates array of 3
i = 3

ex = bytearray(i)
print(ex)

Output

bytearray(b'\x00\x00\x00')

Creating byte array from iterable list

list = [1,2,3]

ex = bytearray(list)
print(ex)

Output

bytearray(b'\x01\x02\x03')

Python breakpoint()

The breakpoint() function is a debugging function that is built into Python 3.7 .

Use this built in function by adding breakpoint() where you suspect the error or are wanting to check for bugs.

The pdb (Python Debugger) is a interactive source code debugger for Python programs.

Python Debugger Commands :

c -> continue execution
q -> quit the debugger/execution
n -> step to next line within the same function
s -> step to next line in this function or a called function

Ex.

def Test(x): 
    breakpoint() 
    ex = [x[obj] for obj in range(0, len(x)-2)] 
    return ex 
  
print(Test([1, 2, 3]))

Output

> /home/runner/ue53p3stxbj/main.py(3)Test()
-> ex = [x[obj] for obj in range(0, len(x)-1)]

(Pdb) c # here pdb command C is inputted

[1, 2]

Once code as been executed enter one of the commands in the terminal

Since there is no issue with the above code NO error message is prompted

The code below produce an error. The c pdb command will be used

def Test(x): 
    breakpoint() 
    ex = [x[obj] for obj in range(0, len(x)+1)] 
    return ex 
  
print(Test([1, 2, 3]))

Output

> /home/runner/ue53p3stxbj/main.py(3)Test()
-> ex = [x[obj] for obj in range(0, len(x)+1)]

(Pdb) c

Traceback (most recent call last):
  File "main.py", line 6, in <module>
    print(Test([1, 2, 3])) 
  File "main.py", line 3, in Test
    ex = [x[obj] for obj in range(0, len(x)+1)] 
  File "main.py", line 3, in <listcomp>
    ex = [x[obj] for obj in range(0, len(x)+1)] 
IndexError: list index out of range
 

Python bool()

The bool() function converts a value to a Boolean expression, True or False .

If no parameter is given, by default the Boolean returns False. Boolean returns True if the parameter or value is True.

Syntax

bool([x])
x - is the value being evaluated by standard truth testing procedures.    

Example

# Returns False as x is False
x = 0
print(bool(x))
 
# Returns True as x is True
x = 1
print(bool(x))

# Returns False empty List
x = []
print(bool(x))

# Returns True as x is True
x = ['Python']
print(bool(x))

Output

False
True
False
True