Sunday 7 December 2014

Capture photo and save it into internal storage

1) create class

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.rws.alarm.AlarmReceiver;
import com.rws.apputil.Constants;
import com.rws.ezyparkingalaram.R;
import com.rws.ezyparkingalaram.SplashScreen;
import com.rws.ezyparkingalaram.TopBarActivity;
import com.rws.viewfolders.ViewFoldersActivity;

public class HomeActivity extends TopBarActivity {
private LinearLayout lytSettings, lytViewFolder, lytCaptureTicket;
private String strMonthTitle;
protected Toast toast;
private static final int CAMERA_PIC_REQUEST = 1001;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.homeactivity);
SplashScreen.setFirstTime(false, this);

lytSettings = (LinearLayout) findViewById(R.id.lytSettings);
lytSettings.setOnClickListener(this);

lytViewFolder = (LinearLayout) findViewById(R.id.lytViewFolders);
lytViewFolder.setOnClickListener(this);

lytCaptureTicket = (LinearLayout) findViewById(R.id.lytCaptureTicket);
lytCaptureTicket.setOnClickListener(this);

Calendar cal = Calendar.getInstance();
SimpleDateFormat month_year = new SimpleDateFormat("MMMM yyyy");
strMonthTitle = month_year.format(cal.getTime());

// new TimeDialog(this).show();
}

@Override
public void onClick(View v) {
super.onClick(v);
switch (v.getId()) {
case R.id.lytSettings:
Intent mIntentSettings = new Intent(getBaseContext(),
SettingsActivity.class);
startActivity(mIntentSettings);
finish();
break;

case R.id.lytViewFolders:
Intent mIntentViewFolder = new Intent(getBaseContext(),
ViewFoldersActivity.class);
startActivity(mIntentViewFolder);
break;

case R.id.lytCaptureTicket:
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_PIC_REQUEST);

final View toastView = getLayoutInflater().inflate(
R.layout.custom_toast,
(ViewGroup) findViewById(R.id.toastLayout));
ImageView imageView = (ImageView) toastView
.findViewById(R.id.image);
imageView.setImageResource(R.drawable.ic_info);

TextView textView = (TextView) toastView.findViewById(R.id.text);
textView.setText("Take a Clear photo of the Ticket");
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
toast = new Toast(HomeActivity.this);
toast.setGravity(Gravity.TOP, 0, 100);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(toastView);
toast.show();
}
}, 2000);
break;
default:
break;
}
}

String file_path;

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, requestCode, data);
if (toast != null)
toast.cancel();

if (requestCode == CAMERA_PIC_REQUEST && requestCode != 0
&& data != null) {
try {

Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
String foler_path = strMonthTitle;

if (isAutoSaveEnable())
file_path = "Ticket_SAVE" + System.currentTimeMillis()
+ ".jpg";
else
file_path = "Ticket_NONE" + System.currentTimeMillis()
+ ".jpg";

String imagePath = saveToInternalSorage(thumbnail, foler_path,
file_path);

Intent mIntent = new Intent(this, ExpiryTimeActivity.class);
mIntent.putExtra(AlarmReceiver.IMAGE_FILE_PATH, imagePath);
startActivity(mIntent);
} catch (Exception e) {
e.printStackTrace();
}
}
}

private boolean isAutoSaveEnable() {
SharedPreferences mSPreferences = getSharedPreferences(
Constants.SHAREDPREFERENCE.SHAREDPREFERENCES, 0);
return mSPreferences.getBoolean(
Constants.SHAREDPREFERENCE.CHK_AUTOSAVE, false);
}

public String saveToInternalSorage(Bitmap bitmapImage, String folderPath,
String filename) {
File directory = getDir("images", Context.MODE_PRIVATE);
directory = new File(directory, folderPath);
if (!directory.isDirectory())
directory.mkdirs();
File mypath = new File(directory, filename);
try {
FileOutputStream fos = new FileOutputStream(mypath);
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
return mypath.getAbsolutePath();
}

}

Thursday 25 September 2014

Drag and Drop into two gridview

1) Create a MainActivity.java


package com.game.wordgame;

import java.util.ArrayList;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipData.Item;
import android.content.ClipDescription;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.DragEvent;
import android.view.View;
import android.view.View.DragShadowBuilder;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import com.example.wordgame.R;

public class MainActivity extends Activity {
    private BottomGridAdapter mBottomGridAdapter;
    private LinearLayout bottomLayout, topLayout;
    private TopGridAdapter mTopGridAdapter;
    private GridView gridViewTop, gridViewBottom;
    private ArrayList<String> alstTop;
    private ArrayList<String> alstTopPoints;
    private ArrayList<String> alstBottom;
    private ArrayList<String> alstBottomPoints;
    int intTopPos, intBottomPos;
    private String strTopItem, strTopItemPoints;
    private String strBottomItem, strBottomItemPoints;
    public boolean boolGridTop = true;
    MyDragListener myDragListener = new MyDragListener();

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

        alstTop = new ArrayList<String>();
        alstTopPoints = new ArrayList<String>();
        for (int i = 0; i <= 169; i++) {
            if (i == 57) {
                alstTop.add("T");
                alstTopPoints.add("1");
            } else if (i == 58) {
                alstTop.add("H");
                alstTopPoints.add("2");
            } else if (i == 59) {
                alstTop.add("E");
                alstTopPoints.add("3");
            } else {
                alstTop.add("");
                alstTopPoints.add("");
            }
        }

        bottomLayout = (LinearLayout) findViewById(R.id.bottomlayout);
        topLayout = (LinearLayout) findViewById(R.id.toplayout);
        gridViewTop = (GridView) findViewById(R.id.top_gridview);
        mTopGridAdapter = new TopGridAdapter(this, alstTop, alstTopPoints);
        gridViewTop.setAdapter(mTopGridAdapter);
        gridViewTop.setOnItemLongClickListener(gridTopClickListener);

        gridViewBottom = (GridView) findViewById(R.id.bottom_gridview);
        gridViewBottom.setOnItemLongClickListener(gridBottomClickListener);

