Monday, June 18, 2012

Send Data to Another Activity - Simple Android Login

5 comments
In this article you will learn how to send data from one Activity  to another Activity,I created two activity AndroidLoginActivity and LoginSuccess, in the LoinSuccess Activity will display logged user name.




Add OnClickListener to Button and Send Data to next Activity


// Set OnClickListner to the login button 
Button login = (Button) findViewById(R.id.btn_login);

login.setOnClickListener(new View.OnClickListener() {

 @Override
 public void onClick(View v) {
  // Get user Name
  EditText loginName = (EditText) findViewById(R.id.txt_userName);
  String name = loginName.getText().toString();

  // create Intent and set LoginSuccess Activity 
  Intent intent = new Intent(getApplicationContext(),
    LoginSuccess.class);

  // put values to intent which will get in the LoginSuccess    Activity
 
  intent.putExtra("name", name);

  // Start LoginSuccess Activity 
  startActivity(intent);

 }
});




Create AndroidLoginActivity 

Right the project and create Java class and name it as AndroidLoginActivity, copy and past bellow code.


package jsupport.com;

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

public class AndroidLoginActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
       
     /* Set OnClickListner to the login button */
        Button login = (Button) findViewById(R.id.btn_login);
        
        login.setOnClickListener(new View.OnClickListener() {
   
   @Override
   public void onClick(View v) {
    
    EditText loginName = (EditText) findViewById(R.id.txt_userName);  
    String  name  = loginName.getText().toString();
    
    Intent intent  = new Intent(getApplicationContext(),LoginSuccess.class);
    
    intent.putExtra("name", name);
    
    startActivity(intent);
     
   }
  });
    }
}



Create new layout  for AndroidLoginActivity


Android Login



Right click on res/layout , New-> Android XML give the file name as login , copy and past bellow xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <TextView android:text="Login here" android:textAppearance="?android:attr/textAppearanceLarge" android:id="@+id/textView1" android:layout_height="wrap_content" android:layout_width="180dp" ></TextView>
    <TextView android:text="User Name " android:textAppearance="?android:attr/textAppearanceMedium" android:id="@+id/textView2" android:layout_height="wrap_content" android:layout_width="126dp"></TextView>
    <EditText android:layout_height="wrap_content" android:id="@+id/txt_userName" android:layout_width="272dp">
        <requestFocus></requestFocus>
    </EditText>
    <TextView android:text="Password" android:textAppearance="?android:attr/textAppearanceMedium" android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
    <EditText android:layout_height="wrap_content" android:inputType="textPassword" android:id="@+id/password" android:layout_width="272dp"></EditText>
    <Button android:text="Login" android:layout_height="wrap_content" android:layout_width="126dp" android:id="@+id/btn_login" ></Button>
</LinearLayout>



Get Value from Intent


/* Get values from Intent */
 Intent intent =  getIntent();
        
 String name    =  intent.getStringExtra("name");



Create LoginSuccess Activity 


Right the project and create Java class and name it as  LoginSuccess  , copy and past bellow code.


package jsupport.com;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class LoginSuccess extends Activity {

 public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.success);
        
        TextView txt_loggedName = (TextView) findViewById(R.id.txt_loggedName);
        
        /* Get values from Intent */
        Intent intent = getIntent();
        
        String name  = intent.getStringExtra("name");
        
        txt_loggedName.setText(name);
 }
}


Create new layout  for LoginSuccess 


Simple Android Login for beginners




Right click on res/layout , New-> Android XML give the file name as success, copy and past bellow xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content" android:weightSum="1">
    <TextView android:text="Hello" android:textAppearance="?android:attr/textAppearanceLarge" android:id="@+id/textView1" android:layout_width="158dp" android:layout_height="wrap_content" android:layout_weight="0.06"></TextView>
    <TextView android:text="Java Srilankan Support" android:textAppearance="?android:attr/textAppearanceLarge" android:layout_height="wrap_content" android:layout_width="match_parent" android:id="@+id/txt_loggedName"></TextView>
    
</LinearLayout>



