Showing posts with label Listview. Show all posts
Showing posts with label Listview. Show all posts

Saturday, 26 April 2014

Device information

I am writing this tutorial as lot of people are asking me about how to get System properties like what is the version,Model,Hardware Manufacturer,Serial and FingerPrint of a device.As well as many of the visitors also request me to post on how to get ip4/ip6 and MAC Address of Device.
    So Today I am creating a simple ListView to show all the list of system properties i mentioned above and a Utility class that will return an Array list of strings to load listView adapter.

OutPut:
Device informationDevice IP and MAC

Create new Android Project
Project Name: DeviceInformation
//tested from 2.3.3 to current android sdk 
Build Target: Android 2.3.3   //or greater than that
Application Name: DeviceInformation
Package Name: com.shaikhhamadali.blogspot.deviceinformation
Create Layout file: activity_device_info

1. code of Layout:


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".DeviceInfo" >

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </ListView>

</RelativeLayout>

2. code of activity:

package com.shaikhhamadali.blogspot.deviceinformation;

import android.os.Bundle;
import android.app.Activity;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class DeviceInfo extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_device_info);
  //Create instance of Listview and assign reference of control we declared in layout
  ListView lv=(ListView)findViewById(R.id.listView1);
  //create an instance of ArrayAdapter and pass context,layout,list of items
  ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
    this, 
    android.R.layout.simple_list_item_1,
    Utility.getlist() );
  //assign adapter to listview
  lv.setAdapter(arrayAdapter); 
 }

}

code of UtilityClass:


package com.shaikhhamadali.blogspot.deviceinformation;

import java.util.ArrayList;
import java.util.List;
import java.net.*;
import java.util.*;   
import org.apache.http.conn.util.InetAddressUtils;

public class Utility {

 public Utility() {

 }
 public static ArrayList<String> getlist(){
  //Create an instance of ArrayList of String.
  ArrayList<String> str=new ArrayList<String>();
  //add information to list
  str.add("Version : "+System.getProperty("os.version"));
  str.add("Version Release : "+android.os.Build.VERSION.RELEASE);
  str.add("Device : "+android.os.Build.DEVICE);
  str.add("Model : "+android.os.Build.MODEL);
  str.add("Product : "+android.os.Build.PRODUCT);
  str.add("Brand : "+android.os.Build.BRAND);
  str.add("Display : "+android.os.Build.DISPLAY);
  str.add("CPU_ABI : "+android.os.Build.CPU_ABI);
  str.add("CPU_ABI2 : "+android.os.Build.CPU_ABI2);
  str.add("Unknown  :"+android.os.Build.UNKNOWN);
  str.add("HARDWARE : "+android.os.Build.HARDWARE);
  str.add("ID : "+android.os.Build.ID);
  str.add("Manufecturer : "+android.os.Build.MANUFACTURER);
  str.add("Serial : "+android.os.Build.SERIAL);
  str.add("Host : "+android.os.Build.HOST);
  str.add("FingerPrint : "+android.os.Build.FINGERPRINT);
  str.add("User : "+android.os.Build.USER);
  str.add("Lan Mac Add : "+getMACAddress("wlan0"));
  str.add("ether Add : "+getMACAddress("eth0"));
  str.add("ipv4 : "+getIPAddress(true));
  str.add("ipv6 : "+getIPAddress(false));
  //return list
  return str; 
 }
 /**
   Returns MAC address of the given interface name like wlan0 or eth0.
   @param interfaceName eth0, wlan0 or NULL=use first interface 
   @return  mac address or empty string
  */
 public static String getMACAddress(String interfaceName) {
  try {
   //create instance of List to store List of NetworkInterfaces
   List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
   //iterate to every item of interfaces
   for (NetworkInterface intf : interfaces) {
    //check only not null interfaces
    if (interfaceName != null) {
     //if interface matches to the required or not 
     if (!intf.getName().equalsIgnoreCase(interfaceName)) continue;
    }
    //get hardware address that is MAC address
    byte[] mac = intf.getHardwareAddress();
    if (mac==null) return "";
    //create instance of StringBuilder
    StringBuilder buf = new StringBuilder();
    //iterate though every byte to format the address in Particular MAC address format.
    for (int idx=0; idx<mac.length; idx++)
     buf.append(String.format("%02X:", mac[idx]));       
    if (buf.length()>0) buf.deleteCharAt(buf.length()-1);
    return buf.toString();
   }
  } catch (Exception ex) { } // for now ignore exceptions
  return "";
 }

