Monday 25 November 2013

Focus problems with list rows and ImageButtons


There has been lot of discussions on this blog about some widgets that steal focus from others - creating behaviour that sounds completely illogical for the uninitiated. So far we have seen how Buttons steal the focus from list rows. The same monster rears its ugly head in this slightly different example. Here we have a simple ListView with list rows. Each list row has a text widget and an ImageButton in it. Now if we code this example innocently without being aware of the tricky focus-stealing effect of ImageButton, list rows cannot be selected.



The example program as it is works nicely. If you click the row, you will get one sort of Toast message. If you click the ImageButton within the row, you will get another Toast message. Now let's observe this XML attribute in res/layout/item.xml:

android:descendantFocusability="blocksDescendants"

Try removing this attribute and notice, that selecting list items does not work anymore. What happened? As explained previously, ImageButton steals the focus from the view group (the list row) it is in. This means that when you click the list row, it is always the ImageButton that captures the event but as it is outside of its screen area, the event is discarded. Therefore we prevented the ImageButton to capture the focus.

Previously I recommended preventing the capture of the focus by making the button non-focusable (android:focusable="false"). Curiously, it does not work in this example so I had to find another way. That's why I shared this example.


Click here to download the example program.

Friday 22 November 2013

Android programming Tips & Tricks


How to Scroll up Screen page on EditText focus ?


ScrollView sv = (ScrollView) findViewById(R.id.LoginScrollView);
              // sv.scrollTo(0, sv.getBottom());
              unm.setOnClickListener(new OnClickListener() {
                     @Override
                     public void onClick(View v) {

                           sv.post(new Runnable() {
                                  public void run() {
                                         sv.fullScroll(ScrollView.FOCUS_DOWN);
                                  }
                           });
                     }

              });


How to Hide Soft keybord on page load of form or Sign In page?

 Set EditText property as 

    android:focusable="true"
    android:focusableTouchMode="true"

or set manifest property for that particular activity as 

  android:windowSoftInputMode="stateHidden"



Encode Bitmap to base64 ?

here is simple method you can use directly
      
       public static String encodeTobase64(Bitmap bitmap) {
              ByteArrayOutputStream baos = new ByteArrayOutputStream();
              bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
              byte[] byteArray = baos.toByteArray();
              String imageEncoded = Base64.encodeToString(byteArray, Base64.DEFAULT);

              Log.e("Base 64 String", imageEncoded);
              return imageEncoded;
       }


Decode Base 64 String to Bitmap?

       public static Bitmap decodeBase64(String input) {
              byte[] decodedByte = Base64.decode(input, 0);
              return BitmapFactory
                           .decodeByteArray(decodedByte, 0, decodedByte.length);
       }

Scale / Resize Bitmap to particular size?

      Bitmap newBitmap = Bitmap.createScaledBitmap(bitmap, 640, 480, false);


Some useful commands:

adb devices – lists which devices are currently attached to your computer
adb install – lets you install an Android application on your phone
adb remount – Remounts your system in write mode – this lets you alter system files on your phone using ADB
adb push – lets you upload files to your phones filesystem
adb pull – lets you download files off your phones filesystem
adb logcat – starts dumping debugging information from your handset to the console – useful for debugging your apps
adb shell – drops you into a basic linux command shell on your phone with no parameters, or lets you run commands directly

Some advanced commands 
device commands:
adb push <local> <remote> - copy file/dir to device
adb pull <remote> <local> - copy file/dir from device
adb sync [ <directory> ] - copy host->device only if changed
(see 'adb help all')
adb shell - run remote shell interactively
adb shell <command> - run remote shell command
adb emu <command> - run emulator console command
adb logcat [ <filter-spec> ] - View device log
adb forward <local> <remote> - forward socket connections
forward specs are one of:
tcp:<port>
localabstract:<unix domain socket name>
localreserved:<unix domain socket name>
localfilesystem:<unix domain socket name>
dev:<character device name>
jdwp:<process pid> (remote only)
adb jdwp - list PIDs of processes hosting a JDWP transport
adb install [-l] [-r] <file> - push this package file to the device and install it
('-l' means forward-lock the app)
('-r' means reinstall the app, keeping its data)
adb uninstall [-k] <package> - remove this app package from the device
('-k' means keep the data and cache directories)
adb bugreport - return all information from the device
that should be included in a bug report.


