Monday, October 12, 2015

java - How to know a variable type

MainActivity.java

package com.cfsuman.me.javaexamples;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Window;
import android.widget.RelativeLayout;
import android.widget.TextView;


public class MainActivity extends AppCompatActivity {

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

        // Set background color for action bar
        getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.RED));

        // Get widget reference from XML layout
        RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl);
        TextView tv = (TextView) findViewById(R.id.tv);

        // Empty the TextView
        tv.setText("");

        // Initialize a new String variable
        String StringVariable = "Innee";
        tv.setText(StringVariable.getClass().getSimpleName() + " : " + StringVariable);

        // Initialize a new Boolean variable
        Boolean BooleanVariable = true;
        tv.setText(tv.getText() + "\n"
                + BooleanVariable.getClass().getSimpleName() + " : " + BooleanVariable);

        // Initialize a new Integer variable
        Integer IntegerVariable = 456;
        tv.setText(tv.getText() + "\n"
                + IntegerVariable.getClass().getSimpleName() + " : " + IntegerVariable);

        // Initialize a new Double variable
        Double DoubleVariable = 125.99;
        tv.setText(tv.getText() + "\n"
                + DoubleVariable.getClass().getSimpleName() + " : " + DoubleVariable);

        // Initialize a new Float type variable
        Float FloatVariable = 5.29f;
        tv.setText(tv.getText() + "\n"
                + FloatVariable.getClass().getSimpleName() + " : " + FloatVariable);

        // Initialize a new Byte type variable
        Byte ByteVariable = 22;
        tv.setText(tv.getText() + "\n"
                + ByteVariable.getClass().getSimpleName() + " : " + ByteVariable);
    }
}
More android examples