        alstBottom = new ArrayList<String>();
        alstBottomPoints = new ArrayList<String>();
        alstBottom.add("A");
        alstBottom.add("B");
        alstBottom.add("C");
        alstBottom.add("D");
        alstBottom.add("E");
        alstBottom.add("F");
        alstBottom.add("G");
        for (int i = 0; i < 7; i++) {
            alstBottomPoints.add("" + i);
        }

        mBottomGridAdapter = new BottomGridAdapter(this, alstBottom,alstBottomPoints);
        gridViewBottom.setAdapter(mBottomGridAdapter);
        gridViewTop.setOnDragListener(myDragListener);
        bottomLayout.setOnDragListener(myDragListener);
        gridViewBottom.setOnDragListener(myDragListener);
        topLayout.setOnDragListener(myDragListener);
    }

    OnItemLongClickListener gridTopClickListener = new OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> l, View v, int Position,long id){
            intTopPos = Position;
            boolGridTop = true;
            // Selected item is passed as item in dragData
            ClipData.Item item = new ClipData.Item(alstTop.get(Position)
                    + alstTopPoints.get(Position));
            String[] clipDescription = { ClipDescription.MIMETYPE_TEXT_PLAIN };
            ClipData dragData = new ClipData((CharSequence) v.getTag(),
                    clipDescription, item);

            DragShadowBuilder myShadow = new MyDragShadowBuilder(v, Position);
            v.startDrag(dragData, myShadow, alstTop.get(Position), 0);

            strTopItem = alstTop.get(Position);
            strTopItemPoints = alstTopPoints.get(Position);
            Log.i("strTopItem", "strTopItem==>>" + strTopItem);
            Log.i("strTopPoints", "strTopPoints==>>" + strTopItemPoints);

            alstTop.remove(intTopPos);
            alstTop.add(intTopPos, "");

            alstTopPoints.remove(intTopPos);
            alstTopPoints.add(intTopPos, "");
            mTopGridAdapter = new TopGridAdapter(MainActivity.this, alstTop,
                    alstTopPoints);
            gridViewTop.setAdapter(mTopGridAdapter);
            mTopGridAdapter.notifyDataSetChanged();
            Log.i("", "intTopPos ===>>>>" + intTopPos);
            return true;
        }
    };

    OnItemLongClickListener gridBottomClickListener = new OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> l, View v, int Position,long id) {
            // Selected item is passed as item in dragData
            boolGridTop = false;
            intBottomPos = Position;
            ClipData.Item item = new ClipData.Item(alstBottom.get(Position)
                    + alstBottomPoints.get(Position));
            String[] clipDescription = { ClipDescription.MIMETYPE_TEXT_PLAIN };
            ClipData dragData = new ClipData((CharSequence) v.getTag(),
                    clipDescription, item);

            DragShadowBuilder myShadow = new MyDragShadowBuilder(v, Position);
            v.startDrag(dragData, myShadow, alstBottom.get(Position), 0);

            strBottomItem = alstBottom.get(Position);
            strBottomItemPoints = alstBottomPoints.get(Position);
            Log.i("strBottomItem", "strBottomItem==>>" + strBottomItem);
            Log.i("strBottomPoints", "strBottomPoints==>>" + strBottomItemPoints);

            alstBottom.remove(intBottomPos);
            alstBottom.add(intBottomPos, "");
            alstBottomPoints.remove(intBottomPos);
            alstBottomPoints.add(intBottomPos, "");

            mBottomGridAdapter = new BottomGridAdapter(MainActivity.this,alstBottom, alstBottomPoints);
            gridViewBottom.setAdapter(mBottomGridAdapter);
            mBottomGridAdapter.notifyDataSetChanged();

            return true;
        }
    };

    @SuppressLint("NewApi")
    private class MyDragShadowBuilder extends View.DragShadowBuilder {
        private Drawable shadow;

        public MyDragShadowBuilder(View view, int pos) {
            super(view);
            Log.d("TAG", "Building shadow.");
            shadow = getResources().getDrawable(R.drawable.tile1);

            shadow.setCallback(view);
            Log.i("view.getWidth()", "view.getWidth()==>>" + view.getWidth()/ 2);
            Log.i("getHeight", "getHeight==>>" + view.getHeight() / 2);
            shadow.setBounds(20, 20, view.getWidth() / 2, view.getHeight() / 2);
        }

        @Override
        public void onDrawShadow(Canvas canvas) {
            Log.d("TAG", "Drawing shadow.");
            shadow.draw(canvas);
            getView().draw(canvas);
        }
    }

    protected class MyDragListener implements View.OnDragListener {
        @Override
        public boolean onDrag(View v, DragEvent event) {
            final int action = event.getAction();
            switch (action) {
            case DragEvent.ACTION_DRAG_STARTED:
                // All involved view accept ACTION_DRAG_STARTED for
                // MIMETYPE_TEXT_PLAIN
                // Toast.makeText(MainActivity.this, "ACTION_DRAG_STARTED",
                // Toast.LENGTH_SHORT).show();
                // if (event.getClipDescription().hasMimeType(
                // ClipDescription.MIMETYPE_TEXT_PLAIN)) {
                // return true;
                // } else {
                // return false; // reject
                // }

                return true;
            case DragEvent.ACTION_DRAG_ENTERED:

                return true;
            case DragEvent.ACTION_DRAG_LOCATION:

                return true;
            case DragEvent.ACTION_DRAG_EXITED:

                return true;
            case DragEvent.ACTION_DROP:
                // Toast.makeText(MainActivity.this, "ACTION_DROP",
                // Toast.LENGTH_SHORT).show();
                // Gets the item containing the dragged data
                // ClipData.Item item = event.getClipData().getItemAt(0);
                // If apply only if drop on buttonTarget
                if (v == bottomLayout) {
                    // String droppedItem = item.getText().toString();
                    if (boolGridTop) {
                        int newPosition = gridViewBottom.pointToPosition(
                                (int) (event.getX()), (int) event.getY());
                        Log.d("Position is==", Integer.toString(newPosition));
                        if (newPosition != ListView.INVALID_POSITION)
                            return processDropTopToBottom(event, newPosition);
                        else
                            return false;
                    } else {
                        int newPosition = gridViewBottom.pointToPosition(
                                (int) (event.getX()), (int) event.getY());
                        Log.d("Position is==", Integer.toString(newPosition));
                        if (newPosition != ListView.INVALID_POSITION)
                            return processDropBottomToBottom(event, newPosition);
                        else
                            return false;
                    }
                } else if (v == topLayout) {
                    if (boolGridTop) {
                        int newPosition = gridViewTop.pointToPosition(
                                (int) (event.getX()), (int) event.getY());
                        Log.d("Position is==", Integer.toString(newPosition));
                        if (newPosition != ListView.INVALID_POSITION)
                            return processDropTopToTop(event, newPosition);
                        else
                            return false;
                    } else{
                        int newPosition = gridViewTop.pointToPosition(
                                (int) (event.getX()), (int) event.getY());
                        Log.d("Position is==", Integer.toString(newPosition));
                        if (newPosition != ListView.INVALID_POSITION)
                            return processDropBottomToTop(event, newPosition);
                        else
                            return false;
                    }
                } else{
                    return false;
                }
            case DragEvent.ACTION_DRAG_ENDED:
                if (event.getResult()){
                } else {
                }
                ;
                return true;
            default:
                return false;
            }
        }
    }

    private boolean processDropTopToBottom(DragEvent event, int newPosition) {
        ClipData data = event.getClipData();
        if (data != null) {
            if (data.getItemCount() > 0) {
                Item item = data.getItemAt(0);
                String value = item.getText().toString();
                Log.i("New value", "New value==" + value);
                updateTopToBottomViewsAfterDropComplete(value, newPosition);
                return true;
            }
        }
        return false;
    }

    private boolean processDropTopToTop(DragEvent event, int newPosition) {
        ClipData data = event.getClipData();
        if (data != null) {
            if (data.getItemCount() > 0) {
                Item item = data.getItemAt(0);
                String value = item.getText().toString();
                updateTopToTopViewsAfterDropComplete(value, newPosition);
                return true;
            }
        }
        return false;
    }

    private boolean processDropBottomToTop(DragEvent event, int newPosition) {
        ClipData data = event.getClipData();
        if (data != null) {
            if (data.getItemCount() > 0) {
                Item item = data.getItemAt(0);
                String value = item.getText().toString();
                updateBottomToTopViewsAfterDropComplete(value, newPosition);
                return true;
            }
        }
        return false;
    }

    private boolean processDropBottomToBottom(DragEvent event, int newPosition) {
        ClipData data = event.getClipData();
        if (data != null) {
            if (data.getItemCount() > 0) {
                Item item = data.getItemAt(0);
                String value = item.getText().toString();
                updateBottomToBottomViewsAfterDropComplete(value, newPosition);
                return true;
            }
        }
        return false;
    }

    private void updateTopToBottomViewsAfterDropComplete(String listItem, int index) {
        String strBottom = "" + listItem.charAt(0);
        String strBottomPoins = listItem.substring(1);
       
        Log.i("", "alstBottom.get(index)===>>>"+alstBottom.get(index));
        if (alstBottom.get(index) == null || alstBottom.get(index).equalsIgnoreCase("")) {
            alstBottom.remove(index);
            alstBottom.add(index, strBottom);

            alstBottomPoints.remove(index);
            alstBottomPoints.add(index, strBottomPoins);

            mBottomGridAdapter = new BottomGridAdapter(MainActivity.this,alstBottom,alstBottomPoints);
            gridViewBottom.setAdapter(mBottomGridAdapter);
            mBottomGridAdapter.notifyDataSetChanged();
        }else{
            alstTop.remove(intTopPos);
            alstTop.add(intTopPos, strTopItem);

            alstTopPoints.remove(intTopPos);
            alstTopPoints.add(intTopPos, strBottomPoins);
            mTopGridAdapter = new TopGridAdapter(MainActivity.this, alstTop,
                    alstTopPoints);
            gridViewTop.setAdapter(mTopGridAdapter);
            mTopGridAdapter.notifyDataSetChanged();
        }
    }

    private void updateTopToTopViewsAfterDropComplete(String listItem, int index){
        String strTop = "" + listItem.charAt(0);
        String strTopPoints = listItem.substring(1);

        if (alstTop.get(index) == null || alstTop.get(index).equals("")){
            alstTop.remove(index);
            alstTop.add(index, strTop);
            alstTopPoints.remove(index);
            alstTopPoints.add(index, strTopPoints);

            mTopGridAdapter = new TopGridAdapter(MainActivity.this, alstTop,alstTopPoints);
            gridViewTop.setAdapter(mTopGridAdapter);
            mTopGridAdapter.notifyDataSetChanged();
        } else{
            alstTop.remove(intTopPos);
            alstTop.add(intTopPos, strTopItem);
            alstTopPoints.remove(intTopPos);
            alstTopPoints.add(intTopPos, strTopItemPoints);

            mTopGridAdapter = new TopGridAdapter(MainActivity.this, alstTop,alstTopPoints);
            gridViewTop.setAdapter(mTopGridAdapter);
            mTopGridAdapter.notifyDataSetChanged();
        }
    }

    private void updateBottomToTopViewsAfterDropComplete(String listItem,int index) {
        Log.d("InsertItem", "Position: " + index);
        String strTop = "" + listItem.charAt(0);
        String strTopPoints = listItem.substring(1);
       
        if (alstTop.get(index) == null || alstTop.get(index).equals("")) {
            alstTop.remove(index);
            alstTop.add(index, strTop);

            alstTopPoints.remove(index);
            alstTopPoints.add(index, strTopPoints);

            mTopGridAdapter = new TopGridAdapter(MainActivity.this, alstTop,alstTopPoints);
            gridViewTop.setAdapter(mTopGridAdapter);
            mTopGridAdapter.notifyDataSetChanged();
           
        } else {
            alstBottom.remove(intBottomPos);
            alstBottom.add(intBottomPos, strBottomItem);

            alstBottomPoints.remove(intBottomPos);
            alstBottomPoints.add(intBottomPos, strBottomItemPoints);
            mBottomGridAdapter = new BottomGridAdapter(MainActivity.this,alstBottom, alstBottomPoints);
            gridViewBottom.setAdapter(mBottomGridAdapter);
            mBottomGridAdapter.notifyDataSetChanged();
        }
    }

    private void updateBottomToBottomViewsAfterDropComplete(String listItem,int index){
        String strBottom = "" + listItem.charAt(0);
        String strBottomPoins = listItem.substring(1);
        if (alstBottom.get(index) == null || alstBottom.get(index).equals("")) {
            alstBottom.remove(index);
            alstBottom.add(index, strBottom);

            alstBottomPoints.remove(index);
            alstBottomPoints.add(index, strBottomPoins);

            Log.i("", "" + alstBottom.toString());
            mBottomGridAdapter = new BottomGridAdapter(MainActivity.this,alstBottom, alstBottomPoints);
            gridViewBottom.setAdapter(mBottomGridAdapter);
            mBottomGridAdapter.notifyDataSetChanged();
   
        } else{
            alstBottom.remove(intBottomPos);
            alstBottom.add(intBottomPos, strBottomItem);

            alstBottomPoints.remove(intBottomPos);
            alstBottomPoints.add(intBottomPos, strBottomItemPoints);
            mBottomGridAdapter = new BottomGridAdapter(MainActivity.this,alstBottom, alstBottomPoints);
            gridViewBottom.setAdapter(mBottomGridAdapter);
            mBottomGridAdapter.notifyDataSetChanged();
        }
    }
}

