Thursday, October 22, 2015

Adb push-pull to your android device sdcard

First cd your path, where adb installed, copy and paste here any file to transfer..
then Shift+Right click and open command prompt.

now make sure that device is connected to pc via cable with adb driver installed on pc.

call this command now to check devices:

C:\androidsdk\platform-tools>adb devices
List of devices attached
HT359W917815    recovery

Now push any file to your device:

C:\androidsdk\platform-tools>adb push "ViperOne+9.0.0-fix_3.zip" /sdcard

it will take some time to transfer but you cant see the progress.
it will return following response after finishing transfer.

3622 KB/s (2010320545 bytes in 541.982s).

you just need device path of file to pull to your adb location

adb pull /sdcard/file.apk

Monday, October 12, 2015

SharedPreference Usage Example



Common for set values and get values

SharedPreferences sharedPreferences = getSharedPreferences("Pref_Tag", Context.MODE_PRIVATE);

Set values in Preference

SharedPreferences.Editor editor = sharedPreferences.edit();

editor.putString("String_Tag","NameToStore");
editor.putInt("Int_Tag", IntToStore);

//commit to save 
editor.commit();

Get values from Preference

String name = sharedPreferences.getString("String_Tag", "StringInCaseOfNoReturns");
int number = sharedPreferences.getString("Int_Tag", IntInCaseOfNoReturns);

Clear values from Preference

editor.clear();

Note:- You can not get preferences values, if values are stored on same activity, and you are on same page, and page is not destroyed yet, until you initialize SharedPreferences again before getting value.

Call AlertDialog in background thread, as well on Main thread.

Make sure to put this permission to manifest:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

public static void callDialog(Context context){
    AlertDialog.Builder alertDialogBiulder;
    alertDialogBiulder =
            new AlertDialog.Builder(context)
                    .setTitle("Title")
                    .setMessage("Would you like to do certain things?")
                    .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            //do certain things
                        }
                    })
                    .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    })
                    .setIcon(android.R.drawable.ic_dialog_alert);

    AlertDialog alertDialog = alertDialogBiulder.create();
    alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
    alertDialog.show();
}

Saturday, October 3, 2015

Set Custom font using extended TextView Class

Make sure to put otf, ttf to your assets folder

I choose to put assets --> fonts(folder) --> custom.otf or ttf

import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;

public class TextViewCustoma extends TextView {
    public TextViewMonaBella(Context context) {
        super(context);
        setTypeface(context);
    }

    public TextViewMonaBella(Context context, AttributeSet attrs) {
        super(context, attrs);
        setTypeface(context);
    }

    public TextViewMonaBella(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setTypeface(context);
    }

    public void setTypeface(Context context) {
        Typeface face = Typeface.createFromAsset(context.getAssets(), "fonts/" + "custom.otf");
        this.setTypeface(face);
    }
}

and set to XML

<com.example.TextViewCustom
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

Wednesday, June 3, 2015

Get Screen Size of Device

If you want to get Screen Size of Device then do it as follows
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
and if you are using in API < 13 then use
Display display = getWindowManager().getDefaultDisplay(); 
int width = display.getWidth();  // deprecated
int height = display.getHeight();

Friday, March 20, 2015

Set Image from gallary/Camera to imageview and option to crop it

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.imageloader.CropOptionAdapter;



ImageView profilePhoto;
OutputStream output;

private static final int PICK_FROM_CAMERA = 1;
private static final int CROP_FROM_CAMERA = 2;
private static final int PICK_FROM_FILE = 3;

AlertDialog.Builder builder11  =  new AlertDialog.Builder(this);
private Uri mImageCaptureUri;
public File imagePath = new File(new File(Environment
.getExternalStorageDirectory().getAbsolutePath()
+ "/.profilePhoto/"), "myprofile.png");
int photoSize = 200;

final String[] items = new String[] { "Take from camera",
"Select from gallery" };
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.select_dialog_item, items);

