Pages

Friday, November 1, 2013

Get Files list from assets folder and sub folder files in android

Hello,
In this posting How to get files list from assets folder and sub folder.




It'a show files to array of String.

import java.io.IOException;

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

public class ReadAssetsFolderActivity extends Activity {

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

  TextView txt = (TextView) findViewById(R.id.textView1);
  //here write folder name which one added assets folder
  
  String[] myfilesfolderlist = listAssetFiles("Myfiles");  
  
  txt.append("Myfiles/Subfolder");
  txt.append("\n");
  
  for (int i = 0; i < myfilesfolderlist.length; i++) {
   txt.append(myfilesfolderlist[i]);
   txt.append("\n");
  }
  String[] mysubfolderlist = listAssetFiles("Myfiles/Subfolder");
  txt.append("\n");
  txt.append("Myfiles/Subfolder");
  txt.append("\n");
  txt.append("\n");
  
  for (int i = 0; i < mysubfolderlist.length; i++) {
   txt.append(mysubfolderlist[i]);
   txt.append("\n");
  }
 }

 //Method for get files from Assets Folder and sub folder  
 private String [] listAssetFiles(String path)  
 {  
  String [] list;  
  try  
  {  
   list = ReadAssetsFolderActivity.this.getAssets().list(path);  
   if (list.length > 0)  
   {  
    return list;  
   }  
  }catch (IOException e)  
  {  
  }  
  return null;  
 }  

}


Output : 



Thank you :)

Friday, June 21, 2013

Set Gradient color in TextView.

Hello Everyone! Today I am going to post to set gradiant color in TextView using LinearGradient, RadialGradient.

LinearGradient

Add some code in onCreate() method.



1>
TextView txt1 = (TextView) findViewById(R.id.textview);
int[] color = {Color.DKGRAY,Color.CYAN};
float[] position = {0, 1};
TileMode tile_mode = TileMode.MIRROR; // or TileMode.REPEAT;
LinearGradient lin_grad = new LinearGradient(0, 0, 0, 50,color,position, tile_mode);
Shader shader_gradient = lin_grad;
txt1.getPaint().setShader(shader_gradient);
   




2>
TextView txt1 = (TextView) findViewById(R.id.textview);
int[] color = {Color.DKGRAY,Color.CYAN};
float[] position = {0, 1};
TileMode tile_mode0= TileMode.REPEAT; // or TileMode.REPEAT;
 LinearGradient lin_grad0 = new LinearGradient(0, 0, 0, 200,color,position, tile_mode0);
Shader shader_gradient0 = lin_grad0;
txt1.getPaint().setShader(shader_gradient0);



See more detail of the LinearGradient

RedialGradient


1>  
TextView txt1 = (TextView) findViewById(R.id.textview);
int[] color = {Color.DKGRAY,Color.CYAN};
TileMode tile_mode1 = TileMode.REPEAT;// or TileMode.REPEAT;
RadialGradient rad_grad = new RadialGradient(0, 3, 5, color[0], color[1], tile_mode1);
Shader shader_gradient1 = rad_grad;
txt1.getPaint().setShader(shader_gradient1);



See more detail of the RedialGradient





Saturday, May 4, 2013

How to get Device Unique ID in Android


Hello everyone! Here posting to get unique Device-ID in android. In android require the Unique ID in some special case when developing application.

Ways to get device id in Android
  • Unique number (IMEI, MEID, ESN, IMSI)
  • MAC Address
  • ANDROID_ID

Unique number (IMEI, MEID, ESN, IMSI)

TelephonyManager.getDeviceId() is required to return (depending on the network technology) the IMEI, MEID, ESN and IMSI of the phone, which is unique to that piece of hardware.


The IMEI, MEID, ESN, IMSI can be defined as follows:
  • IMEI( International Mobile Equipment Identity ) - The unique number to identify GSM, WCDMA mobile phones as well as some satellite phones
  • MEID(Mobile Equipment IDentifier)  - The globally unique number identifying a physical piece of CDMA mobile station equipment, the MEID was created to replace ESNs(Electronic Serial Number)
  • ESN(Electronic Serial Number)  - The unique number to identify CDMA mobile phones
  • IMSI(International Mobile Subscriber Identity)  - The unique identification associated with all GSM and UMTS network mobile phone users