2) Create BottomGridAdapter.java

package com.game.wordgame;

import java.util.ArrayList;
import com.example.wordgame.R;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class BottomGridAdapter extends BaseAdapter{
    private LayoutInflater mLayoutInflater = null;
    private Context mContext = null;
    private ArrayList<String> alstBottom;
    private ArrayList<String> alstBottomPoints;
   
    public BottomGridAdapter(Context mContext,ArrayList<String>alstBottom,ArrayList<String> alstBottomPoints){
        this.mContext = mContext;
        this.alstBottom = alstBottom;
        this.alstBottomPoints = alstBottomPoints;
        this.mLayoutInflater = LayoutInflater.from(mContext);
    }

    @Override
    public int getCount(){
        Log.i("TAG", ""+alstBottom.size());
        return alstBottom.size();
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position){
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        convertView = mLayoutInflater.inflate(R.layout.bottom_grid_adapter, null);
        TextView txtBottom = (TextView)convertView.findViewById(R.id.txtBottom);
        TextView txtBottomPoints = (TextView)convertView.findViewById(R.id.txtBottomPoints);
       
        txtBottomPoints.setText(alstBottomPoints.get(position));
        //txtBottom.setBackgroundResource(R.drawable.tile1);
        txtBottom.setText(alstBottom.get(position));
       
        if (TextUtils.equals(txtBottom.getText(), "")) {
            txtBottom.setBackgroundResource(R.drawable.transperent_icon);
        } else {
            txtBottom.setBackgroundResource(R.drawable.tilebig);
        }
        return convertView;
    }
}