Add AndroidLoginActivity and LoginSuccess  to AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="jsupport.com"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="8" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".AndroidLoginActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="LoginSuccess"></activity>

    </application>
</manifest>

AndroidLoginActivity   is the main activity


Download application source code from here  Simple Android Login
Read more...

Friday, June 15, 2012

Create Dynamic JButton with Image and ActionListener - Java Swing

0 comments
In this tutorial you will learn how to create JButton dynamically with Image and the ActionListener . You will be able to change the button height , width horizontal gap and vertical gap in one place.

I have create dummy database class which will return the Main menu items and the Sub menu items.You will see the Main menu item in your JFrame. If you select main Item (FOOD) from the button panel it will load Sub Items from the dummy database class (sub items of the FOOD)


Here are the screen shots

Main menu items


Sub menu items


Create Main Frame


Open NetBeans and create New Project, name it as
DynamicButton

  • Add New JFrame Form give class name as DynamicSwingButton
  • Add these code to your DynamicSwingButton class and import relevant classes and interfaces
  private final static int button_width   =   145;        // button width
private final static int button_height = 140; // button height
private final static int horizontalGap = 10; // horizontal gap in button
private final static int verticalGap = 10; // verticle gap in button
private final static int numberOfColumns= 4; // number of colums in the button panel
private final static int fontSize = 11; // font size of button name
private final static int fontType = Font.BOLD; // font type
private final static String fontName = "Thoma"; // font name
private final static Color fontColor = new Color(0, 51, 255); // font colot

  • Add Scroll Pane to your Frame from the palette and set the height and width to Scroll Pane
  • Add JPanel to the Scroll Pane and change the panel variable name as pnl_button
  • Add bellow function to your DynamicSwingButton class
    private void addMainMenue() {

pnl_button.removeAll();
repaint();

Image img, sub;
ImageIcon icon;
String imagePath,imag = "/com/images/";

ArrayList menue = new ArrayList();
ArrayList itemName = new ArrayList();

for (int size = 0 ; size<ItemDB.mainMenuCodes.length; size++) {
menue.add(ItemDB.mainMenuCodes[size]);
itemName.add(ItemDB.mainMenuDesc[size]);
}

JButton[] buttons = new JButton[menue.size()];

for (int i = 0; i < buttons.length; i++) {

imagePath = imag+menue.get(i).toString()+".jpeg";

URL url = getClass().getResource(imagePath);
// System.out.println(imagePath +" Get Res : " +getClass().getResource(imagePath));

if(url!=null){
img = Toolkit.getDefaultToolkit().getImage(url);
sub = img.getScaledInstance(button_width - 8, button_height - 30, Image.SCALE_FAST);
icon = new ImageIcon(sub);
}
else
icon = new ImageIcon();

buttons[i] = new JButton(itemName.get(i).toString(), icon);
buttons[i].setVerticalTextPosition(AbstractButton.BOTTOM);
buttons[i].setHorizontalTextPosition(AbstractButton.CENTER);

buttons[i].setBorder(javax.swing.BorderFactory.createEtchedBorder());
buttons[i].setFont(new java.awt.Font("Tahoma", 1, 13));
buttons[i].setForeground(new java.awt.Color(0, 51, 255));

buttons[i].setActionCommand(menue.get(i).toString());
buttons[i].addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {
String choice = e.getActionCommand();
addSubmenue(choice);
}
});
}

int b = 0;
int vGap = verticalGap;
int hGap = horizontalGap;
int bLength = buttons.length;
int bRows = bLength/numberOfColumns +1;

L1: for (int j = 0; j <bRows; j++) {
vGap = 10;
for (int k = 0; k < numberOfColumns; k++) {

pnl_button.add(buttons[b], new org.netbeans.lib.awtextra.AbsoluteConstraints(vGap, hGap, button_width, button_height));
repaint();
vGap +=button_width+verticalGap;
b++;
if(b>=bLength){
break L1;
}
}
hGap +=button_height+horizontalGap;
}
pack();
}