ProfilePhoto.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {

builder11.setTitle("Select Image");
builder11.setAdapter(adapter,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) { // pick
// from camera
if (item == 0) {
Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);

mImageCaptureUri = Uri.fromFile(new File(
Environment
.getExternalStorageDirectory(),
"tmp_avatar_"
+ String.valueOf(System
.currentTimeMillis())
+ ".jpg"));

intent.putExtra(
android.provider.MediaStore.EXTRA_OUTPUT,
mImageCaptureUri);

try {
intent.putExtra("return-data", true);

startActivityForResult(intent,
PICK_FROM_CAMERA);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
} else { // pick from file
Intent intent = new Intent();

intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);

startActivityForResult(Intent
.createChooser(intent,
"Complete action using"),
PICK_FROM_FILE);
}
}
});

final AlertDialog dialog = builder11.create();
dialog.show();
}
});

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK)
return;

switch (requestCode) {
case PICK_FROM_CAMERA:
doCrop();

break;

case PICK_FROM_FILE:
mImageCaptureUri = data.getData();
if (mImageCaptureUri == null) {
return;
}
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(mImageCaptureUri,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();

Bitmap bitmap = BitmapFactory.decodeFile(picturePath);
Bitmap resized = Bitmap.createScaledBitmap(bitmap,
photoSize, photoSize, true);

                        // getRoundedRectBitmap method is given below
Bitmap newBitmap = getRoundedRectBitmap(resized,
photoSize);

                   
try {
// Find the SD Card path
File filepath = Environment.getExternalStorageDirectory();

// Create a new folder in SD Card
File dir = new File(filepath.getAbsolutePath()
+ "/.facebookPhoto/");
if (!dir.exists()) {
dir.mkdirs();
}

// Create a name for the saved image
File file = new File(dir, "myprofile.png");
output = new FileOutputStream(file);

// Compress into png format image from 0% - 100%
newBitmap.compress(Bitmap.CompressFormat.PNG, 100, output);
output.flush();
output.close();
} catch (Exception e) {
e.printStackTrace();
}
doCrop();

break;

case CROP_FROM_CAMERA:
Bundle extras = data.getExtras();
Bitmap roundPreview = null;
if (extras != null) {
Bitmap photo = extras.getParcelable("data");
Bitmap resize = Bitmap.createScaledBitmap(photo,
photoSize, photoSize, true);

roundPreview = getRoundedRectBitmap(resize,
.photoSize);
// FBMainPhoto.setImageBitmap(roundPreview);
}
try {
// Find the SD Card path
File filepath = Environment.getExternalStorageDirectory();

// Create a new folder in SD Card
File dir = new File(filepath.getAbsolutePath()
+ "/.profilePhoto/");
if (!dir.exists()) {
dir.mkdirs();
}

// Create a name for the saved image
File file = new File(dir, "myprofile.png");
output = new FileOutputStream(file);

// Compress into png format image from 0% - 100%
roundPreview.compress(Bitmap.CompressFormat.PNG, 100, output);
output.flush();
output.close();
} catch (Exception e) {
e.printStackTrace();
}
File f = new File(mImageCaptureUri.getPath());

if (f.exists())
f.delete();

ProfilePhoto.setImageBitmap(BitmapFactory.decodeFile(imagePath
.getAbsolutePath()));

}
}

private void doCrop() {
final ArrayList<com.playearn.reward.imageloader.CropOption> cropOptions = new ArrayList<com.playearn.reward.imageloader.CropOption>();

Intent intent = new Intent("com.android.camera.action.CROP");
intent.setType("image/*");
intent.putExtra("scaleUpIfNeeded", true);
List<ResolveInfo> list = getPackageManager().queryIntentActivities(
intent, 0);

int size = list.size();

if (size == 0) {
Toast.makeText(this, "Can not find image crop app",
Toast.LENGTH_SHORT).show();

return;
} else {
intent.setData(mImageCaptureUri);

intent.putExtra("outputX", 150);
intent.putExtra("outputY", 150);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
intent.putExtra("return-data", true);

if (size == 1) {
Intent i = new Intent(intent);
ResolveInfo res = list.get(0);

i.setComponent(new ComponentName(res.activityInfo.packageName,
res.activityInfo.name));

startActivityForResult(i, CROP_FROM_CAMERA);
} else {
for (ResolveInfo res : list) {
final com.example.imageloader.CropOption co = new com.example.imageloader.CropOption();

co.title = getPackageManager().getApplicationLabel(
res.activityInfo.applicationInfo);
co.icon = getPackageManager().getApplicationIcon(
res.activityInfo.applicationInfo);
co.appIntent = new Intent(intent);

co.appIntent
.setComponent(new ComponentName(
res.activityInfo.packageName,
res.activityInfo.name));

cropOptions.add(co);
}

CropOptionAdapter adapter = new CropOptionAdapter(
getApplicationContext(), cropOptions);

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose Crop App");
builder.setAdapter(adapter,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
startActivityForResult(
cropOptions.get(item).appIntent,
CROP_FROM_CAMERA);
}
});

builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {

if (mImageCaptureUri != null) {
getContentResolver().delete(mImageCaptureUri, null,
null);
mImageCaptureUri = null;
}
}
});