3) Create TopGridAdapter.java
package com.game.wordgame;

import java.util.ArrayList;
import com.example.wordgame.R;
import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class TopGridAdapter extends BaseAdapter {
    private LayoutInflater mLayoutInflater;
    private Context mContext;
    private ArrayList<String> alstTop;
    private ArrayList<String> alstTopPoints;

    public TopGridAdapter(Context mContext, ArrayList<String> alstTop,ArrayList<String> alstTopPoints) {
        this.mContext = mContext;
        this.mLayoutInflater = LayoutInflater.from(mContext);
        this.alstTop = alstTop;
        this.alstTopPoints = alstTopPoints;
    }

    @Override
    public int getCount() {
        return 169;
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        convertView = mLayoutInflater.inflate(R.layout.top_grid_adapter, null);

        TextView txtTop = (TextView) convertView.findViewById(R.id.txtTop);
        TextView txtTopPoints = (TextView)convertView.findViewById(R.id.txtTopPoints);
        txtTopPoints.setText(alstTopPoints.get(position));
        txtTop.setText("" + alstTop.get(position));
       
        if (TextUtils.equals(txtTop.getText(), "")) {
            txtTop.setBackgroundResource(R.drawable.transperent_icon);
        } else {
            txtTop.setBackgroundResource(R.drawable.tile1);
        }
        return convertView;
    }
}

4)create activity_main.xml


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

    <LinearLayout
        android:id="@+id/toplayout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dip"
        android:orientation="vertical" >
        <GridView
            android:id="@+id/top_gridview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/board"
            android:gravity="center"
            android:numColumns="13"
            android:stretchMode="columnWidth" >
        </GridView>
    </LinearLayout>
    <LinearLayout
        android:id="@+id/bottomlayout"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_below="@id/toplayout"
        android:orientation="vertical">
        <GridView
            android:id="@+id/bottom_gridview"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:gravity="top"
            android:layout_gravity="top"
            android:layout_marginTop="@dimen/grid_bottom_margin"
            android:numColumns="7"
            android:padding="@dimen/bottom_grid_margin" >
        </GridView>
    </LinearLayout>
</RelativeLayout>

5) Create bottom_grid_adapter.xml

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

    <TextView
        android:id="@+id/txtBottom"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_gravity="center"
        android:background="@drawable/tile_bg"
        android:contentDescription="@string/app_name"
        android:gravity="center"
        android:text="a"
        android:textSize="@dimen/b_cell_textsize"
        android:textStyle="bold"
        android:textColor="@android:color/black" />

    <TextView
        android:id="@+id/txtBottomPoints"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="top|right"
        android:padding="10dp"
        android:text="1"
        android:textSize="@dimen/b_cell_point_size"
        android:textColor="@android:color/black" />
</FrameLayout>

6) top_grid_adapter.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="30dp"
    android:layout_height="30dp"
    android:orientation="vertical" >
