Thursday, February 21, 2013

Add transparent theme to activity


In manifest

<activity

      . . . .  .
    android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen"

. . . . . . .
> 
</activity>

How to create a splash screen


public class SplashActivity extends Activity {

                 private static String TAG = SplashActivity.class.getName();
                   private static long SLEEP_TIME = 5;    // Sleep for some time
                                   @Override
                   protected void onCreate(Bundle savedInstanceState) {
                      super.onCreate(savedInstanceState);
                      setContentView(R.layout.activity_splash);
                 
                      // Start timer and launch main activity
                      IntentLauncher launcher = new IntentLauncher();
                      launcher.start();
                   }
                 
                   private class IntentLauncher extends Thread {
                      @Override
                      /**
                       * Sleep for some time and than start new activity.
                       */
                      public void run() {
                         try {
                            // Sleeping
                            Thread.sleep(SLEEP_TIME*1000);
                         } catch (Exception e) {
                            Log.e(TAG, e.getMessage());
                         }
                 
                         // Start main activity
                         Intent intent = new Intent(SplashActivity.this,mainactivity.class);
                         SplashActivity.this.startActivity(intent);
                         SplashActivity.this.finish();
                      }
                   }
}


In manifest

<activity
           . . . . . .
             android:theme="@android:style/Theme.NoTitleBar.Fullscreen"

. . . . . . . . . .
           >
        </activity>

Set editext input type programmatically

edittext1.setInputType(InputType.TYPE_CLASS_NUMBER);

Saturday, January 26, 2013

Create custom dialog :


code:

final Dialog d = new Dialog(myActivity.this);
d.setContentView(R.layout.mylayout);
d.setTitle("my title");
 final EditText edit = (EditText)d.findViewById(R.id.txtedit);
 Button btn = (Button)d.findViewById(R.id.txtbtn);
d.show();

layout:

<Button
        android:id="@+id/btnAdd"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
      />

    <EditText
        android:id="@+id/txtItem2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="text" />

Change color of alertdialog button


 Button b = dialogf.getButton(DialogInterface.BUTTON_NEGATIVE);
if(b != null){
   b.setBackgroundDrawable(getResources().getDrawable(R.drawable.loginbutton));
  b.setTextColor(getResources().getColor(android.R.color.white));
 }

Iterate through array values and insert to sqlite db:


String [] arrayA ={"a","b","c"};
Value[] adst =new Value[arrayA.length];
for( int i = 0; i < arrayA.length; i++)
{
String something = arrayA[i];
   Value dist =new Value();
    dist.setname(something);
     adst[i]=dist;
}

valuedao.insertInTx(adst);

Delete a row from sqlitetable:


 db.delete("Tablename","coloumnname"+"="+valuetocompare,null);



Removing duplicate rows from sqlite table


db.execSQL("delete from TABLENAME where rowid not in (select min(rowid) from TABLENAME group by COLOUMNNAME);");


Count number of rows in a sqlite table

long numRows = DatabaseUtils.queryNumEntries(db,"Table_name");

Get image from sdcard and put in imageview


File imageFile2 =new File(Environment.getExternalStorageDirectory(),"/images/"+imagef2);

      if(imageFile2!=null)
      {
Bitmap bitmap2 = BitmapFactory.decodeFile(imageFile2.getAbsolutePath());
     imageview.setImageBitmap(bitmap2);
      }

Delete image from sdcard:


 File file  =new File(Environment.getExternalStorageDirectory(),yourfilename);
     file.delete();


Populate AlertDialog with CheckBoxes


boolean[] isChecked = null;
final  List<CharSequence> selectedItems = new ArrayList<CharSequence>();
final CharSequence[] others = {"value1","value2", "value3", "value4" };
AlertDialog.Builder buildnew = new AlertDialog.Builder(this);
buildnew .setTitle("Select ");
buildnew .setMultiChoiceItems(others,isChecked, new DialogInterface.OnMultiChoiceClickListener() {
                  public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if(isChecked)
{  selectedItems.add(others[which]);
}

else
                     {
selectedItems.remove(others[which]);
}
StringBuilder stringBuilder = new StringBuilder();

               for(CharSequence item : selectedItems)
           stringBuilder.append(item + ",");
               edittext.setText(stringBuilder.toString());            
}
});
buildnew.setPositiveButton("Done", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which)
                 {
dialog.dismiss();
}
});
buildnew .create();
buildnew .show();