To get the Device ID, you would include the following code in your project:


import android.content.Context;
import android.telephony.TelephonyManager;

String imeistring=null;                        
String imsistring=null;

    TelephonyManager telephonyManager;                                            
    telephonyManager  = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);

    /*
    * getDeviceId() function Returns the unique device ID.
    * for example,the IMEI for GSM and the MEID or ESN for CDMA phones. 
    */                                                               
    imeistring = telephonyManager.getDeviceId();

    /*
    * getSubscriberId() function Returns the unique subscriber ID,
    * for example, the IMSI for a GSM phone.
    */
    imsistring = telephonyManager.getSubscriberId();    


To allow read only access to phone state add permission READ_PHONE_STATE in the AndroidManifest.xml

<uses-permission android:name="android.permission.READ_PHONE_STATE" /> 


MAC Address


It may be possible to retrieve a Mac address from a device’s Wi-Fi or Bluetooth hardware. But, it is not recommended using this as a unique identifier.


Device should have Wi-Fi (where not all devices have Wi-Fi)
If Wi-Fi present in Device should be turned on otherwise does not report the MAC address

You would include the following code in your project for get MAC Address:


import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

 String macAddress=null;
    WifiManager wifiManager = ( WifiManager ) getSystemService(Context.WIFI_SERVICE);
    WifiInfo wInfo = wifiManager.getConnectionInfo();
    String macAddress = wInfo.getMacAddress();
    if (macAddress != null)
        macAddress = macAddress;

To allow only access to wifi state add permission ACCESS_WIFI_STATE in the AndroidManifest.xml

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

ANDROID_ID

In ANDROID_ID. A 64-bit number (as a hex string) that is randomly generated on the device's first boot and should remain constant for the lifetime of the device (The value may change if a factory reset is performed on the device.) ANDROID_ID seems a good choice for a unique device identifier.

To retrieve the ANDROID_ID for using Device ID, please refer to example code below


import android.provider.Settings;

              String androidId = Settings.Secure.getString(getContentResolver(), 
                                         Settings.Secure.ANDROID_ID);

Not 100% reliable of Android prior to 2.2 (“Froyo”) devices
Also, there has been at least one widely-observed bug in a popular handset from a major manufacturer, where every instance has the same ANDROID_ID.


Sample Example

Create the project "com.uniqueid" with the activity "UniqueDeviceID ".

Class :-  UniqueDeviceID.java


  import android.app.Activity;
  import android.content.Context;
  import android.net.wifi.WifiInfo;
  import android.net.wifi.WifiManager;
  import android.os.Bundle;
  import android.provider.Settings;
  import android.telephony.TelephonyManager;
  import android.view.View;
  import android.view.View.OnClickListener;
  import android.widget.Button;
  import android.widget.TextView;
 
  public class UniqueDeviceID extends Activity implements OnClickListener {

       Button bt;
       TextView txt_View;

       /** Called when the activity is first created. */
       @Override
       public void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.main);

              bt=(Button)findViewById(R.id.button1);
              txt_View =(TextView)findViewById(R.id.textView1);       
              bt.setOnClickListener(this);     
  }

  @Override
  public void onClick(View v) {
       // TODO Auto-generated method stub
       String imeistring=null;                        
       String imsistring=null;

       TelephonyManager   telephonyManager  = 
(TelephonyManager)getSystemService( Context.TELEPHONY_SERVICE );

       /*
        * getDeviceId() function Returns the unique device ID.
        * for example,the IMEI for GSM and the MEID or ESN for CDMA phones. 
        */                           
       imeistring = telephonyManager.getDeviceId();
       txt_View.append("IMEI No : "+imeistring+"\n");


       /*
        * getSubscriberId() function Returns the unique subscriber ID,
        * for example, the IMSI for a GSM phone.
        */                                                                                                             
       imsistring = telephonyManager.getSubscriberId();                                      
       txt_View.append("IMSI No : "+imsistring+"\n");

/*
        * returns the MacAddress             
        */

       WifiManager wifiManager =
(WifiManager) getSystemService(Context.WIFI_SERVICE);
       WifiInfo wInfo = wifiManager.getConnectionInfo();
       String macAddress = wInfo.getMacAddress();
       if (macAddress == null)
              txt_View.append( "MAC Address : " + macAddress + "\n" );
       else
              txt_View.append( "MAC Address : " + macAddress + "\n" );
       }


       /*
        * Settings.Secure.ANDROID_ID returns the unique DeviceID
        * Works for Android 2.2 and above                         
        */
       String androidId = Settings.Secure.getString(getContentResolver(), 
                     Settings.Secure.ANDROID_ID);                          
       txt_View.append( "AndroidID : " + androidId + "\n" );

      
  }