<!--     <TextView -->
<!--         android:id="@+id/imgCellTop" -->
<!--         android:layout_width="30dp" -->
<!--         android:layout_height="30dp" -->
<!--         android:contentDescription="@string/app_name" -->
<!--         android:layout_gravity="center" -->
<!--         android:gravity="center" -->
<!--         android:textColor="@android:color/black"/> -->
    <TextView
        android:id="@+id/txtTop"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_gravity="center"
        android:background="@drawable/tile1"
        android:contentDescription="@string/app_name"
        android:gravity="center"
        android:text="a"
        android:padding="2dp"
        android:textSize="@dimen/t_cell_textdize"
        android:textStyle="bold"
        android:textColor="@android:color/black" />
    <TextView
        android:id="@+id/txtTopPoints"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="top|right"
        android:padding="2dp"
        android:text="1"
        android:textSize="@dimen/t_cell_point_size"
        android:textColor="@android:color/black" />
</FrameLayout>

Tuesday 8 July 2014

Push notification Demo

1) GCMIntentService

import android.app.Notification;
import android.app.Notification.Builder;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;

import com.google.android.gcm.GCMBaseIntentService;

public class GCMIntentService extends GCMBaseIntentService {

public static final String GCM_SENDER_ID = "378946919077";

public GCMIntentService() {
super(GCM_SENDER_ID);
}

@SuppressWarnings("deprecation")
@Override
protected void onMessage(Context context, Intent intent) {
try {
final Bundle bundle = intent.getExtras();

String message = bundle.getString("message");

Log.i(TAG, "message: " + message);

// MainActivity mainActivity = MainActivity.getMainActivity();
// if (mainActivity != null) {
// mainActivity.onPushMessage(message);
// clearPushMessage();
// } else
//Intent notificationIntent = new Intent(this, MyClass.class);
//PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);


Intent mIntent = new Intent(context, PopUpNotification.class);
mIntent.putExtra("pushmessage", message);
mIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

final PendingIntent contentIntent = PendingIntent.getActivity(
context, (int) System.currentTimeMillis(), mIntent, 0);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
setPushMessage(message);
final Notification notification = new Notification();
final Object systemService = context
.getSystemService(Context.NOTIFICATION_SERVICE);
final NotificationManager notificationMgr = (NotificationManager) systemService;

notification.flags |= Notification.FLAG_AUTO_CANCEL;
// notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults = Notification.DEFAULT_LIGHTS
| Notification.DEFAULT_VIBRATE;

notification.vibrate = new long[] { 0, 100, 200, 300 };
notification.contentIntent = contentIntent;
notification.icon = R.drawable.icon;

notification.tickerText = context.getString(R.string.app_name);
String appName = context.getResources().getString(
R.string.app_name);
notification.setLatestEventInfo(this, appName, message,
contentIntent);
//notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
int ss = (int) System.currentTimeMillis();

notificationMgr.notify(ss, notification);
} else {

NotificationManager m_notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Builder m_builder = new Notification.Builder(this);
m_builder
.setContentTitle(context.getString(R.string.app_name))
.setContentText(message)
.setSmallIcon(R.drawable.icon)
.setContentIntent(contentIntent)
.setAutoCancel(true)
.setVibrate(new long[] { 0, 100, 200, 300 })
.setDefaults(
Notification.DEFAULT_LIGHTS
| Notification.DEFAULT_VIBRATE);
String appName = context.getResources().getString(
R.string.app_name);
Notification m_notification = new Notification.BigTextStyle(
m_builder).bigText(message).build();
m_notification.setLatestEventInfo(this, appName, message, contentIntent);
int ss = (int) System.currentTimeMillis();
m_notificationManager.notify(ss, m_notification);
}
} catch (Exception e) {
e.printStackTrace();
}
}

private void setPushMessage(String message) {
final SharedPreferences mSharedPreferences = getSharedPreferences(
"PushNotification", 0);
final SharedPreferences.Editor mEditor = mSharedPreferences.edit();
mEditor.putString("message", message);
mEditor.commit();
}

public void clearPushMessage() {
final SharedPreferences mSharedPreferences = getSharedPreferences(
"PushNotification", 0);
final SharedPreferences.Editor mEditor = mSharedPreferences.edit();
mEditor.putString("message", null);
mEditor.commit();
}

private static final String TAG = "GCMIntentService";

@Override
protected void onRegistered(Context arg0, String registrationId) {
Log.i(TAG, "Device registered: regId = " + registrationId);
MainActivity instance = MainActivity.getInstance();
if (instance != null)
instance.onDeiceToken(registrationId);
}

@Override
protected void onUnregistered(Context arg0, String arg1) {
Log.i(TAG, "unregistered = " + arg1);
}

@Override
protected void onError(Context arg0, String errorId) {
Log.i(TAG, "Received error: " + errorId);
}

@Override
protected boolean onRecoverableError(Context context, String errorId) {
return super.onRecoverableError(context, errorId);
}

}

2) MainActivity.java
==============
public class MainActivity extends DroidGap {

public static MainActivity mainActivity;
private String regId;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

mainActivity = this;

super.loadUrl("file:///android_asset/www/html/index.html", 3000);
super.setIntegerProperty("loadUrlTimeoutValue", 80000);
super.setIntegerProperty("splashscreen", R.drawable.splash_screen);
appView.loadUrl("javascript:android.selection.longTouch();");

GCMRegistrar.checkDevice(this);
GCMRegistrar.checkManifest(this);
regId = GCMRegistrar.getRegistrationId(this);

if (TextUtils.isEmpty(regId)) {
GCMRegistrar.register(this, GCMIntentService.GCM_SENDER_ID);
} else {
appView.setWebChromeClient(new MyChromeClient(this, regId));
}

Intent mIntent = getIntent();
if (mIntent != null) {
Bundle mBundle = mIntent.getExtras();
if (mBundle != null) {
if (mBundle.containsKey("bundle")) {
mBundle = mBundle.getBundle("bundle");
String cal_envet_id = mBundle
.getString(AlarmReceiver.NOTIFICATION_ID);
String title = mBundle.getString(AlarmReceiver.TITLE);

String nServerEventID = mBundle
.getString(AlarmReceiver.SERVEREVENTID);
onEventArise(cal_envet_id, title, nServerEventID);
}
}
}
}