private void addSubmenue(String choice) {
pnl_button.removeAll();
repaint();

Image img, sub;
ImageIcon icon;
String imagePath,imag = "/com/images/";

ArrayList menue = new ArrayList();
ArrayList itemName = new ArrayList();

ArrayList list = ItemDB.getSubMenu(choice);
String subCode[] = (String[]) list.get(0);
String subDesc[] = (String[]) list.get(1);

for (int size = 0 ; size<subCode.length; size++) {
menue.add(subCode[size]);
itemName.add(subDesc[size]);
}

JButton[] buttons = new JButton[menue.size()];

for (int i = 0; i < buttons.length; i++) {

imagePath = imag+menue.get(i).toString()+".jpeg";

URL url = getClass().getResource(imagePath);
// System.out.println(imagePath +" Get Reso : " +getClass().getResource(imagePath));

if(url!=null){
img = Toolkit.getDefaultToolkit().getImage(url);
sub = img.getScaledInstance(button_width - 8, button_height - 30, Image.SCALE_FAST);
icon = new ImageIcon(sub);
}
else
icon = new ImageIcon();



buttons[i] = new JButton(itemName.get(i).toString(), icon);
buttons[i].setVerticalTextPosition(AbstractButton.BOTTOM);
buttons[i].setHorizontalTextPosition(AbstractButton.CENTER);

buttons[i].setBorder(javax.swing.BorderFactory.createEtchedBorder());
buttons[i].setFont(new java.awt.Font("Tahoma", 1, 13));
buttons[i].setForeground(new java.awt.Color(0, 51, 255));


buttons[i].setActionCommand(menue.get(i).toString());
buttons[i].addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {
String choice = e.getActionCommand();
addItems(choice);
}
});
}
int b = 0;
int vGap = verticalGap;
int hGap = horizontalGap;
int bLength = buttons.length;
int bRows = bLength/numberOfColumns +1;

L1: for (int j = 0; j <bRows; j++) {
vGap = 10;
for (int k = 0; k < numberOfColumns; k++) {

pnl_button.add(buttons[b], new org.netbeans.lib.awtextra.AbsoluteConstraints(vGap, hGap, button_width, button_height));
repaint();
vGap +=button_width+verticalGap;
b++;
if(b>=bLength){
break L1;
}
}
hGap +=button_height+horizontalGap;
}
pack();
}

private void addItems(String choice) {

if(choice.equals("P"))
choice = "PIZZA";
else if(choice.equals("B"))
choice = "BURGER";
else if(choice.equals("FJ"))
choice = "FRUIT JUICE";
else if(choice.equals("HB"))
choice = "HOT BEVERAGES";
JOptionPane.showMessageDialog(this, "You have select "+choice);
}


  • Go to Window->Navigating-> Inspector, Right Click your Frame and add window open event



  • Add this function to windows opened event
    addMainMenue();

  • Add tow buttons and name one as Back and another as Exit
  • Select Back button and add Action performed event with addMainMenue(); function
  • Select Exit button and add Action performed event with System.exit(0);
  • Add this dummy database class to your project



import java.util.ArrayList;

/**
*
* @author JSupport
*/
class ItemDB {

public static String mainMenuCodes[] = {"FOOD","BEVE","FOOD","BEVE","FOOD","BEVE"};
public static String mainMenuDesc[] = {"FOOD","BEVERAGES","FOOD","BEVERAGES","FOOD","BEVERAGES"};
private static ArrayList list;

public static ArrayList getSubMenu(String mainMenuCodes){

list = new ArrayList();
if(mainMenuCodes.equals("FOOD")){
String subCode[] = {"P","B"};
String subDesc[] = {"PIZZA","BURGER"};

list.add(subCode);
list.add(subDesc);

}else if(mainMenuCodes.equals("BEVE")){
String subCode[] = {"FJ","HB"};
String subDesc[] = {"Fruit Juice","Hot Beverages"};

list.add(subCode);
list.add(subDesc);
}
return list;
}
}

  • Run the DynamicSwingButton frame.

Read more...

Friday, June 8, 2012

Install Android application on Android Device

1 comments

APK Creation in Eclipse and Install on Android Device