AlertDialog alert = builder.create();
alert.show();
}
}
}

public Bitmap getRoundedRectBitmap(Bitmap bitmap, int pixels) {
Bitmap result = null;
try {
result = Bitmap.createBitmap(pixels, pixels,
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(result);

int color = 0xff424242;
Paint paint = new Paint();
Rect rect = new Rect(0, 0, pixels, pixels);

paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawCircle(pixels / 2, pixels / 2, pixels / 2, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);

} catch (NullPointerException e) {
} catch (OutOfMemoryError o) {
o.printStackTrace();
}
return result;
}

Add this two permission to androidMenifest,
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Here is, needed ImageLoader Files,
https://drive.google.com/file/d/0B0gbeiEUEyH-V0dpdDVEU1Y3S2M/view?usp=sharing


Thursday, March 19, 2015

Date Picker with age limitation

DatePicker BirthD;
BirthD = (D..P..) findviewbyId(....);

BirthD.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(
BirthD.getWindowToken(), 0);
int mYear, mMonth, mDay;
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);

DatePickerDialog dt = new DatePickerDialog(SignUpActivity.this,
new OnDateSetListener() {

@Override
public void onDateSet(DatePicker arg0, int yr,
int mo, int day) {
Calendar userAge = new GregorianCalendar(yr,
mo, day);
Calendar minAdultAge = new GregorianCalendar();
minAdultAge.add(Calendar.YEAR, -16);
if (minAdultAge.before(userAge)) {
Global.alertInfo(SignUpActivity.this,
"Alert",
"Your age should be atleast minimum 16 years.");
} else {
BirthD.setText(yr + "-" + (mo + 1) + "-"
+ day);
}

}
}, mYear, mMonth, mDay);
if (!dt.isShowing())
dt.show();
}
});
}

POST JSON Data

Here, sample url to post
Global.url_forgotPass = "you php url"+ ?action=add&date=2014-06-30

String reverseString_rest;

@Override
protected Void doInBackground(Void... params) {

// TODO Auto-generated method stub
HttpClient httpclient = new DefaultHttpClient();
// harsh.vinnigtechnologies.com/api/add_point.php?action=add&date=2014-06-30&user_id=15&points=10
HttpPost httppost = new HttpPost(Global.url_forgotPass);
HttpParams httpParams = httpclient.getParams();
httpParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 100000);
final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("action", "forgot"));
nameValuePairs.add(new BasicNameValuePair("email", emailForgot
.getText().toString()));

try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse r = httpclient.execute(httppost);
int status = r.getStatusLine().getStatusCode();
if (status == 200) {

HttpEntity entity = r.getEntity();
String response = EntityUtils.toString(entity);
;
reverseString_rest = response;
reverseString_rest = reverseString_rest.replaceAll("&",
"amp;");
reverseString_rest = reverseString_rest.trim();
Log.i("reverseString_rest", reverseString_rest);

}

} catch (Exception e) {
Log.i("Exceptionn", "" + e);
exceptionOccurred = true;
e.printStackTrace();
}

return null;
}

@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialog.dismiss();
if (exceptionOccurred) {
Global.internetAlert(myCtx, "No Internet Connection",
"You don't have internet connection.", false);

} else if (reverseString_rest.contains("ENTER VALID EMAIL ADDRESS")) {
Global.alertInfo(myCtx, "Alert", "ENTER VALID EMAIL ADDRESS.");
} else if (reverseString_rest.contains("UNAUTHORIZED")) {
Global.alertInfo(myCtx, "Alert",
"Enter all required parameters.");
} else if (reverseString_rest.contains("success")) {
try {


Global.alertInfo(myCtx, "Login",
"You will soon recieve password in your email.");

Global.Reference = "";
// ((Activity) myCtx).finish();
} catch (Exception e) {
Log.i("Exception signup", "" + e.toString());
}

}

}