adb help - show this help message
adb version - show version num


DATAOPTS:
(no option) - don't touch the data partition
-w - wipe the data partition
-d - flash the data partition


scripting:
adb wait-for-device - block until device is online
adb start-server - ensure that there is a server running
adb kill-server - kill the server if it is running
adb get-state - prints: offline | bootloader | device
adb get-serialno - prints: <serial-number>
adb status-window - continuously print device status for a specified device
adb remount - remounts the /system partition on the device read-write
adb reboot [bootloader|recovery] - reboots the device, optionally into the bootloader or recovery program
adb root - restarts the adbd daemon with root permissions
adb usb - restarts the adbd daemon listening on USB
adb tcpip <port> - restarts the adbd daemon listening on TCP on the specified port


networking:
adb ppp <tty> [parameters] - Run PPP over USB.
Note: you should not automatically start a PPP connection.
<tty> refers to the tty for PPP stream. Eg. dev:/dev/omap_csmi_tty1
[parameters] - Eg. defaultroute debug dump local notty usepeerdns


adb sync notes: adb sync [ <directory> ]
<localdir> can be interpreted in several ways:
- If <directory> is not specified, both /system and /data partitions will be updated.
- If it is "system" or "data", only the corresponding partition
is updated.

Booting commands also hold their place and come in very handy while rooting processes and even while Android development. Below are stated such 3 commands:
adb reboot
The command simply reboots your device at any instance

adb reboot recovery
The command reboots a device into recovery mode

adb reboot bootloader
The command reboots a device into its bootloader (fastboot) mode

In case you’re in bootloader mode, your device shall never show any response to ADB commands. But, here comes fastboot in action, which has a limited, but a few and very useful commands. This is the same reason that bootloader mode is often referred to as fastboot mode.
fastboot devices
Displays the device ID of the Android device connected while in bootloader mode.

fastboot reboot
Reboots a device

fastboot reboot-bootloader
Reboots the bootloader

fastboot oem unlock
Initiates the bootloader unlocking sequence

fastboot oem lock
Re-locks the device bootloader

fastboot flash recovery <recovery_image_name.img>
Flashes a recovery image to the device
eg: fastboot flash recovery clockworkmod-6.0.3.1_mako.img

fastboot flash radio <radio_file_name.img>
Flashes the Radio (baseband) image file
eg. fastboot flash radio radio-crespo-i9020xxki1.img

fastboot flash bootloader <bootloader_file_name.img>
Flashes a bootloader image to the device partition
eg. fastboot flash bootloader bootloader-crespo-i9020xxlc2.img

Android - Run/install/debug applications over WiFi?

Connect device via USB and make sure debugging is working.
adb tcpip 5555
adb connect 10.0.0.2:5555 
(replace with device's IP address)
Disconnect USB and proceed with wireless debugging.
adb usb to switch back when done.
No root required!


or Try this 

- disconnect device from usb then tell it to listen on 4455
adb tcpip 4455
restarting in TCP mode port: 4455

- connect to the device using a specified ip:port. my device is using wifi
adb connect 192.168.1.103:4455
connected to 192.168.1.103:4455

- now do normal adb commands over tcp
adb shell

- when your done, you can put it back in USB mode
adb usb
restarting in USB mode



or try this 

If you want to enable wireless adb on the device without connecting with a usb cable at all:

Install a terminal app on the device (like Android Terminal Emulator) Type the following
su
setprop service.adb.tcp.port 5555
stop adbd
start adbd
Since you already have the terminal opened, you can find the find the ip of the device: ip addr show

Then in your debugging environment run command:

adb connect ip.of.the.device
This will make the device to be listed as any other emulators you might have. Note that the tcp will stay opened until you reset the device. You might also want to install WiFi Keep Alive app if you experience often disconnects.

Remember to close the tcp when connecting to public networks if you want to feel safe.You can do the following or simply restart the device:

su
setprop service.adb.tcp.port -1
stop adbd
start adbd

or try this link ( Don't worry All are same Methods :p  )

http://www.jessechen.net/blog/debugging-your-android-app-wirelessly-on-an-android-smartphone/





Thursday 14 November 2013

Friday 8 November 2013

Android Alert Dialog (Dialog, Alert Dialog, Progress Dialog, Date Picker Dialog, Time Picker Dialog, Login Dialog, Date and Time Picker Dialog)


Hi,
Today we have very basic dialog boxes  Example, Here i try to cover all kind of simple default dialog boxes available in android. These are very basic and quite simple.


here is self explanatory project example Download.
Happy Downloadddding :P  opppss  Sorry, I mean
Happy Codddddding :)







Thursday 7 November 2013

Check GPS, Internet and Wifi availability Status in android


Check GPS, Internet and Wifi availability Status in android


Hi guys, here is simple tutorial for frequently used functions as Internet GPS  and WiFi availability in android.
here we created separate utility class and just passing context to the constructor and calling desire functions.
Thats end, simple :)





 have look on code example.