 /**
   Get IP address from first non-localhost interface
   @param ipv4  true=return ipv4, false=return ipv6
   @return  address or empty string
  */
 public static String getIPAddress(boolean useIPv4) {
  try {
   //create instance of List to store List of NetworkInterfaces
   List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
   //iterate to every item of interfaces
   for (NetworkInterface intf : interfaces) {
    //create instance of List to store List of InetAddress
    List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
    //iterate to every item of InetAddress list
    for (InetAddress addr : addrs) {
     //check that is loop back address 
     /*Valid IPv4 loopback addresses have the prefix 127/8. 
       The only valid IPv6 loopback address is ::1.*/
     if (!addr.isLoopbackAddress()) {
      //get HostAddress
      String sAddr = addr.getHostAddress().toUpperCase();
      //check that is ipv4
      boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
      //if ipv4 return address 
      if (useIPv4) {
       if (isIPv4) 
        return sAddr;
      } else {
       //or ipv6 
       if (!isIPv4) {
        int delim = sAddr.indexOf('%'); // drop ip6 port suffix
        //return ipv6
        return delim<0 ? sAddr : sAddr.substring(0, delim);
       }
      }
     }
    }
   }
  } catch (Exception ex) { } // for now ignore Exceptions
  return "";
 }
}

3. note that:

  • As I ignored exceptions above but Good practice is to always check that or notify that to users regarding the problem.
  • Above I have used NetworkInterface that represent a network interface of the local device. An interface is defined by its address and a platform dependent name. The class provides methods to get all information about the available interfaces of the system or to identify the local interface of a joined multicast group.
  • Also InetAddress used to get the IPV4 or IPV6 of a device.
  • You may be interested in getting paired devices listget list of sensorsListView from array and array strings.