All About Database Handler - Part 2

Now , We see how to use it..

1. get all data from TABLE_POINTS

DatabaseHandler db = new DatabaseHandler(this);

Cursor cursor = db.getAllPoints();

cursor.moveToFirst();
do {

int points = Integer.toString(cursor.getInt(0));
String dates = String.valueOf(cursor.getString(1));
types = String.valueOf(cursor.getString(2));
Log.i("counttttttttttttt", "" + cursor.getCount() + " points"
+ cursor.getInt(0) + " type" + cursor.getString(2));
} while (cursor.moveToNext());

db.close();
cursor.close();

2. add data to TABLE_DATA

DatabaseHandler db = new DatabaseHandler(
LoginActivity.this);
db.addData(name.trim(), username.getText().toString()
.trim(), pass.getText().toString().trim(),
dob.trim());

db.close();


You can use the format and syntax as you need.

All About Database Handler - Part 1


public class DatabaseHandler extends SQLiteOpenHelper {

// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "database_name.db";

// user table name
private static final String TABLE_DATA = "User_Details";
private static final String TABLE_POINTS = "Points_Details";

public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {

String CREATE_DATA_TABLE = "CREATE TABLE IF NOT EXISTS "
+ TABLE_DATA
+ "(UserName TEXT, Email TEXT, Password TEXT, BirthDate TEXT)";
db.execSQL(CREATE_DATA_TABLE);

String CREATE_POINTS_TABLE = "CREATE TABLE IF NOT EXISTS "
+ TABLE_POINTS
+ "(point INTEGER, [date] DATETIME, type STRING)";
db.execSQL(CREATE_POINTS_TABLE);


}

// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_DATA);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_POINTS);
   onCreate(db);
}

void delete() {
SQLiteDatabase db = this.getReadableDatabase();
db.execSQL("DROP TABLE IF EXISTS " + TABLE_DATA);
onCreate(db);
db.close();
}

boolean checkIfExist() {
SQLiteDatabase db = this.getReadableDatabase();

Cursor c = db.rawQuery("SELECT Email FROM User_Details", null);

if (c.moveToFirst()) {
return true;
} else {
return false;
}
}

/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding user details
void addData(String UserName, String Email, String Password,
String BirthDate) {
SQLiteDatabase db = this.getWritableDatabase();

ContentValues values = new ContentValues();
values.put("UserName", UserName);
values.put("Email", Email);
values.put("Password", Password);
values.put("BirthDate", BirthDate);

// Inserting Row
db.insert(TABLE_DATA, null, values);
db.close(); // Closing database connection
}

public void deleteData() {
// db.delete(String tableName, String whereClause, String[] whereArgs);
// If whereClause is null, it will delete all rows.
SQLiteDatabase db = this.getWritableDatabase(); // helper is object
// extends
// SQLiteOpenHelper
db.delete(TABLE_DATA, null, null);
db.delete(TABLE_POINTS, null, null);
}

// Updating
public int updateUserDetails(String UserName, String Email,
String BirthDate) {
SQLiteDatabase db = this.getWritableDatabase();

ContentValues values = new ContentValues();
values.put("UserName", UserName);
values.put("Email", Email);
values.put("Password", Password);
values.put("BirthDate", BirthDate);

// updating row
return db.update(TABLE_DATA, values, "Email = ?",
new String[] { String.valueOf(Email) });
}

// public int updateUserPassword(String Password, String Email) {
// SQLiteDatabase db = this.getWritableDatabase();
//
// ContentValues values = new ContentValues();
// values.put("Password", Password);
//
// // updating row
// return db.update(TABLE_DATA, values, "Email = ?",
// new String[] { String.valueOf(Email) });
// }