DialogUtility.java

package com.example.availabilitychecker;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.provider.Settings;

public class DialogUtility {

       Context context;

       public DialogUtility(Context context) {
              this.context = context;

       }

       /**
        * Function to show settings alert dialog On pressing Settings button will
        * lauch Settings Options
        * */
       public void showGPSSettingsAlert() {
              AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);

              // Setting Dialog Title
              alertDialog.setTitle("GPS is settings");

              // Setting Dialog Message
              alertDialog
                           .setMessage("GPS is not enabled. Do you want to go to settings menu?");

              // On pressing Settings button
              alertDialog.setPositiveButton("Settings",
                           new DialogInterface.OnClickListener() {
                                  public void onClick(DialogInterface dialog, int which) {
                                         Intent intent = new Intent(
                                                       Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                         context.startActivity(intent);
                                  }
                           });

              // on pressing cancel button
              alertDialog.setNegativeButton("Cancel",
                           new DialogInterface.OnClickListener() {
                                  public void onClick(DialogInterface dialog, int which) {
                                         dialog.cancel();
                                  }
                           });
              // Showing Alert Message
              alertDialog.show();
       }

       /**
        * Display a dialog that user has no internet connection lauch Settings
        * Options
        * */
       public void showInternetSettingsAlert() {
              AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);

              // Setting Dialog Title
              alertDialog.setTitle("Internet Settings");

              // Setting Dialog Message
              alertDialog
                           .setMessage("Internet is not enabled. Do you want to go to settings menu?");

              // On pressing Settings button
              alertDialog.setPositiveButton("Settings",
                           new DialogInterface.OnClickListener() {
                                  public void onClick(DialogInterface dialog, int which) {
                                         Intent intent = new Intent(
                                                       Settings.ACTION_WIRELESS_SETTINGS);
                                         context.startActivity(intent);
                                  }
                           });