In this tutorial you will be learn how to install developed Android application on your Android Device. You must know the correct Android Version of your device before you going to create APK file.Here I am going to install previous Android ListView example with Image and Text  application on android device.

Device is Cisco Cius and the Android Version is 2.2.2 

Android list view on cisco cius


Check API Levels 

Open your android AndroidListView  project in eclipse , you may download it from here AndroidListView. Go to the application property and select android on left pane. Select android version of your device

android project properties


Change the  SDK API Level     <uses-sdk android:minSdkVersion="8" />      according to your version


AndroidManifest.xml


Export Android Application and Create APK file 

Right click on the project and click on Export and select Export Android Application

Export Android Application in Eclipse


Export Android Application in Eclipse


Click next and select create new keystore give the name with location for key, give password and click next.

create android key


Fill required fields in the next screen and give the destination for APK file and finish it.

android key creation

Create Android APK and Install on Android Device


Allow Installation of non-Market Application


Now you create the APK file and it is ready to install on your Android Device. Your android device may give the permission to install your application. Select Unknown Source  Go to Setting -> Application Setting  ->Unknown Source and tick check box which will allow to install non-market application on your device.

Copy APK file to your SD card and insert it to your device, install it and run.




Read more...

Thursday, June 7, 2012

Synthetica Look And Feel Java Swing

19 comments

How to Apply Synthetica Look And Feel to JFrame in Netbeans


Here I am going to explain how to apply Synthetica Look And Feel to a JFrame in Netbeans,in the previous tutorial I was explained how to apply Nimbus Look and Feel Java Swing to a JFrame.You will be able to apply

  • SyntheticaSkyMetallicLookAndFeel
  • SyntheticaBlueMoonLookAndFeel
  • SyntheticaBlueIceLookAndFeel
  • SyntheticaWhiteVisionLookAndFeel
  • and SystemLookAndFeel which will your OS look and feel.
To apply Synthetica look and feel you must add Synthetica libraries to your project class path.

This code will remove your current look and feel which will help to apply new look and feel clearly.

UIManager.removeAuxiliaryLookAndFeel(UIManager.getLookAndFeel());

To apply new look and feel you must use this code snip which will update all Component with new look and feel

SwingUtilities.updateComponentTreeUI(this);



Look and Feel change function


private void changeLookandFeel() {
        try {

            UIManager.removeAuxiliaryLookAndFeel(UIManager.getLookAndFeel());
            SyntheticaLookAndFeel.setWindowsDecorated(false);
            UIManager.setLookAndFeel(UIMANAGER_STRING);

//             for (int i = 0; i < LookAndFeel.getFrames().length; ++i) {
//                SwingUtilities.updateComponentTreeUI(LookAndFeel.getFrames()[i]);
//                SwingUtilities.updateComponentTreeUI(this);
//            }
            SwingUtilities.updateComponentTreeUI(this);

        } catch (Exception ex) {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

Synthetica Blue Moon Look And Feel

Synthetica Blue Moon Look And Feel

Synthetica Blue Moon Look And Feel


Synthetica White Vision Look And Feel

Synthetica White Vision Look And Feel

Synthetica White Vision Look And Feel


System Look And Feel (Windows 7)

System Look And Feel (Windows 7 Look And Feel)


Synthetica Sky Metallic Look And Feel

Synthetica Sky Metallic Look And Feel

Synthetica Sky Metallic Look And Feel


Synthetica Blue Ice Look And Feel

Synthetica Blue Ice Look And Feel

SyntheticaBlueIceLookAndFeel


Download the Netbean project from here Synthetica Look and Feel, you will be find libraries in the lib folder

 
Look And Feel Netbeans Project
Read more...

Tuesday, June 5, 2012

Nimbus Look and Feel Java Swing

4 comments
It is very easy to apply  Nimbus Look and Feel which was introduced in Java SE 6 update 10 release. Copy and past following code before creating the (GUI) Graphical User Interface


Nimbus Look and Feel

nimbus look and feel

Before Applying the Nimbus Look and Feel

Java Look and Feel


try {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
            
        } catch (Exception ex) {
            // If the nibus is not available, GUI will set to the system's look and feel  
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        }
Read more...