public class MyChromeClient extends CordovaChromeClient {

private String registerToken = "";

public MyChromeClient(CordovaInterface cordova, String regId) {
super(cordova);
registerToken = regId;
}

@Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
if (newProgress == 100) {
onDeiceToken(registerToken);
Bundle data = getIntent().getExtras();
if (data.containsKey("pushmessage")) {
onPushMessage(data.getString("pushmessage"));
}
}
}
}

public static MainActivity getInstance() {
return mainActivity;
}

@Override
protected void onResume() {
mainActivity = this;
super.onResume();
}

@Override
public void onDestroy() {
mainActivity = null;
super.onDestroy();
}

public void onDeiceToken(final String deviceToken) {
runOnUiThread(new Runnable() {
@Override
public void run() {
appView.loadUrl("javascript:onDeviceToken('" + deviceToken
+ "')");
}
});
}

public void onEventArise(String id, String message, String nServerEventID) {
appView.loadUrl("javascript:onCalanderEvent('" + id + "','" + message
+ "'" + nServerEventID + "')");

}

public void onPushMessage(final String mMessage) {
appView.loadUrl("javascript:onPushMessage('" + mMessage + "')");
}

}
3) in mani fest add
<!-- GCM code Begin -->
    <permission
        android:name="com.rightway.amour.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />

    <uses-permission android:name="com.rightway.amour.permission.C2D_MESSAGE" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <!-- GCM code End -->



    <!-- GCM Code Begin -->
        <receiver
            android:name="com.google.android.gcm.GCMBroadcastReceiver"
            android:permission="com.google.android.c2dm.permission.SEND" >
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
                <category android:name="com.rightway.amour" />
            </intent-filter>
        </receiver>

        <service android:name=".GCMIntentService" />
        <!-- GCM code End -->

Sunday 15 June 2014

Date and Alert dialog (Register) example

package com.rws.ohmsantihyoga;

import java.util.Calendar;
import java.util.Date;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.Window;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.actionbarsherlock.app.ActionBar;
import com.rws.localwsutils.AppUtil;
import com.rws.wsutil.PostAndGetData.onJsonResult;
import com.rwsutil.masterview.GroupPrefrences.RegisterPref;
import com.rwsutil.masterview.MyBaseActivityWS;
import com.rwsutil.masterview.WebServiceUrl;

public class RegisterActivity extends MyBaseActivityWS implements onJsonResult,
RegisterPref, WebServiceUrl, OnClickListener {

private EditText edtUserName, edtFirstName, edtLastName, edtDateOfBirth,
edtGender, edtStreetAddress, edtAppartment, edtTownCity,
edtPostCode;
private EditText edtEmailAddress, edtPhoneNumber, edtAccountPassword,
edtConfirmPassword, edtNote, edtContry;
private int register_responcCode = 900;
private ImageView iconMenu, iconHome;
private Button btnSubmit;
private int Year = 0, Month = 0, Day = 0,iCount = 1;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register_activity);
setTitle("Register");
setBehindContentView(R.layout.menu_frame);
getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getActionBar().setCustomView(R.layout.headder_back);
getActionBar().setBackgroundDrawable(
new ColorDrawable(R.color.brn_lite));
getSlidingMenu().setSlidingEnabled(false);
// mAppUtil = AppUtil.getInstance();

// mSPreferences = getSharedPreferences(
// Constants.SHAREDPREFERENCE.SHAREDPREFERENCES, 0);

// strUserID = mSPreferences.getString(Constants.USER_ID, "");
// strUserRole = mSPreferences.getString(Constants.USER_ROLE, "");

iconMenu = (ImageView) findViewById(R.id.iconMenu);
iconMenu.setVisibility(ImageView.VISIBLE);
iconMenu.setOnClickListener(this);
iconHome = (ImageView) findViewById(R.id.iconHome);
iconHome.setOnClickListener(this);

edtUserName = (EditText) findViewById(R.id.edtUserName);
observeText(edtUserName);
edtFirstName = (EditText) findViewById(R.id.edtFirstName);
observeText(edtFirstName);
edtLastName = (EditText) findViewById(R.id.edtLastName);

observeText(edtLastName);
edtStreetAddress = (EditText) findViewById(R.id.edtStreetAddress);
edtDateOfBirth = (EditText) findViewById(R.id.edtDateOfBirth);
edtDateOfBirth.requestFocus();
edtDateOfBirth.setOnClickListener(this);
edtGender = (EditText) findViewById(R.id.edtGender);
edtGender.requestFocus();
edtGender.setOnClickListener(this);
edtStreetAddress = (EditText) findViewById(R.id.edtStreetAddress);
observeText(edtStreetAddress);
edtAppartment = (EditText) findViewById(R.id.edtAppartment);
edtTownCity = (EditText) findViewById(R.id.edtTownCity);
observeText(edtTownCity);
edtPostCode = (EditText) findViewById(R.id.edtPostalCode);
observeText(edtPostCode);
edtContry = (EditText) findViewById(R.id.edtContry);
observeText(edtContry);
edtEmailAddress = (EditText) findViewById(R.id.edtEmailAddress);
observeText(edtEmailAddress);
edtPhoneNumber = (EditText) findViewById(R.id.edtPhoneNumber);
observeText(edtPhoneNumber);
edtAccountPassword = (EditText) findViewById(R.id.edtAccountPassword);
observeText(edtAccountPassword);
edtConfirmPassword = (EditText) findViewById(R.id.edtConfirmPassword);
observeText(edtConfirmPassword);
edtNote = (EditText) findViewById(R.id.edtNote);
onFocusChange(edtNote);
// imgLeftDevider = (ImageView)findViewById(R.id.imgLeftDivider);
// imgLeftDevider.setVisibility(ImageView.INVISIBLE);
// iconMenu = (ImageView)findViewById(R.id.iconMenu);
// iconMenu.setVisibility(ImageView.INVISIBLE);
btnSubmit = (Button) findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(this);
edtDateOfBirth = (EditText) findViewById(R.id.edtDateOfBirth);
edtDateOfBirth.requestFocus();
edtDateOfBirth.setOnClickListener(this);
edtDateOfBirth
.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
DateDialog();
}
}
});
edtGender = (EditText) findViewById(R.id.edtGender);
edtGender.requestFocus();
edtGender.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
onCreateDialog();
}
}
});