Sunday, January 20, 2013

Create Excel file and store in sdcard


Create an excel file in android :
Download jxl.jar from
extract the file and  copy the jar file to project – libs fiolder


try the following code in your class file
an excel file will be created in sdcard


String Fnamexls="testfile"  + ".xls";
               File sdCard = Environment.getExternalStorageDirectory();
         File directory = new File (sdCard.getAbsolutePath() + "/newfolder");
         directory.mkdirs();
             File file = new File(directory, Fnamexls);

             WorkbookSettings wbSettings = new WorkbookSettings();

             wbSettings.setLocale(new Locale("en", "EN"));

             WritableWorkbook workbook;
             try {
               int a = 1;
                 workbook = Workbook.createWorkbook(file, wbSettings);
                 //workbook.createSheet("Report", 0);
                 WritableSheet sheet = workbook.createSheet("First Sheet", 0);
                 Label label = new Label(0, 2, "SECOND");
                 Label label1 = new Label(0,1,"first");
                 Label label0 = new Label(0,0,"HEADING");
                 Label label3 = new Label(1,0,"Heading2");
                 Label label4 = new Label(1,1,String.valueOf(a));
                 try {
                                  sheet.addCell(label);
                                   sheet.addCell(label1);
                                  sheet.addCell(label0);
                                  sheet.addCell(label4);
                                  sheet.addCell(label3);
                           } catch (RowsExceededException e) {
                                  // TODO Auto-generated catch block
                                  e.printStackTrace();
                           } catch (WriteException e) {
                                  // TODO Auto-generated catch block
                                  e.printStackTrace();
                           }
             

                 workbook.write();
                 try {
                                  workbook.close();
                           } catch (WriteException e) {
                                  // TODO Auto-generated catch block
                                  e.printStackTrace();
                           }
                 //createExcel(excelSheet);
             } catch (IOException e) {
                 // TODO Auto-generated catch block
                 e.printStackTrace();
             }

export sqlite to excel


Export sqlite db to excel:


Open Sqlitedatabrowser
File open database- select ur db file
After it is opened
Go to file – export – table as csv file




Export table as csv file

Select table name –click Export
Open excel
Goto file - Open

Select -All files in the right side and choose ur file
Then select Delimited

Next –
Select Comma also as delimiter



Next

Finish
Now you can see the db fields in excel sheet
Now go to file – save as – excel
Thus your db is converted to excel.

Export sqlitedb to excel


download software from this link
  
Select
sqlitedatabase  - in source
db location   - in database
next

Select 
Msexcel – in destination
Location where you want to store the excel sheet   - in database
Next
 

Select all tables

Next
Su bmit
Migration completed message is displayed , just ignore the remaining.
Exit
 now you will find all the tables exported to a single excel sheet.

Convert sqlite to excel


Connect to database:



-Database group – local host
-Next

-Database Name – Select the location of database

-Ready
-Ctrl+shft+C
 db will be seen in the recent profiles,Now
Click the object browser(marked in red)
U will find all the tables listed

Right click on the respective table –
Data Management – export data – xcel


Select the format
Export


install apk file to emulator from command line:





first add environment variable (right click computer –properties - advanced settings – environment variable)
PATH – path of adb – (ex:d:\android\platform-tools)

go to command prompt

cd  (adb.exe path)location of adb (ex: cd d:\android\platform-tools )

Adb devices                     – shows list of devices present (emulator which Is active)
Adb install “apk location”       (ex: c:\users\desktop\sample.apk)


General error :
-  failure install failed older sdk
Emulator api level is lesser than the  target api declared in manifest – change it

Editext hint not visible

  If EditText hint is not visible- 


add this
android:ellipsize="start"

Slide-in Animation


slide- in slide out animations for activity transition(left to right):

Intent in = new intetn(this,bactivity);
Startactivity(i);
animateactivity.this.overridePendingTransition(R.anim.slide-in-left,R.anim.slide-out-right);

check if sd card is available:




public static boolean checkStorageAvailability() {
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
}

save image in sdcard


start camera intent and save image in sdcard:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == IMAGE_CAPTURE)
          {
            if (resultCode == RESULT_OK)
          {
            imageName = String.valueOf(System.currentTimeMillis()) + ".jpg";
            }
        }
}

public void startCamera()
   {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
imageName = "newImage"+String.valueOf(System.currentTimeMillis()) + ".jpg";
File file = new File(Environment.getExternalStorageDirectory().getPath(), “/images/" +imageName);
imageUri = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, IMAGE_CAPTURE);

    }

