Friday, 6 March 2015

Custom listview

1)MainActivity.java
===============
package com.example.multiselectdemo;

import java.util.ArrayList;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity {
private ListView lstProfile;
private MainActivityAdapter mActivityAdapter;
private ArrayList<ProfileModel> alstProfile;
ProfileModel profileModel1,profileModel2,profileModel3,profileModel4;
private Button btnShow;
String str="";

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

alstProfile = new ArrayList<ProfileModel>();
btnShow = (Button)findViewById(R.id.btnShow);
btnShow.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
for (int i = 0; i < alstProfile.size(); i++) {
int size = alstProfile.size();
if(alstProfile.get(i).isSelected()){
Log.e("", "size="+size);
Log.e("","i==>>"+(i-1));
if(size == i+1){
str = str+alstProfile.get(i).getName().toString();
}else{
str = str+alstProfile.get(i).getName().toString()+"\n";
}
//Toast.makeText(MainActivity.this, ""+alstProfile.get(i).getName(),Toast.LENGTH_LONG).show();
}
}
//Toast.makeText(MainActivity.this, "",Toast.LENGTH_LONG).show();
Toast.makeText(MainActivity.this, ""+str.toString(),Toast.LENGTH_LONG).show();
str="";
}
});

profileModel1 = new ProfileModel();
profileModel1.setName("Manisha");
profileModel1.setCity("Ahmedabad");
profileModel1.setSelected(false);
alstProfile.add(profileModel1);

profileModel2 = new ProfileModel();
profileModel2.setName("Khyati");
profileModel2.setCity("Rajkot");
   profileModel2.setSelected(false);
alstProfile.add(profileModel2);

profileModel3 = new ProfileModel();
profileModel3.setName("Khyati");
profileModel3.setCity("Delhi");
profileModel3.setSelected(false);
alstProfile.add(profileModel3);

profileModel4 = new ProfileModel();
profileModel4.setName("Hrishik");
profileModel4.setCity("Mumbai");
profileModel4.setSelected(false);
alstProfile.add(profileModel4);

lstProfile = (ListView)findViewById(R.id.lstProfile);
mActivityAdapter = new MainActivityAdapter(this,alstProfile);
lstProfile.setAdapter(mActivityAdapter);
lstProfile.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
if(alstProfile.get(arg2).isSelected()){
alstProfile.get(arg2).setSelected(false);
}else{
alstProfile.get(arg2).setSelected(true);
}
Toast.makeText(MainActivity.this, ""+arg2, Toast.LENGTH_SHORT).show();
mActivityAdapter.notifyDataSetChanged();
}
});

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

2) MainActivityAdapter.java
=====================
package com.example.multiselectdemo;

import java.util.ArrayList;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivityAdapter extends BaseAdapter{
public Context mContext;
public ArrayList<ProfileModel>alstProfile;
private LayoutInflater mInflater;

public MainActivityAdapter(Context mContext,ArrayList<ProfileModel>alstProfile){
this.mContext = mContext;
this.alstProfile = alstProfile;
this.mInflater = LayoutInflater.from(mContext);
}
@Override
public int getCount() {
return alstProfile.size();
}

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

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

@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.mainactivity_adapter, null);
LinearLayout lyt = (LinearLayout)convertView.findViewById(R.id.lytList);
TextView txtName = (TextView)convertView.findViewById(R.id.txtName);
Log.e("",""+alstProfile.get(position).getName());
txtName.setText(alstProfile.get(position).getName());
TextView txtCity = (TextView)convertView.findViewById(R.id.txtCity);
txtCity.setText(alstProfile.get(position).getCity());
if(alstProfile.get(position).isSelected()){
lyt.setBackgroundResource(R.color.gray);
}else{
lyt.setBackgroundResource(R.color.Red);
}
return convertView;
}

}

3)ProfileModel.java
===============
package com.example.multiselectdemo;

public class ProfileModel {
private String name;
private String city;
private boolean selected;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}

}

4) activity_main.xml
===============
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

   <ListView 
       android:id="@+id/lstProfile"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:layout_alignParentTop="true"
       ></ListView>
   
   <Button 
       android:id="@+id/btnShow"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:layout_alignParentBottom="true"
       android:text="Show"/>
</RelativeLayout>

5) mainactivity_adapter.xml
=====================
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/lytList"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/txtName"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Name" />

    <TextView
        android:id="@+id/txtCity"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="City" />

</LinearLayout>

Monday, 2 February 2015

Get Characters from string

    // **THIS FUNCTION USED TO GET FIRST THREE CHARACTER FROM STRING
    public String getFirstThreeChar(String str) {
        String first3;
        first3 = str.substring(0, Math.min(str.length(), 3));
        return first3;
    }

    // **THIS FUNCTION USED TO GET LAST THREE CHARACTER FROM STRING
    public String getLastThreeChar(String str) {
        String last3;
        if (str == null || str.length() < 3) {
            last3 = str;
        } else {
            last3 = str.substring(str.length() - 3);
        }
        return last3;
    }

    public String removeLastThreeChar(String s) {
        if (s == null || s.length() == 0) {
            return s;
        }
        return s.substring(0, s.length() - 3);
    }

Saturday, 10 January 2015

Get Date Difference

public static String getDateDifference(Date thenDate){
        Calendar now = Calendar.getInstance();
        Calendar then = Calendar.getInstance();
        now.setTime(new Date());
        then.setTime(thenDate);

     
        // Get the represented date in milliseconds
        long nowMs = now.getTimeInMillis();
        long thenMs = then.getTimeInMillis();
     
        // Calculate difference in milliseconds
        long diff = nowMs - thenMs;
     
        // Calculate difference in seconds
        long diffMinutes = diff / (60 * 1000);
        long diffHours = diff / (60 * 60 * 1000);
        long diffDays = diff / (24 * 60 * 60 * 1000);

  if (diffMinutes<60){
   if (diffMinutes==1)
    return diffMinutes + " minute ago";
   else
    return diffMinutes + " minutes ago";
  } else if (diffHours<24){
   if (diffHours==1)
    return diffHours + " hour ago";
   else
    return diffHours + " hours ago";
  }else if (diffDays<30){
   if (diffDays==1)
    return diffDays + " day ago";
   else
    return diffDays + " days ago";
  }else {
   return "a long time ago..";
  }
 }


//// get day difference
=============
Time date1 = initializeDate1(); //get the date from somewhere
Time date2 = initializeDate2(); //get the date from somewhere

long millis1 = date1.toMillis(true);
long millis2 = date2.toMillis(true);

long difference = millis2 - millis1 ;

//now get the days from the difference and that's it
long days = TimeUnit.MILLISECONDS.toDays(difference);

//now you can do something like
if(days == 7)
{
    //do whatever when there's a week of difference
}

if(days >= 30)
{
    //do whatever when it's been a month or more
}

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 -->