// edtGender.setOnClickListener(this);

final Calendar c = Calendar.getInstance();
Year = c.get(Calendar.YEAR);
Month = c.get(Calendar.MONTH);
Day = c.get(Calendar.DAY_OF_MONTH);
// updateDisplay();

}

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnSubmit:
JSONObject validResponce = getValidResponce();
if (validResponce != null) {
callWsPost(REGISTER_URL, validResponce, register_responcCode)
.setCacheEnable(false);
}
break;
// case R.id.edtDateOfBirth:
// DateDialog();
// break;
// case R.id.edtGender:
// onCreateDialog();
// break;
case R.id.iconMenu:
finish();
break;
case R.id.edtDateOfBirth:
DateDialog();
break;
case R.id.edtGender:
onCreateDialog();
break;

case R.id.iconHome:
Intent mIntent = new Intent(this, HomeActivity.class);
mIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(mIntent);
finish();
break;
}
}

@Override
public void onResult(int mResponceCode, JSONArray mResponce) {
try {
JSONObject mJsonRegisterResponse = mResponce.getJSONObject(0);
String mRegisterStatus = mJsonRegisterResponse.getString("bStatus");
String response = mJsonRegisterResponse.getString("sMessage");
if (TextUtils.equals(mRegisterStatus, "1")) {
AlertDialogRegFailed(RegisterActivity.this, getResources()
.getString(R.string.app_name), response);
// clearPrefrenc();
// Intent mIntent = new Intent(this, LoginActivity.class);
// startActivity(mIntent);
} else {
AlertDialogRegSuccessfully(RegisterActivity.this, getResources()
.getString(R.string.app_name), response);
}
} catch (Exception e) {
e.printStackTrace();
}
}

private void clearPrefrenc() {
edtUserName.setText("");
edtFirstName.setText("");
edtLastName.setText("");
edtDateOfBirth.setText("");
edtGender.setText("");
edtStreetAddress.setText("");
edtAppartment.setText("");
edtTownCity.setText("");
edtPostCode.setText("");
edtContry.setText("");
edtEmailAddress.setText("");
edtPhoneNumber.setText("");
edtAccountPassword.setText("");
edtConfirmPassword.setText("");
edtNote.setText("");

putPref(REG_USER_NAME, "");
putPref(REG_FIRSTNAME, "");
putPref(REG_LASTNAME, "");
putPref(REG_DATE_OF_BIRTH, "");
putPref(REG_GENDER, "");
putPref(REG_STREET_ADDRESS, "");
putPref(REG_APPARTMENT, "");
putPref(REG_TOWNCITY, "");
putPref(REG_POSTAL_CODE, "");
putPref(REG_COUNTRY, "");
putPref(REG_EMAIL_ADDRESS, "");
putPref(REG_PHONE_NUMBER, "");
putPref(REG_ACCOUNT_PASSWORD, "");
putPref(REG_CONFIRM_PASSWORD, "");
putPref(REG_NOTE, "");

}

// validations
public JSONObject getValidResponce() {
String strUserName = edtUserName.getText().toString().trim();
String strFirstName = edtFirstName.getText().toString().trim();
String strLastName = edtLastName.getText().toString().trim();
String strBirthDate = edtDateOfBirth.getText().toString().trim();
String strStreetAddress = edtStreetAddress.getText().toString().trim();
String strStreetAddress2 = edtAppartment.getText().toString().trim();
String strTownCity = edtTownCity.getText().toString().trim();
String strPostCode = edtPostCode.getText().toString().trim();
String strCountry = edtContry.getText().toString().trim();
String strEmailAddress = edtEmailAddress.getText().toString().trim();
String strPhoneNumber = edtPhoneNumber.getText().toString().trim();
String strAccountPassword = edtAccountPassword.getText().toString()
.trim();
String strConfirmPassword = edtConfirmPassword.getText().toString()
.trim();
String strGender = edtGender.getText().toString().trim();
String strNote = edtNote.getText().toString().trim();

if (TextUtils.isEmpty(strUserName)) {
edtUserName.requestFocus();
edtUserName.setError("Please Enter User Name");
return null;
} else if (TextUtils.isEmpty(strFirstName)) {
edtFirstName.requestFocus();
edtFirstName.setError("Please Enter First Name");
return null;
} else if (TextUtils.isEmpty(strLastName)) {
edtLastName.requestFocus();
edtLastName.setError("Please Enter Last Name");
return null;
} else if (TextUtils.isEmpty(strStreetAddress)) {
edtStreetAddress.requestFocus();
edtStreetAddress.setError("Please Enter Address");
return null;
} else if (TextUtils.isEmpty(strTownCity)) {
edtTownCity.requestFocus();
edtTownCity.setError("Please Enter City");
return null;
} else if (TextUtils.isEmpty(strPostCode)) {
edtPostCode.requestFocus();
edtPostCode.setError("Please Enter PostCode");
return null;
} else if (TextUtils.isEmpty(strCountry)) {
edtContry.requestFocus();
edtContry.setError("Please Enter Country");
return null;
} else if (!AppUtil.isValidEmail(strEmailAddress)) {
edtEmailAddress.requestFocus();
edtEmailAddress.setError("Please Enter Valid Email Address");
return null;
} else if (TextUtils.isEmpty(strPhoneNumber)) {
edtPhoneNumber.requestFocus();
edtPhoneNumber.setError("Please Enter Phone Number");
return null;
} else if (TextUtils.isEmpty(strAccountPassword)) {
edtAccountPassword.requestFocus();
edtAccountPassword.setError("Please Enter Account Password");
return null;
} else if (edtAccountPassword.getText().toString().length() < 5) {
edtAccountPassword.requestFocus();
edtAccountPassword.setError("Password is too short");
return null;
} else if (TextUtils.isEmpty(strConfirmPassword)) {
edtConfirmPassword.requestFocus();
edtConfirmPassword.setError("Please Enter Confirm Password");
return null;
} else if (edtConfirmPassword.getText().toString().length() < 5) {
edtConfirmPassword.requestFocus();
edtConfirmPassword.setError("Password is too short");
return null;
} else if (!TextUtils.equals(strConfirmPassword, strAccountPassword)) {
edtConfirmPassword.requestFocus();
edtConfirmPassword.setError("Password does not match");
return null;
} else {
JSONObject mJsonObject = new JSONObject();
try {
mJsonObject.put("user_login", strUserName);
mJsonObject.put("user_pass", strAccountPassword);
mJsonObject.put("user_email", strEmailAddress);
mJsonObject.put("first_name", strFirstName);
mJsonObject.put("last_name", strLastName);
mJsonObject.put("billing_address_1", strStreetAddress);
mJsonObject.put("billing_city", strTownCity);
mJsonObject.put("billing_postcode", strPostCode);
mJsonObject.put("billing_country", strCountry);
mJsonObject.put("billing_phone", strPhoneNumber);
mJsonObject.put("birthdate", strBirthDate);
mJsonObject.put("gender", strGender);
mJsonObject.put("order_notes", strNote);
mJsonObject.put("billing_address_2", strStreetAddress2);
return mJsonObject;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
}

// @Override
// public void onDateSet(DatePicker view, int year, int monthOfYear,int
// dayOfMonth) {
// String date = String.valueOf(dayOfMonth) + "-"
// + String.valueOf(monthOfYear + 1) + "-" + String.valueOf(year);
// edtDateOfBirth.setText(date);
// // Toast.makeText(RegisterActivity.this, date, Toast.LENGTH_LONG)
// // .show();
// }

public void onCreateDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final String[] strgender = new String[] { "Male", "Female" };
builder.setTitle("Select Gender").setItems(strgender,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
edtGender.setText(strgender[which]);
}
});
builder.create().show();
}