Check if internet is available:



//return true if the application can access the internet

private static boolean haveInternet(Context context) {
NetworkInfo info = ((ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if (info == null || !info.isConnected())
{
return false;
}
if (info.isRoaming()) {
return true;
}
return true;
}

Saturday, January 19, 2013

limit Editext values


Set limit on number of digits entered in edittext :

In layout
Android:maxLength=”2”

Hide soft keyboard


Hide soft keyboard  in edit text:

edit = (EditText) findViewById(R.id.txtedit);
InputMethodManager im = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
im.hideSoftInputFromWindow(edit.getWindowToken(), 0);

Go to gps settings screen


Go to gps settings screen (to check gps availablity):


Intent in = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(in);

Disable Landscape Mode


disable landscape mode for all or one activity:

in manifest
<android . . . >
    . . .
    <manifest . . . >
        . . .
        <application>
            <activity android:name=".MyActivity"
                android:screenOrientation="portrait"
                android:configChanges="keyboardHidden|orientation">
            </activity>
        </application>
    </manifest>
</android>

in activity oncreate

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}

Get Current date with timestamp:


get  current date with timestamp  as  a string  ---

string date = (DateFormat.format("dd-MM-yyyy hh:mm:ss", new java.util.Date()).toString());

Get only time –
String mytime = java.text.DateFormat.getTimeInstance().format(Calendar.getInstance().getTime());

Get only date -
String mydate =java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());


DatePicker widget



call the date dialog by

showDialog(DATE_DIALOG_ID);

declare constant
static final int DATE_DIALOG_ID = 333;



@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
// set date picker as current date
return new DatePickerDialog(this, datePickerListener, year, month,
day);
}
return null;
}

private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {

// when dialog box is closed, below method will be called.
public void onDateSet(DatePicker view, int selectedYear, int selectedMonth, int selectedDay)
 {

year = selectedYear;
month = selectedMonth;
day = selectedDay;

editext.setText(new StringBuilder()
// Month is 0 based, just add 1
.append(day).append("/").append(month + 1).append("/")
.append(year).append(" "));

}
};

Wednesday, January 16, 2013

check if gps is on or off:



public static boolean hasGPSCapability(Context context) {
final LocationManager mgr = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
boolean status = mgr.isProviderEnabled(LocationManager.GPS_PROVIDER);
return status;

android on back button pressed


public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(yourActivity.this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent home = new Intent(yourActivity.this,yourhomeActivity.class);
startActivity(home);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
};


go to phone home screen on back pressed
 public void onBackPressed() {
 AlertDialog.Builder builder = new AlertDialog.Builder(MenuActivity.this);
 builder.setMessage("Are you sure you want to exit?")
        .setCancelable(false)
        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
            Intent intent = new Intent(Intent.ACTION_MAIN);
              intent.addCategory(Intent.CATEGORY_HOME);
              intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
              startActivity(intent);
            }
        })
        .setNegativeButton("No", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                 dialog.cancel();
            }
        });
builder.create();
builder.show();
       }        
 };

populate alertdialog with array


Alertdialog popup with list values:

final CharSequence[] digitList = {"1", "2", "3","4","5","6" };
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select");
builder.setSingleChoiceItems(digitList, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
editest.setText(digitList[which].toString());
dialog.dismiss();
}
});
builder.create();
builder.show();

Tuesday, January 8, 2013

Reading exif info



How to get the Exif info of an image :
Private string  selected imagepath;

if (requestCode == IMAGE_CAPTURE) {
                if (resultCode == RESULT_OK) 
       imageName = String.valueOf(System.currentTimeMillis()) + ".jpg";
    Uri selectedImageUri = data.getData();
selectedImagePath = getRealPathFromURI(selectedImageUri);
Log.w("Path of Capture image", "Camera Image Path :"+ selectedImagePath);
Getexifinfo();
}
}
public String getRealPathFromURI(Uri contentUri) {
                                                try {
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                                                                cursor.moveToFirst();
                                                                return cursor.getString(column_index);
                                                } catch (Exception e) {
                                                                return contentUri.getPath();
                                                }}