              // on pressing cancel button
              alertDialog.setNegativeButton("Cancel",
                           new DialogInterface.OnClickListener() {
                                  public void onClick(DialogInterface dialog, int which) {
                                         dialog.cancel();
                                  }
                           });
              // Showing Alert Message
              alertDialog.show();
       }

       /**
        * Display a dialog that user has no Wifi connection lauch Settings Options
        * */
       public void showBluetoothSettingsAlert() {
              AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);

              // Setting Dialog Title
              alertDialog.setTitle("Wifi Settings");

              // Setting Dialog Message
              alertDialog
                           .setMessage("Wifi is not enabled. Do you want to go to settings menu?");

              // On pressing Settings button
              alertDialog.setPositiveButton("Settings",
                           new DialogInterface.OnClickListener() {
                                  public void onClick(DialogInterface dialog, int which) {
                                         Intent intent = new Intent(
                                                       Settings.ACTION_WIFI_SETTINGS);
                                         context.startActivity(intent);
                                  }
                           });

              // on pressing cancel button
              alertDialog.setNegativeButton("Cancel",
                           new DialogInterface.OnClickListener() {
                                  public void onClick(DialogInterface dialog, int which) {
                                         dialog.cancel();
                                  }
                           });
              // Showing Alert Message
              alertDialog.show();
       }

       /**
        * Check Internet Availability and return true or false Require permitions
        * <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
        * <uses-permission android:name="android.permission.INTERNET" />
        * <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"
        * />
        *
        * @param context
        * @return
        */
       public boolean isInternetConnected() {

              ConnectivityManager cm = (ConnectivityManager) context
                           .getSystemService(Context.CONNECTIVITY_SERVICE);
              NetworkInfo netinfo = cm.getActiveNetworkInfo();

              if (netinfo != null && netinfo.isConnectedOrConnecting()) {
                     android.net.NetworkInfo wifi = cm
                                  .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
                     android.net.NetworkInfo mobile = cm
                                  .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

                     if ((mobile != null && mobile.isConnectedOrConnecting())
                                  || (wifi != null && wifi.isConnectedOrConnecting()))
                           return true;
                     else
                           return false;
              } else
                     return false;
       }

       public boolean isWiFiConnected() {
              // Create object for ConnectivityManager class which returns network
              // related info
              ConnectivityManager connectivity = (ConnectivityManager) context
                           .getSystemService(Context.CONNECTIVITY_SERVICE);
              // If connectivity object is not null
              if (connectivity != null) {
                     // Get network info - WIFI internet access
                     NetworkInfo info = connectivity
                                  .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
                     if (info != null) {
                           // Look for whether device is currently connected to WIFI
                           // network
                           if (info.isConnected()) {
                                  return true;
                           }
                     }
              }
              return false;
       }

       /**
        * requires <uses-permission
        * android:name="android.permission.ACCESS_FINE_LOCATION" />
        *
        * @param context
        * @return
        */

       public boolean isGPSConnected() {
              LocationManager service = (LocationManager) context
                           .getSystemService(context.LOCATION_SERVICE);
              boolean status = service
                           .isProviderEnabled(LocationManager.GPS_PROVIDER);
              return status;
       }
}





and we use this class functions as in our MainActivity.java file 








package com.example.availabilitychecker;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
       Context context;

       @Override
       protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
              context = MainActivity.this;
              Button button = (Button) findViewById(R.id.button1);
              button.setOnClickListener(new OnClickListener() {
                     @Override
                     public void onClick(View v) {

                           DialogUtility dialogUtility = new DialogUtility(context);
                           if (!dialogUtility.isGPSConnected())
                                  dialogUtility.showGPSSettingsAlert();
                           else
                                  Toast.makeText(context, "GPS Available", Toast.LENGTH_SHORT)
                                                .show();
                     }
              });

              Button button2 = (Button) findViewById(R.id.button2);
              button2.setOnClickListener(new OnClickListener() {
                     @Override
                     public void onClick(View v) {

                           DialogUtility dialogUtility = new DialogUtility(context);
                           if (!dialogUtility.isInternetConnected())
                                  dialogUtility.showInternetSettingsAlert();
                           else
                                  Toast.makeText(context, "Internet Available",
                                                Toast.LENGTH_SHORT).show();
                     }
              });

              Button button3 = (Button) findViewById(R.id.button3);
              button3.setOnClickListener(new OnClickListener() {
                     @Override
                     public void onClick(View v) {

                           DialogUtility dialogUtility = new DialogUtility(context);
                           if (!dialogUtility.isWiFiConnected())
                                  dialogUtility.showBluetoothSettingsAlert();
                           else
                                  Toast.makeText(context, "Wifi Available",
                                                Toast.LENGTH_SHORT).show();
                     }
              });

       }

}



activity xml file as 


<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/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/button1"
        android:text="Check Internet Availability" />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/button2"
        android:text="Check Wifi Availability" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:src="@drawable/images" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/imageView1"
        android:text="Check GPS Availability " />

</RelativeLayout>


and we use following permissions in our app 


<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />



and here is complete complete menifest.xml file as




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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.availabilitychecker.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>




thats end, simple  :)

and Here you can download complete working example.


Happpppppy Codddddding :)