// Updating
public void updatePoints(String date, int point, String type) {

SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.query(TABLE_POINTS, new String[] { "point", "date",
"type" }, "type = ?  AND date = ?",
new String[] { String.valueOf(type), String.valueOf(date) },
null, null, null);
Log.i("cursorrrrrrrrrrr", "" + cursor.getCount());
if (cursor.getCount() != 0) {
int actualPoint = 0;
if (cursor.moveToFirst()) {
do {
actualPoint = cursor.getInt(0);
} while (cursor.moveToNext());
}
cursor.close();

ContentValues values = new ContentValues();

values.put("point", actualPoint + point);

// Inserting Row
db.update(TABLE_POINTS, values, "type = ?  AND date = ?",
new String[] { String.valueOf(type), String.valueOf(date) });

} else {

ContentValues values = new ContentValues();

values.put("point", point);
values.put("date", date);
values.put("type", type);
// Inserting Row
db.insert(TABLE_POINTS, null, values);
}

db.close();

}

// Getting all data
public int getTodayPoints(String date) {
int points = 0;
SQLiteDatabase db = this.getReadableDatabase();

Cursor cursor = db.query(TABLE_POINTS,
new String[] { "point", "date" }, "date" + "=?",
new String[] { String.valueOf(date) }, null, null, null, null);
if (cursor != null) {

if (cursor.moveToFirst()) {
do {
points = cursor.getInt(0);
} while (cursor.moveToNext());
}

}

db.close();
return points;
}

// Getting all data
public Cursor getData() {

SQLiteDatabase db = this.getReadableDatabase();

Cursor cursor = db.query(TABLE_DATA, new String[] { "UserName",
"Email", "Password", "BirthDate" }, null, null, null,
null, null, null);
// cursor.close();
// db.close();
return cursor;
}

public Cursor getAllPoints() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_POINTS, new String[] { "point", "date",
"type" }, null, null, null, null, null, null);

return cursor;
}


@SuppressLint("SimpleDateFormat")
public int getMonthlyPoints(int total_Point) {

//this will show points of add and referal type only
total_Point = 0;
int st_addPoint = 0;
int mYear, mMonth, mDay;
String date1, date2;
final Calendar c = Calendar.getInstance();
c.add(Calendar.DAY_OF_YEAR, +1);
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);

final Calendar c1 = Calendar.getInstance();
c1.add(Calendar.DAY_OF_YEAR, -(mDay + 1));
Integer md1 = c1.get(Calendar.DAY_OF_MONTH);
Integer m1 = c1.get(Calendar.MONTH);
Integer y1 = c1.get(Calendar.YEAR);
date1 = y1 + "-" + (m1 + 1) + "-" + md1;
date2 = mYear + "-" + (mMonth + 1) + "-" + mDay;
SQLiteDatabase db = this.getReadableDatabase();


Cursor cursor_add = db.query(TABLE_POINTS, new String[] { "point", "date",
"type" }, "type like 'ADD'", null, null, null, null);
// Cursor cursor = db.query(TABLE_POINTS,
// new String[] { "point", "date" }, null, null, null, null, null);
if (cursor_add.moveToFirst()) {
do {
String str_date = cursor_add.getString(1);
SimpleDateFormat formatter;
Date date, datefr, datels;
formatter = new SimpleDateFormat("yyyy-MM-dd");
try {
date = formatter.parse(str_date);
datefr = formatter.parse(date1);
datels = formatter.parse(date2);
if (date.after(datefr) && date.before(datels)) {

st_addPoint = cursor_add.getInt(0) + st_addPoint;

}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} while (cursor_add.moveToNext());
}
if (cursor_add != null && !cursor_add.isClosed()) {
cursor_add.close();
}
}
}


to be continued..

Set Perfect Square imageview

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageView;

public class SquareImageView extends ImageView
{
    public SquareImageView(Context context)
    {
        super(context);
    }

    public SquareImageView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
    }

    public SquareImageView(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

       //Snap to width
        setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth());
    }

and use it in xml instead of ImageView

useful for gridview

Custom Alert Dialog Box