private void getexifinfo() {
               
                                                try {
                                                                ExifInterface exif = new ExifInterface(selectedImagePath);        
StringBuilder builder = new StringBuilder();
                               
                                builder.append("Date & Time: " + getExifTag(exif,ExifInterface.TAG_DATETIME) + "\n\n");
                                builder.append("Flash: " + getExifTag(exif,ExifInterface.TAG_FLASH) + "\n");
                                builder.append("Focal Length: " + getExifTag(exif,ExifInterface.TAG_FOCAL_LENGTH) + "\n\n");
                                builder.append("GPS Datestamp: " + getExifTag(exif,ExifInterface.TAG_FLASH) + "\n");
                                builder.append("GPS Latitude: " + getExifTag(exif,ExifInterface.TAG_GPS_LATITUDE) + "\n");
                                builder.append("GPS Latitude Ref: " + getExifTag(exif,ExifInterface.TAG_GPS_LATITUDE_REF) + "\n");
                                builder.append("GPS Longitude: " + getExifTag(exif,ExifInterface.TAG_GPS_LONGITUDE) + "\n");
                                builder.append("GPS Longitude Ref: " + getExifTag(exif,ExifInterface.TAG_GPS_LONGITUDE_REF) + "\n");
                                builder.append("GPS Processing Method: " + getExifTag(exif,ExifInterface.TAG_GPS_PROCESSING_METHOD) + "\n");
                                builder.append("GPS Timestamp: " + getExifTag(exif,ExifInterface.TAG_GPS_TIMESTAMP) + "\n\n");
                                builder.append("Image Length: " + getExifTag(exif,ExifInterface.TAG_IMAGE_LENGTH) + "\n");
                                builder.append("Image Width: " + getExifTag(exif,ExifInterface.TAG_IMAGE_WIDTH) + "\n\n");
                                builder.append("Camera Make: " + getExifTag(exif,ExifInterface.TAG_MAKE) + "\n");
                                builder.append("Camera Model: " + getExifTag(exif,ExifInterface.TAG_MODEL) + "\n");
                                builder.append("Camera Orientation: " + getExifTag(exif,ExifInterface.TAG_ORIENTATION) + "\n");
                                builder.append("Camera White Balance: " + getExifTag(exif,ExifInterface.TAG_WHITE_BALANCE) + "\n");
                               
  TextView info = (TextView)findViewById(R.id.exifinfo);
                               
  info.setText(builder.toString());




(for latitude , longitude the values are retrieved as degrees ,minutes, seconds so we convert to degreee                )
                                                                Float Latitude, Longitude;
                                String attrLATITUDE = exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE);
//this gives the latitude in degrees minutes seconds
                                 String attrLATITUDE_REF = exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE_REF);
                 String attrLONGITUDE = exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE);
 String attrLONGITUDE_REF = exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF);
//convert  to degrees
if(attrLATITUDE_REF.equals("N")){
                                                                                   Latitude = convertToDegree(attrLATITUDE);
                                                                                  }
                                                                                  else{
                                                                                   Latitude = 0 - convertToDegree(attrLATITUDE);
                                                                                  }
  if(attrLONGITUDE_REF.equals("E")){
   Longitude = convertToDegree(attrLONGITUDE);
                                                                                  }
                                                                                  else{
                                                                                   Longitude = 0 - convertToDegree(attrLONGITUDE);
                                                                                  }           
                Toast.makeText(getApplicationContext(),latitude+longitude+ Toast.LENGTH_LONG).show();
                                                } catch (IOException e) {
                                                                // TODO Auto-generated catch block
                                                                e.printStackTrace();
                                                }
               
                                }
               
                                private Float convertToDegree(String stringDMS){
                                                 Float result = null;
                                                 String[] DMS = stringDMS.split(",", 3);

                                                 String[] stringD = DMS[0].split("/", 2);
                                                    Double D0 = new Double(stringD[0]);
                                                    Double D1 = new Double(stringD[1]);
                                                    Double FloatD = D0/D1;

                                                 String[] stringM = DMS[1].split("/", 2);
                                                 Double M0 = new Double(stringM[0]);
                                                 Double M1 = new Double(stringM[1]);
                                                 Double FloatM = M0/M1;
                                                 
                                                 String[] stringS = DMS[2].split("/", 2);
                                                 Double S0 = new Double(stringS[0]);
                                                 Double S1 = new Double(stringS[1]);
                                                 Double FloatS = S0/S1;
                                                 
                                                    result = new Float(FloatD + (FloatM/60) + (FloatS/3600));
                                                 return result;
                                                };