// Dialog for show error msg
public void AlertDialogRegFailed(Context mContext, String mStrDailogTitle,
String mStrDailogMsg) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
mContext);
// alertDialogBuilder.setTitle(Constant.LOGIN.LOGIN_FAIL_MESSAGE);
alertDialogBuilder.setMessage(mStrDailogMsg).setTitle(mStrDailogTitle)
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
   clearPrefrenc();
dialog.cancel();
}
});

AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
// Dialog for show error msg
public void AlertDialogRegSuccessfully(Context mContext, String mStrDailogTitle,
String mStrDailogMsg) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
mContext);
// alertDialogBuilder.setTitle(Constant.LOGIN.LOGIN_FAIL_MESSAGE);
alertDialogBuilder.setMessage(mStrDailogMsg).setTitle(mStrDailogTitle)
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Intent mIntent = new Intent(RegisterActivity.this, LoginActivity.class);
// //mIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// startActivity(mIntent);
dialog.cancel();
finish();
}
});

AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}


private DatePicker mdatePicker = null;
private Dialog mDialog = null;
private View mView = null;

private void DateDialog() {
mDialog = new Dialog(this);
mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
mdatePicker = new DatePicker(this);
mdatePicker.setCalendarViewShown(false);
mView = LayoutInflater.from(this).inflate(R.layout.xdatelayout, null);
LinearLayout datedialogview = (LinearLayout) mView
.findViewById(R.id.datedialogview);
datedialogview.addView(mdatePicker);

Button btnok = (Button) mView.findViewById(R.id.btnok);
btnok.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Toast.makeText(getApplicationContext(), "OK",
// Toast.LENGTH_SHORT).show();
DateValidation();
}
});

Button btncancel = (Button) mView.findViewById(R.id.btncancel);
btncancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Toast.makeText(getApplicationContext(), "CANCEL",
// Toast.LENGTH_SHORT).show();
mDialog.dismiss();
}
});

mDialog.setContentView(mView);
InitDateSet();
mDialog.show();
}

private void InitDateSet() {
final Calendar c = Calendar.getInstance();
Year = c.get(Calendar.YEAR);
Month = c.get(Calendar.MONTH);
Day = c.get(Calendar.DAY_OF_MONTH);
mdatePicker.init(Year, Month, Day, mDatePickListener);
}

// updates the date in the TextView
@SuppressWarnings("deprecation")
private void updateDisplay() {
Date mDate = new Date();
mDate.setYear(Year - 1900);
mDate.setMonth(Month);
mDate.setDate(Day);

String selectedDate = (String) DateFormat.format("yyyy-MM-dd", mDate)
.toString();
edtDateOfBirth.setText(selectedDate);
}

private DatePicker.OnDateChangedListener mDatePickListener = new DatePicker.OnDateChangedListener() {
@Override
public void onDateChanged(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
Year = year;
Month = monthOfYear;
Day = dayOfMonth;
}
};

/**
* 0 if the times of the two Calendars are equal, -1 if the time of this
* Calendar is before the other one, 1 if the time of this Calendar is after
* the other one.
*/
private int FirstDateCheck(int year, int month, int day) {
final Calendar CurrentDate = Calendar.getInstance();
Calendar NewDate = (Calendar) CurrentDate.clone();
NewDate.set(year, month, day);
return NewDate.compareTo(CurrentDate);
}

private void DateValidation() {
int Result = FirstDateCheck(Year, Month, Day);
if (Result == 0) {
// Toast.makeText(ServiceSetupRequest.this, "equal",
// Toast.LENGTH_SHORT).show();
updateDisplay();
mDialog.dismiss();
} else if (Result == -1) {
mDialog.dismiss();
updateDisplay();
} else if (Result == 1) {
Toast.makeText(RegisterActivity.this, "Please enter valid date",
Toast.LENGTH_SHORT).show();
// updateDisplay();
// mDialog.dismiss();
}
}

public void onFocusChange(final EditText edittext) {
edittext.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
edittext.setError(null);
}
}
});
}
}