XML:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/r"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/back_shadow" >

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:paddingBottom="10dp"
            android:paddingLeft="5dp"
            android:paddingRight="5dp"
            android:paddingTop="10dp"
            android:text="@string/do_you_want_to_quit"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="@color/LtdRed" />

        <View
            android:layout_width="match_parent"
            android:layout_height="2dp"
            android:background="@color/DarkCherry" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:padding="5dp" >

            <RelativeLayout
                android:id="@+id/r2"
                android:layout_width="0dip"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:background="@drawable/back_shadow" >

                <TextView
                    android:id="@+id/yes"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:background="@drawable/click_slider"
                    android:gravity="center"
                    android:padding="10dp"
                    android:text="Yes"
                    android:textAppearance="?android:attr/textAppearanceLarge"
                    android:textColor="@color/Aamli" />
            </RelativeLayout>

            <View
                android:layout_width="5dp"
                android:layout_height="2dp" />

            <RelativeLayout
                android:id="@+id/r1"
                android:layout_width="0dip"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:background="@drawable/back_shadow" >

                <TextView
                    android:id="@+id/no"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:background="@drawable/click_slider"
                    android:gravity="center"
                    android:padding="10dp"
                    android:text="No"
                    android:textAppearance="?android:attr/textAppearanceLarge"
                    android:textColor="@color/LtdRed" />
            </RelativeLayout>
        </LinearLayout>
    </LinearLayout>

</RelativeLayout>



CODE:

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
new ContextThemeWrapper(MainActivity.this,
android.R.style.Theme_Holo));

               // Use of ContextThemeWrapper and Holo style makes dialog without border

final AlertDialog alertDialog = alertDialogBuilder.create();
View view = getLayoutInflater().inflate(R.layout.dialog_quit, null);

TextView yes, no;
yes = (TextView) view.findViewById(R.id.yes);
no = (TextView) view.findViewById(R.id.no);

yes.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
alertDialog.dismiss();

                               // to finish current activity
finish();

}
});
no.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
alertDialog.dismiss();
}
});

alertDialogBuilder.setView(view);

                // set dimension as per xml and popup into center
alertDialog.setView(view, 0, 0, 0, 0);

// show alert
alertDialog.show();
}


Set Custom Drawer Title Bar and Drawer Layout

XML:

main_activity.xml

 <?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawerLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#000" >

  // put your other elements

    <ListView
        android:id="@+id/drawerList"
        android:layout_width="@dimen/sidebarWidth"
        android:layout_height="match_parent"
        android:layout_gravity="left"
        android:background="@drawable/back_slider"
        android:divider="#C1C1C1"
        android:dividerHeight="1dp" >
    </ListView>

</android.support.v4.widget.DrawerLayout>



sample_titlebar.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rr"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#186CB7" >

    <TextView
        android:id="@+id/textSlider"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:ellipsize="end"
        android:gravity="center"
        android:textColor="#fff"
        android:textSize="27sp" />

</RelativeLayout>

CODE:

public class MainActivity extends Activity implements OnItemClickListener {



DrawerLayout drawerLayout;
ListView listView;
ActionBarDrawerToggle drawerListner;

// Baseadapter Class for slider options
CustomSliderList slideAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

getActionBar().setDisplayOptions(
ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_USE_LOGO
| ActionBar.DISPLAY_SHOW_HOME
| ActionBar.DISPLAY_HOME_AS_UP);

drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
listView = (ListView) findViewById(R.id.drawerList);
listView.setOnItemClickListener(this);

LayoutInflater inflater = (LayoutInflater) this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

// inflate the view that we created before
View v = inflater.inflate(R.layout.sample_titlebar, null);

TextView tv = (TextView) v.findViewById(R.id.textSlider);

                // set application name to title text
tv.setText(getResources().getString(R.string.app_name));


                // Here you set menu icon, and R.string (for disabled(you speak, it open close))
drawerListner = new ActionBarDrawerToggle(MainActivity.this,
drawerLayout, R.drawable.menu_icon, R.string.open_the_drawer,
R.string.close_the_drawer) {
@Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}

@Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
};

                // adapter according to your need
slideAdapter = new CustomSliderList(MainActivity.this,
CustomSliderList.name);

listView.setAdapter(slideAdapter);

drawerLayout.setDrawerListener(drawerListner);
getActionBar().setDisplayHomeAsUpEnabled(true);

                // set background of menu icon by color or
getActionBar().setBackgroundDrawable(
new ColorDrawable(Color.rgb(24, 108, 183)));

                // or set background of menu icon by image
                getActionBar().setBackgroundDrawable(
getResources().getDrawable(R.drawable.back_strip));

getActionBar().setCustomView(v);
}

@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerListner.syncState();
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerListner.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerListner.onConfigurationChanged(newConfig);
}

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
               // you can set your methods using position
listView.setItemChecked(position, true);
}

}