Change the layout "main.xml" to the following.


  <?xml version="1.0" encoding="utf-8"?>
  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      android:orientation="vertical"
      android:padding="10dp" >

      <TextView
          android:layout_width="fill_parent"
          android:layout_height="wrap_content" />

      <Button
          android:id="@+id/button1"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="GetDeviceID" >
      </Button>

      <TextView
          android:id="@+id/textView1"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content" >
      </TextView>

  </LinearLayout>

Add the permission "READ_PHONE_STATE" and  to "AndroidManifest.xml" to allow your application to access  WIFI and PHONE state.


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

      <uses-sdk
          android:minSdkVersion="7" />

      <uses-permission android:name="android.permission.READ_PHONE_STATE" />
      <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

      <application
          android:allowBackup="true"
          android:icon="@drawable/ic_launcher"
          android:label="@string/app_name"
          android:theme="@style/AppTheme" >
          <activity
              android:name="com.uniqueid.UniqueDeviceID"
              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>



Output :- 
Below image shows the output of above sample example.

More Reference Like here


Download Sample code ClickHere

 

Monday, April 1, 2013

How to get Hash Key for integarte facebook SDK in android application


Hello Everyone today I am posting to get Hash Key for Facebook integration.




There is a two way to get Hash Key.

1. Using CMD

keytool -exportcert -alias androiddebugkey -keystore "C:\Users\User\.android\debug.keystore" | openssl sha1 -binary | openssl base64

and then press Enter. Insert password: android

 - You will get your hash key for debug.keystore.

 - When you export a signed APK and you create keystore for application, just replace in cmd debugkeystore alias with your alias for app, keystore path with path to your new created keystore for app and insert password for your app.keystore and you will get a new hash key for your signed app.

2. Just Copy below code in Activity class:

Open up the Your Activity class and make the following temporary change to the onCreate() method:
This is easy to use other then ssl and so.

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import android.app.Activity;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;

public class MainActivity extends Activity
{
 @Override
 public void onCreate(Bundle savedInstanceState) 
 {
  super.onCreate(savedInstanceState);

  // Add code to print out the key hash
  try {
   
   PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_SIGNATURES);
   
   for (Signature signature : info.signatures) 
   {
    MessageDigest md = MessageDigest.getInstance("SHA");
    md.update(signature.toByteArray());
    Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
   }
   
  } catch (NameNotFoundException e) {
   Log.e("name not found", e.toString());
  } catch (NoSuchAlgorithmException e) {
   Log.e("no such an algorithm", e.toString());
  }
 }
}

If you Run app without signed APK then You will get your hash key for debug.keystore.
When you export a signed APK, just signed APK with your keystore and Run the Application.

You can delete the code after knowing the key ;)
enjoy !

Note :- If you getting below error in Facebook integration.
A non-native Login Dialog is displayed that includes an error message at the top:

''..App is Misconfigured for facebook login...''.

Besides double checking your key hash generation steps.

Monday, February 4, 2013

Used your existing SQLite database file in Android Application

Here, I am posting to how to use existing SQLite database file in android application. follow below steps.

1. Make the SQLite database file.

If you don't have a sqlite manager I recommend you to download the opensource SQLite Database Browser available for Win/Linux/Mac. Make database file.

2. Use this database in your Android application.