4. conclusion:

  • Some information about how to device information.
  • Some information about how to get IP and MAC address.
  • know how to create an Array Adapter.
  • Know how to us NetworkInterface class and InetAddress class.

    5. About the post:

    • The code seems to explain itself due to comments, but if you have any questions you can freely ask too!
    •  Don’t mind to write a comment whatever you like to ask, to know,to suggest or recommend.
    •  Hope you enjoy it!
        6. Source Code:
                you can download the source code from: GoogleDriveGithub

        Cheers,
        Hamad Ali Shaikh

        Monday, 14 April 2014

        Buetooth

        Bluetooth:

              Bluetooth connectivity is a common way to share data from one device to another.Normally Bluetooth is used to share Media files like mp3 songs images or videos or files. 

        Bluetooth Device Class:

               Bluetooth class, which describes general characteristics and capabilities of a device. For example, Generally when we connect to a Bluetooth Device like Computer, Laptop, Bluetooth Headset and Bluetooth other peripherals.And the Bluetooth class will specify the general device type such as a phone, a computer, or headset, and whether it's capable of services such as audio or telephony.

        And today I am adding an other basic tutorial to get List of Paired Bluetooth Devices and get the Major Class (Headset, Computer or other Peripheral) of the Paired Bluetooth Devices:

        OutPut:
        onlaunchCheckbluetoothafter enabling bluetooth

        paired devices list
        Create new Android Project
        Project Name: BlueToothPairing
        //tested from 2.3.3 to current android sdk 
        Build Target: Android 2.3.3   //or greater than that
        Application Name: BlueToothPairing
        Package Name: com.shaikhhamadali.blogspot.bluetoothpairing
        Create Layout file: activity_pair

        1. code of Layout:

        <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            android:id="@+id/Main"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
             >
        <TextView 
            android:id="@+id/tVBluetoothState" 
            android:layout_width="fill_parent" 
            android:layout_height="wrap_content" 
            />
        <Button
            android:id="@+id/btnListPairedDevices" 
            android:layout_width="fill_parent" 
            android:layout_height="wrap_content"
            android:text="List Paired Devices" 
            android:enabled="false"
            /> 
        </LinearLayout>
        
        

        2. code of activityies:

           PairingActivity:

        package com.shaikhhamadali.blogspot.bluetoothpairing;
        
        import android.app.Activity;
        import android.app.ActionBar;
        import android.app.Fragment;
        import android.os.Bundle;
        import android.view.LayoutInflater;
        import android.view.Menu;
        import android.view.MenuItem;
        import android.view.View;
        import android.view.ViewGroup;
        import android.os.Build;
        import android.app.Activity;
        import android.bluetooth.BluetoothAdapter;
        import android.content.Intent;
        import android.os.Bundle;
        import android.view.View;
        import android.widget.Button;
        import android.widget.TextView;
        public class PairingActivity extends Activity {
         //Create variables
         private static final int REQUEST_ENABLE_BT = 1;
         private static final int REQUEST_PAIRED_DEVICE = 2;
        
         //declare views/controls
         Button btnListPairedDevices;
         TextView tVBluetoothState;
        
         //declare Bluetooth Adapter
         BluetoothAdapter btAdapter;
         @Override
         protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_pair);
          //get reference of the UI Controls
          btnListPairedDevices = (Button)findViewById(R.id.btnListPairedDevices);
          tVBluetoothState = (TextView)findViewById(R.id.tVBluetoothState);
          //Get Default bluetooth adapter
          btAdapter = BluetoothAdapter.getDefaultAdapter();
          //Check the state of bluetooth
          CheckBlueToothState();
          //set listner for the button.
          btnListPairedDevices.setOnClickListener(btnListPairedDevicesOnClickListener);
         }
        
         private void CheckBlueToothState(){
          //does device support Bluetooth 
          if (btAdapter == null){
           tVBluetoothState.setText("Bluetooth NOT support");
          }else{
           //is Bluetooth enable
           if (btAdapter.isEnabled()){
            //is in discovery mode
            if(btAdapter.isDiscovering()){
             tVBluetoothState.setText("Bluetooth is currently in device discovery process.");
            }else{
             tVBluetoothState.setText("Bluetooth is Enabled.");
             btnListPairedDevices.setEnabled(true);
            }
           }else{
            tVBluetoothState.setText("Bluetooth is NOT Enabled!");
            //Enable Bluetooth by intent 
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
           }
          }
         }
        
         private Button.OnClickListener btnListPairedDevicesOnClickListener= new Button.OnClickListener(){
        
          @Override
          public void onClick(View arg0) {
           // Create instance of intent
           Intent intent = new Intent();
           //set class for intent 
           intent.setClass(PairingActivity.this, ListPairedDevicesActivity.class);
           //and start list activity for result
           startActivityForResult(intent, REQUEST_PAIRED_DEVICE); 
          }};
        
          @Override
          protected void onActivityResult(int requestCode, int resultCode, Intent data) {
           // is the request code for enable bluetooth or the paired devices
           if(requestCode == REQUEST_ENABLE_BT){
            //check Bluetooth state
            CheckBlueToothState();
           }
           if (requestCode == REQUEST_PAIRED_DEVICE){
            //do nothing is result is ok
            if(resultCode == RESULT_OK){
            }
           } 
          }   
        }

           ListPairedDevicesActivity:

        package com.shaikhhamadali.blogspot.bluetoothpairing;
        
        import java.util.Set;
        
        import android.app.ListActivity;
        import android.bluetooth.BluetoothAdapter;
        import android.bluetooth.BluetoothClass;
        import android.bluetooth.BluetoothDevice;
        import android.content.Intent;
        import android.os.Bundle;
        import android.view.View;
        import android.widget.ArrayAdapter;
        import android.widget.ListView;
        
        
        public class ListPairedDevicesActivity extends ListActivity {
        
         @Override
         protected void onCreate(Bundle savedInstanceState) {
          // TODO Auto-generated method stub
          super.onCreate(savedInstanceState);
          //Create ArrayAdapter to store the list of paired Bluetooth Devices
          ArrayAdapter<String> btArrayAdapter= new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1);
          //Create instance of Bluetooth Adapter
          BluetoothAdapter bluetoothAdapter= BluetoothAdapter.getDefaultAdapter();
          //create Set instance to get the set of Paired devices  
          Set<BluetoothDevice> pairedDevices= bluetoothAdapter.getBondedDevices();
          //check that device has paired devices list or not
          if (pairedDevices.size() > 0) {
           //loop through the every paired device.
           for (BluetoothDevice device : pairedDevices) {
            //Get Name of the paired Device   
            String deviceBTName = device.getName();
            //Get Class of the Paired Device
            String deviceBTMajorClass= getBTMajorDeviceClass(device.getBluetoothClass().getMajorDeviceClass());
            //Add name and class of the Paired device
            btArrayAdapter.add(deviceBTName + "\n" + deviceBTMajorClass);
           }
          }
          //Set list Adapter to the ListActivity
          setListAdapter(btArrayAdapter);
        
         }
        
         private String getBTMajorDeviceClass(int major){
          //Types of the Bluetooth Classes
          switch(major){ 
          case BluetoothClass.Device.Major.AUDIO_VIDEO:
           return "AUDIO_VIDEO";
          case BluetoothClass.Device.Major.COMPUTER:
           return "COMPUTER";
          case BluetoothClass.Device.Major.HEALTH:
           return "HEALTH";
          case BluetoothClass.Device.Major.IMAGING:
           return "IMAGING"; 
          case BluetoothClass.Device.Major.MISC:
           return "MISC";
          case BluetoothClass.Device.Major.NETWORKING:
           return "NETWORKING"; 
          case BluetoothClass.Device.Major.PERIPHERAL:
           return "PERIPHERAL";
          case BluetoothClass.Device.Major.PHONE:
           return "PHONE";
          case BluetoothClass.Device.Major.TOY:
           return "TOY";
          case BluetoothClass.Device.Major.UNCATEGORIZED:
           return "UNCATEGORIZED";
          case BluetoothClass.Device.Major.WEARABLE:
           return "AUDIO_VIDEO";
          default: return "unknown!";
          }
         }
        
         @Override
         protected void onListItemClick(ListView l, View v, int position, long id) {
          super.onListItemClick(l, v, position, id);
          //set Result OK and finish the list activity
          Intent intent = new Intent();
          setResult(RESULT_OK, intent);
          finish();
         }
        
        }
        

        3. note that:

        • Good practice is to always check that is bluetooth supported, is Bluetooth ON or not, and is it in discovering mode.
        • As you can see above I have used some common class types that are supported by Bluetooth are listed here on developer.android.com.
        • You can connect to any device after getting list of all paired devices.
        • Learn more about BluetoothEnable Disable Bluetooth.

        4. conclusion:

        • Some information about how to get Bluetooth paired devices list.
        • know how to get Class type of Bluetooth paired devices.
        • Know how to Create List Activity.
        • How to generate list of dynamic items.

          5. About the post:

          • The code seems to explain itself due to comments, but if you have any questions you can freely ask too!
          •  Don’t mind to write a comment whatever you like to ask, to know,to suggest or recommend.
          •  Hope you enjoy it!
              6. Source Code:
                      you can download the source code from: GoogleDriveGithub

              Cheers,
              Hamad Ali Shaikh

              Sunday, 6 April 2014

              Listview


              What is ListView?

                   A child control of View class that shows items in a vertically scrolling list. The items come from the adapter (ListAdapter, ArrayAdapter or CursorAdapter) associated with this view shows in a Listview.
                     ListView is a control that can be used to show bulk of data in a form of list.the data can be items of String Array, number of records from Database ( SQLite ), JSON Array, ArrayList, Hash Map etc.The good thing about ListView is that it is faster, has its own Scroll view to scroll up or down, can have data in form of Strings,Images,videos almost everything.You can use it the way you want by customising a ListView, you can set custom layout for list view with any child view to create a row of ListView like TextView, Button, ImageView, Checkboxes,RadioButtons etc.

              Simple Project on Listview (SimpleListView):

              OutPut:
              listview of weeksmonths in List
              listview of landscape
              listview of landscape week

              Create new Android Project
              Project Name: SimpleListView
              //tested from 2.3.3 to current android sdk 
              Build Target: Android 2.3.3   //or greater than that
              Application Name: Simple List View
              Package Name: com.shaikhhamadali.blogspot.simplelistview
              Create Layout file: activity_simple_list_view

              1. code of Layout:

              <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                  xmlns:tools="http://schemas.android.com/tools"
                  android:layout_width="match_parent"
                  android:layout_height="match_parent" >
              
                  <Button
                      android:id="@+id/btnArrayList"
                      android:layout_width="wrap_content"
                      android:layout_height="wrap_content"
                      android:layout_alignParentLeft="true"
                      android:layout_alignParentTop="true"
                      android:onClick="fromArray"
                      android:text="List from Array" />
              
                  <Button
                      android:id="@+id/btnArrayList2"
                      android:layout_width="wrap_content"
                      android:layout_height="wrap_content"
                      android:layout_alignParentTop="true"
                      android:layout_toRightOf="@id/btnArrayList"
                      android:onClick="fromStringsArray"
                      android:text="List from Strings.xml" />
              
                  <ListView
                      android:id="@+id/listView1"
                      android:layout_width="match_parent"
                      android:layout_height="wrap_content"
                      android:layout_below="@id/btnArrayList" >
                  </ListView>
              
              </RelativeLayout>
              

              2. code of activity:

              package com.shaikhhamadali.blogspot.simplelistview;
              
              
              
              import android.app.Activity;
              import android.os.Bundle;
              import android.view.View;
              import android.widget.ArrayAdapter;
              import android.widget.ListView;
              
              
              public class SimpleListView extends Activity {
               //Array of Week 
               String[] weeks={"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};
               @Override
               protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_simple_list_view);
              
               }
               /**
                * This method will be called on List from Array button click
                * @param View
                * */
               public void fromArray(View v){
                //get reference of list view
                final ListView lv=(ListView)findViewById(R.id.listView1);
                /*create an array adapter and set simple layout
                 * of single text view and pass an array of week described above
                 */
                ArrayAdapter<String> adpt=new ArrayAdapter<String>(this,
                  android.R.layout.simple_list_item_1,weeks);
                //set this adapter to listview
                lv.setAdapter(adpt);
               }
               /**
                * This method will be called on List from Strings.xml button click
                * @param View
                * */
              
               public void fromStringsArray(View v){
                //get reference of list view
                final ListView lv=(ListView)findViewById(R.id.listView1);
                /*create an array adapter and set simple layout
                 * of single text view and pass an array from strings.xml file
                 */
                ArrayAdapter<String> adpt=new ArrayAdapter<String>(this,
                  android.R.layout.simple_list_item_1,getResources().getStringArray(R.array.months));
                //set this adapter to listview
                lv.setAdapter(adpt);
               }
              
              
              }
              
              

              strings.xml:

                   As you see above in activity i have created an array of Strings and here in strings.xml i have created an StringArray items, don't confuse to see this form of array because these both are the same thing.

              <?xml version="1.0" encoding="utf-8"?>
              <resources>
              
                  <string name="app_name">Simple List View</string>
                  <string name="action_settings">Settings</string>
              
                  <string-array name="months">
                      <item>January</item>
                      <item>February</item>
                      <item>March</item>
                      <item>April</item>
                      <item>May</item>
                      <item>June</item>
                      <item>July</item>
                      <item>August</item>
                      <item>September</item>
                      <item>October</item>
                      <item>November</item>
                      <item>December</item>
                  </string-array>
              
              </resources>

              3. note that:

              • Good practice is to use Strings from strings.xml because strings.xml return Strings according to the Locale of device if you create an application for more than one countries.
              • You can use ListView for many purposes to provide list of options for user to select,to show settings menu items etc.
              • You can get all method details of Listview from developer.android.com.
              • Learn more about ListView, ArrayAdapter.

                  4. conclusion:

                  • Some information about how to use ListView.
                  • know how to show Array of Strings in ListView.
                  • Know how to load StringsArray from strings.xml in ListView.

                    5. About the post:

                    • The code seems to explain itself due to comments, but if you have any questions you can freely ask too!
                    •  Don’t mind to write a comment whatever you like to ask, to know,to suggest or recommend.
                    •  Hope you enjoy it!
                        6. Source Code:
                                you can download the source code from Gdrive,Github.

                        Cheers,
                        Hamad Ali Shaikh