Now put your database file in the "assets" folder of your project and create a Database Helper class by extending the SQLiteOpenHelper class


public class Databasehelper extends SQLiteOpenHelper
{
      private SQLiteDatabase myDataBase;
      private final Context myContext;
      private static final String DATABASE_NAME = "db.sqlite";
      public final static String DATABASE_PATH = "";
      public static final int DATABASE_VERSION = 1;
      //public static final int DATABASE_VERSION_old = 1;
      //Constructor

      public Databasehelper(Context context)
      {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
            this.myContext = context;
            DATABASE_PATH = myContext.getDatabasePath(DATABASE_NAME).toString();
      }

      //Create a empty database on the system
      public void createDatabase() throws IOException
      {
           boolean dbExist = checkDataBase();
            if(dbExist)
            {
                  Log.v("DB Exists", "db exists");
                  // By calling this method here onUpgrade will be called on a
                  // writeable database, but only if the version number has been
                  // bumped
                  //onUpgrade(myDataBase, DATABASE_VERSION_old, DATABASE_VERSION);
           }         
            boolean dbExist1 = checkDataBase();
            if(!dbExist1)
            {
                  this.getReadableDatabase();
                  try
                  {
                        this.close();    
                        copyDataBase();
                  }
                  catch (IOException e)
                  {
                        throw new Error("Error copying database");
                  }
            }
      }

      //Check database already exist or not
      private boolean checkDataBase()
      {
            boolean checkDB = false;
            try
            {
                  String myPath = DATABASE_PATH;
                  File dbfile = new File(myPath);
                  checkDB = dbfile.exists();
            }
            catch(SQLiteException e)
            {
            }
            return checkDB;
      }

      //Copies your database from your local assets-folder to the just created empty database in the system folder

      private void copyDataBase() throws IOException
      {
            String outFileName = DATABASE_PATH;
            OutputStream myOutput = new FileOutputStream(outFileName);
            InputStream myInput = myContext.getAssets().open(DATABASE_NAME);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = myInput.read(buffer)) > 0)
            {
                  myOutput.write(buffer, 0, length);
            }
            myInput.close();
            myOutput.flush();
            myOutput.close();
      }

      //delete database
      public void db_delete()
      {
            File file = new File(DATABASE_PATH);
            if(file.exists())
            {
                  file.delete();
                  System.out.println("delete database file.");
            }
      }

      //Open database
      public void openDatabase() throws SQLException
      {
            String myPath = DATABASE_PATH;
            myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
      }

      public synchronized void closeDataBase()throws SQLException
      {
            if(myDataBase != null)
                  myDataBase.close();
            super.close();
      }

      public void onCreate(SQLiteDatabase db)
      {
      }

      public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
      {    
            if (newVersion > oldVersion)
            {
                  Log.v("Database Upgrade", "Database version higher than old.");
                  db_delete();
            }
      }
      //add your public methods for insert, get, delete and update data in database.
}
Now you can create a new instance of this DataBaseHelper class and call the createDataBase() and openDataBase() methods.


DataBaseHelper myDbHelper = new DataBaseHelper();
    myDbHelper = new DataBaseHelper(this);
    try {
          myDbHelper.createDataBase();
    } catch (IOException ioe) {
          throw new Error("Unable to create database");
    }
    try {
          myDbHelper.openDataBase();
    }catch(SQLException sqle){
          throw sqle;
    }


Friday, February 1, 2013

Enable & Disable Key Lock In android Application

key Lock Enable and Disable in android application



Function for Disable Keylock

// object....


KeyguardManager keyguardManager;
KeyguardLock lock;

public void Disable_AutoLock() {   
 getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
 keyguardManager = (KeyguardManager) getSystemService(Activity.KEYGUARD_SERVICE);
 lock = keyguardManager.newKeyguardLock(KEYGUARD_SERVICE);       
 lock.disableKeyguard();
}

Function for enable KeyLock


public void Enable_AutoLock()
{
   lock.reenableKeyguard();
}

Need to add permission in AndoridManifest.xml 
  

<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
<uses-permission android:name="android.permission.WAKE_LOCK" />