Tuesday 28 March 2017

Database using Assets

1)DBHelper.java
=============
package com.game.database;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import com.wordgame.constant.DBConstants;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBHelper extends SQLiteOpenHelper {
// The Android's default system path of your application database.
// private static String DbConstants.DB_NAME = "myDBName";
public SQLiteDatabase myDataBase;
private final Context myContext;

/**
* Constructor Takes and keeps a reference of the passed context in order to
* access to the application assets and resources.
*
* @param context
*/
public DBHelper(Context context) {
super(context, DBConstants.DB_NAME, null, DBConstants.DB_VERSION);
this.myContext = context;
}

/**
* Creates a empty database on the system and rewrites it with your own
* database.
* */
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
// do nothing - database already exist
} else {
// By calling this method and empty database will be created into
// the default system path
// of your application so we are gonna be able to overwrite that
// database with our database.
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}

/**
* Check if the database already exist to avoid re-copying the file each
* time you open the application.
*
* @return true if it exists, false if it doesn't
*/
public boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DBConstants.DB_PATH + DBConstants.DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
// database does't exist yet.
}

if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}

/**
* Copies your database from your local assets-folder to the just created
* empty database in the system folder, from where it can be accessed and
* handled. This is done by transfering bytestream.
* */
private void copyDataBase() throws IOException {
// Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DBConstants.DB_NAME);
// Path to the just created empty db
String outFileName = DBConstants.DB_PATH + DBConstants.DB_NAME;
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}

// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}

public void openDataBase() throws SQLException {
// Open the database
String myPath = DBConstants.DB_PATH + DBConstants.DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
}

@Override
public synchronized void close() {
if (myDataBase != null)
myDataBase.close();
super.close();
}

@Override
public void onCreate(SQLiteDatabase db) {

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

public boolean Selectword(SQLiteDatabase db, String word) {
String Query = String
.format("SELECT * FROM %s WHERE %s = '%s'",
DBConstants.TABLE.final_dict,
DBConstants.final_dict.word, word);
Cursor cursor = db.rawQuery(Query, null);
// int i = cursor.getCount();
if (cursor.moveToFirst()) {
cursor.close();
return true;
} else {
return false;
}
}

// For insert points into database
public void InsertPoints(SQLiteDatabase db, String user_id, int level,
int coins, int loyalty_points, int exp_level, Boolean flag) {
ContentValues cv = new ContentValues();
cv.put(DBConstants.points.user_id, user_id);
cv.put(DBConstants.points.level, level);
cv.put(DBConstants.points.coins, coins);
cv.put(DBConstants.points.loyalty_points, loyalty_points);
cv.put(DBConstants.points.exp_level, exp_level);
cv.put(DBConstants.points.flag, flag);
db.insert(DBConstants.TABLE.points, null, cv);
}

// For update points into database
public void UpdatePoints(SQLiteDatabase db,int coins){
ContentValues cv = new ContentValues();
cv.put(DBConstants.points.coins, coins);
db.update(DBConstants.TABLE.points, cv, null, null);
}

public void DeletePoints(SQLiteDatabase db) {
db.delete(DBConstants.TABLE.points, null, null);
}

}
2)DBConstants.java
================
package com.wordgame.constant;


public class DBConstants {
public static String DB_PATH = "/data/data/com.game.wordgame/databases/";
public static final String DB_NAME = "WWH.sqlite";
public static final int DB_VERSION = 1;

// table
public class TABLE {
public static final String final_dict = "Final_dict";
public static final String letter_point = "letter_point";
public static final String points = "points";
}
public class final_dict{
public static final String id = "id";
public static final String word = "word";
public static final String w_length = "w_length";
}
public class points{
public static final String user_id = "user_id";
public static final String level = "level";
public static final String coins = "coins";
public static final String loyalty_points = "loyalty_points";
public static final String exp_level = "exp_level";
public static final String flag = "flag";
}

// /** THIS FUNCTION IS USED FOR OPEN DATABASE */
// public static DBHelper mDBHelper = null;
// public static SQLiteDatabase mSQLiteDatabase = null;
//
// public static void OpenDatabase(Context context)
// {
//       try{
//        if(mDBHelper==null && mSQLiteDatabase==null){
//         mDBHelper = new DBHelper(context);
//         mSQLiteDatabase = mDBHelper.getWritableDatabase();
////    mSQLiteDatabase.setLockingEnabled(true);
//        }
//       }
//       catch (Exception e) {
//       e.printStackTrace();
//       }
// }
//
// /** THIS FUNCTION IS USED FOR CLOSE DATABASE */
// public static void CloseDataBase() {
// try {
// if (mDBHelper != null && mSQLiteDatabase != null) {
// mSQLiteDatabase.close();
// mDBHelper.close();
// mSQLiteDatabase = null;
// mDBHelper = null;
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
//
// }

}
3)Constants .java
===============
package com.wordgame.constant;


public class DBConstants {
public static String DB_PATH = "/data/data/com.game.wordgame/databases/";
public static final String DB_NAME = "WWH.sqlite";
public static final int DB_VERSION = 1;

// table
public class TABLE {
public static final String final_dict = "Final_dict";
public static final String letter_point = "letter_point";
public static final String points = "points";
}
public class final_dict{
public static final String id = "id";
public static final String word = "word";
public static final String w_length = "w_length";
}
public class points{
public static final String user_id = "user_id";
public static final String level = "level";
public static final String coins = "coins";
public static final String loyalty_points = "loyalty_points";
public static final String exp_level = "exp_level";
public static final String flag = "flag";
}
// /** THIS FUNCTION IS USED FOR OPEN DATABASE */
// public static DBHelper mDBHelper = null;
// public static SQLiteDatabase mSQLiteDatabase = null;
//
// public static void OpenDatabase(Context context)
// {
//       try{
//        if(mDBHelper==null && mSQLiteDatabase==null){
//         mDBHelper = new DBHelper(context);
//         mSQLiteDatabase = mDBHelper.getWritableDatabase();
////    mSQLiteDatabase.setLockingEnabled(true);
//        }
//       }
//       catch (Exception e) {
//       e.printStackTrace();
//       }
// }
//
// /** THIS FUNCTION IS USED FOR CLOSE DATABASE */
// public static void CloseDataBase() {
// try {
// if (mDBHelper != null && mSQLiteDatabase != null) {
// mSQLiteDatabase.close();
// mDBHelper.close();
// mSQLiteDatabase = null;
// mDBHelper = null;
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
//
// }
}
4)MainActivity.java
===============================================
package com.game.wordgame;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipData.Item;
import android.content.ClipDescription;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.SQLException;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.DragEvent;
import android.view.View;
import android.view.View.DragShadowBuilder;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.game.database.DBHelper;
import com.game.socket.MenuScreen;
import com.game.socket.SocketIOClient;
import com.game.wordgame.model.WordsModel;
import com.game.wordgame.model.WordsPosition;
import com.wordgame.constant.Constants;

@SuppressLint("NewApi")
public class MainActivity extends Activity implements OnClickListener {
private WordsAdapter mWordsAdapter;
private int direction;
int intGrandTotal, temp = 0;
MediaPlayer mp = new MediaPlayer();
private LinearLayout bottomLayout, topLayout;
private Button btnRecall, btnswap;
private GridView gridViewTop, gridViewBottom;
private ArrayList<WordsModel> alstBottom;
private ArrayList<WordsModel> alstTop;
private ArrayList<Integer> alstBottomposition;
private ArrayList<String> alstLetterUsed;
int intTopPos, intBottomPos, indexTopBottom;
private String strTopItem, strBottomItem;
private int intTopCellWidth, intBottomCellWidth;
public boolean boolGridTop = true;
public static Handler Mainhandler, swapresponsehandler, gametimerhandler,
gameoverhandler, leftgamehandler, denyrematchhandler,
submitresponsehandler;

MyDragListener myDragListener = new MyDragListener();
String opponentusername, myusername, mysocket_id, opponentsocket_id,
current_playing_id, current_scoreChanel, allWords, opponenttype,
letter, roww, col, badge, serverid, opponentid, dynamicuserid,
dynamicname, decoyletter, swapresponse, gametimerresponse,
gameover;
String strFWPostion;
String letterbag;
ArrayList<String> alstFinalWordKey;

SocketIOClient socket;
public static Map<String, ArrayList<WordsModel>> mFinalWords = new TreeMap<String, ArrayList<WordsModel>>();
public static Map<String, ArrayList<WordsModel>> mLastWords = new TreeMap<String, ArrayList<WordsModel>>();
public static Map<Integer, WordsModel> mOneTurnWords = new TreeMap<Integer, WordsModel>();
public static Map<Integer, WordsModel> mOpponentOneTurnWords = new TreeMap<Integer, WordsModel>();
public static Map<Integer, WordsModel> mMatchedHorizontalWords = new TreeMap<Integer, WordsModel>();
public static Map<Integer, WordsModel> mMatchedVerticalWords = new TreeMap<Integer, WordsModel>();
public static Map<Integer, WordsModel> mWordsHashMap = new TreeMap<Integer, WordsModel>();
public static Map<String, ArrayList<WordsModel>> mCorrextWords = new TreeMap<String, ArrayList<WordsModel>>();
Intent intent;
int total_row = 13, total_col = 13, column, row;
String strTop, strTopPoints;
SharedPreferences prefs;
int i;
WordsModel wordsModel1, wordsModel2, wordsModel3, wordsModel4, wordsModel5,
wordsModel6, wordsModel7, oppWordModel;
ArrayList<String> decoyid = new ArrayList<String>(Arrays.asList("0", "1","2", "3", "4", "5", "6"));
Editor editor;
String str = "";
ArrayList<WordsModel> finalValue;
private DBHelper mDBHelper;
private int intCoins = 50, intLevel = 1, intExpLevel = 0;
private CountDownTimer countDownTimer;
public TextView text;
private final long startTime = 4 * 1000;
private final long interval = 1 * 1000;
private Dialog dialog;

Handler handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
intCoins = intCoins + 16;
mDBHelper.openDataBase();
mDBHelper.UpdatePoints(mDBHelper.myDataBase, intCoins);
mDBHelper.close();
}
};

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

submitresponsehandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {

String submitresponse = (String) msg.obj;
Log.d("TAG5", "SUBMITRESPONSE" + submitresponse);
Log.i("TAG5","alstBottomposition==" + alstBottomposition.toString());
JSONObject jobj1;
try {
jobj1 = new JSONObject(submitresponse);
current_playing_id = jobj1.getString("playid");
} catch (JSONException e1) {
e1.printStackTrace();
}

if (alstBottomposition.size() != 0) {
try {
JSONObject jobj = new JSONObject(submitresponse);
String reqdecoyletters = jobj.getString("reqdecoyletters");
current_playing_id = jobj.getString("playid");

Log.e("TAG5", "redecoyletter" + reqdecoyletters
+ "currentplayingid" + current_playing_id);
JSONArray jarry = new JSONArray(reqdecoyletters);
for (int i = 0; i < jarry.length(); i++) {
String reqletter = jarry.getString(i);
int bottomposition = alstBottomposition.get(i);
Log.d("TAG5", "bottomposition" + bottomposition);
Log.d("TAG5", "reqletter" + reqletter);
if (alstBottom.get(bottomposition) == null) {
WordsModel wordsModel8 = new WordsModel();
wordsModel8.setBottomPos(bottomposition);
wordsModel8.setWords(reqletter);
wordsModel8.setPoints(setCellPoint(reqletter));
wordsModel8.setFlag(false);
alstBottom.set(bottomposition, wordsModel8);
}
}
mWordsAdapter = new WordsAdapter(MainActivity.this,alstBottom, intBottomCellWidth, temp);
gridViewBottom.setAdapter(mWordsAdapter);
mWordsAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
alstBottomposition.clear();
return false;
}
});

dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.setCancelable(false);
dialog.setContentView(R.layout.customelayout);
dialog.getWindow().setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
text = (TextView) dialog.findViewById(R.id.text);
countDownTimer = new MyCountDownTimer(startTime, interval);
text.setText(text.getText() + String.valueOf(startTime / 1000));

countDownTimer.start();
dialog.show();

final TextView tvvv = (TextView) findViewById(R.id.timer);
mDBHelper = new DBHelper(this);

try {
mDBHelper.createDataBase();
Log.i("", "Database is created");
} catch (IOException ioe) {
throw new Error("Unable to create database");
}

handler.postDelayed(runnable, 1000 * 60 * 60 * 30);
gametimerhandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
gametimerresponse = msg.obj.toString();
JSONObject jsontimer;
try {
jsontimer = new JSONObject(gametimerresponse);
String fromid = jsontimer.getString("from");
String myid = jsontimer.getString("socket_id");
Log.e("TAG3", "fromid::" + fromid);
Log.e("TAG3", "myid::" + myid);
Log.e("TAG3", "dynamic::" + dynamicuserid);

if ((myid.equalsIgnoreCase(dynamicuserid))
|| (fromid.equalsIgnoreCase(dynamicuserid))) {
String gametimer = jsontimer.getString("time");
String time = "00:15";
if (gametimer.equalsIgnoreCase("00:15")
|| gametimer.equalsIgnoreCase("00:14")
|| gametimer.equalsIgnoreCase("00:13")
|| gametimer.equalsIgnoreCase("00:12")
|| gametimer.equalsIgnoreCase("00:11")
|| gametimer.equalsIgnoreCase("00:10")
|| gametimer.equalsIgnoreCase("00:09")
|| gametimer.equalsIgnoreCase("00:08")
|| gametimer.equalsIgnoreCase("00:07")
|| gametimer.equalsIgnoreCase("00:06")
|| gametimer.equalsIgnoreCase("00:05")
|| gametimer.equalsIgnoreCase("00:04")
|| gametimer.equalsIgnoreCase("00:03")
|| gametimer.equalsIgnoreCase("00:02")
|| gametimer.equalsIgnoreCase("00:01")
|| gametimer.equalsIgnoreCase("00:00")) {
tvvv.setBackgroundColor(Color.RED);
} else {
tvvv.setBackgroundColor(Color.GREEN);
}
tvvv.setText(gametimer);
}
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
});
gameoverhandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
gameover = msg.obj.toString();
Log.i("TAG3", "gameover : : " + gameover);
AlertDialog.Builder alertdialog = new AlertDialog.Builder(MainActivity.this);
alertdialog.setTitle("Game Over");
alertdialog.setMessage("Gameover");
alertdialog.setCancelable(false);
alertdialog.setPositiveButton("ok",
new DialogInterface.OnClickListener() {
@SuppressWarnings("static-access")
@Override
public void onClick(DialogInterface dialog,int which) {
JSONObject jsondeny = new JSONObject();
try {
jsondeny.put("opponent_id",
opponentsocket_id);
jsondeny.put("id", dynamicuserid);
if (mysocket_id
.equalsIgnoreCase(dynamicuserid)) {
socket.emit("denyRematch", jsondeny);
Intent intent = new Intent(
MainActivity.this,
MenuScreen.class);
startActivity(intent);
finish();
}
} catch (JSONException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
}

}
});
alertdialog.setNegativeButton("Rematch",
new DialogInterface.OnClickListener() {

@SuppressWarnings("static-access")
@Override
public void onClick(DialogInterface dialog,
int which) {
JSONArray letterjsonarr = null;
try {
letterjsonarr = new JSONArray(letterbag);
} catch (JSONException e1) {

e1.printStackTrace();
}
JSONObject rematchjson = new JSONObject();
try {
rematchjson.put("id", dynamicuserid);
rematchjson.put("opponent_id",
opponentsocket_id);
rematchjson
.put("letter_Bag", letterjsonarr);
socket.emit("requestRematch", rematchjson);
Log.e("TAG4", "REMATCH" + rematchjson);
} catch (JSONException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
}

}
});
alertdialog.show();
return false;
}
});
denyrematchhandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
String denyrematch = msg.obj.toString();
Log.i("TAG4", "DENYREMATCH::" + denyrematch);
if (mysocket_id.equalsIgnoreCase(dynamicuserid)) {
Intent intent = new Intent(MainActivity.this,
MenuScreen.class);
startActivity(intent);
finish();
}
return false;
}
});

leftgamehandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
String userleftgame = msg.obj.toString();
Log.i("TAG4", "userleftgame: : " + userleftgame);
final JSONObject jsontimer;
try {
jsontimer = new JSONObject(gametimerresponse);
String myid = jsontimer.getString("socket_id");
if (userleftgame.equalsIgnoreCase(myid)) {
AlertDialog.Builder alertdialog = new AlertDialog.Builder(
MainActivity.this);
alertdialog.setTitle("User left");
alertdialog.setMessage("User left Game");
alertdialog.setCancelable(false);
alertdialog.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
@SuppressWarnings("static-access")
@Override
public void onClick(DialogInterface dialog,
int which) {
Intent intent = new Intent(
MainActivity.this,
MenuScreen.class);
startActivity(intent);
try {
socket.emit("findAllUsers",
jsontimer);
} catch (MalformedURLException e) {
e.printStackTrace();
}
finish();
}
});
alertdialog.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
});

swapresponsehandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
swapresponse = msg.obj.toString();
Log.i("TAG3", "swapresponse : : " + swapresponse);
alstBottom.clear();
Log.i("TAG3", "Arraybottom" + alstBottom);
JSONObject jobj;
try {
jobj = new JSONObject(swapresponse);
String Requestdecoy = jobj.getString("reqdecoyletters");
JSONArray jarr = new JSONArray(Requestdecoy);
for (int i = 0; i < jarr.length(); i++) {
String decoy = (String) jarr.get(i);
Log.i("TAG3", "Decoyarray" + decoy);

wordsModel1 = new WordsModel();
wordsModel1.setWords(decoy);

wordsModel1.setPoints(setCellPoint(decoy));
alstBottom.add(wordsModel1);

mWordsAdapter = new WordsAdapter(MainActivity.this,
alstBottom, intBottomCellWidth, temp);
gridViewBottom.setAdapter(mWordsAdapter);
mWordsAdapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
});
Log.i("TAG3", "swapresponsebeforehandler" + swapresponse);

socket = new SocketIOClient();
intent = getIntent();
String username = PreferenceManager.getDefaultSharedPreferences(this)
.getString("un", "");
String finduserjson1 = intent.getStringExtra("orgfinduserresponse");
Log.e("TAG3", "FINDJSONFROMMAIN" + finduserjson1);
JSONObject jsonResponse;
try {
jsonResponse = new JSONObject(finduserjson1);
JSONArray jsonarray = jsonResponse
.optJSONArray("findAllUsersResponse");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonChildNode = jsonarray.getJSONObject(i);
dynamicname = jsonChildNode.optString("name");
if (username.equalsIgnoreCase(dynamicname)) {
dynamicuserid = jsonChildNode.optString("id");
Log.e("TAG3", "uid:: " + dynamicuserid + "SAME NAME::: "
+ dynamicname);
}
}
} catch (JSONException e2) {
e2.printStackTrace();
}

String playingresponse = intent.getStringExtra("playingresponse");
String gamerequest = intent.getStringExtra("gamerequest");
Log.v("TAG1", "PlayingresponsefromMain" + playingresponse);
Log.v("TAG1", "GamerequestfromMain" + gamerequest);
prefs = getApplicationContext().getSharedPreferences("prefs",
MODE_WORLD_WRITEABLE);
editor = prefs.edit();
serverid = prefs.getString("myuserid", "");
opponentid = prefs.getString("opponentid", "");

if (gamerequest != null) {
JSONObject jsonobj;
try {
jsonobj = new JSONObject(gamerequest);
opponentusername = jsonobj.getString("fromname");
} catch (JSONException e) {
e.printStackTrace();
}
} else {
opponentusername = prefs.getString("opponentname", null);
}

try {
JSONObject jobj1 = new JSONObject(playingresponse);
letterbag = jobj1.getString("letterbag");
String opponentsocket_iddd = jobj1.getString("from");
String mysocket_idd = jobj1.getString("socket_id");
current_playing_id = jobj1.getString("playid");
current_scoreChanel = jobj1.getString("schanel");
Log.e("TAG3", "mysocket_id" + mysocket_id);
mysocket_id = dynamicuserid;
if (mysocket_idd.equalsIgnoreCase(dynamicuserid)) {
opponentsocket_id = jobj1.getString("from");
Log.e("TAG3", "opponentid in first if ::" + opponentsocket_id
+ "Dynamicuserid::" + dynamicuserid);
decoyletter = jobj1.getString("letter7array");
}

else if (opponentsocket_iddd.equalsIgnoreCase(dynamicuserid)) {
opponentsocket_id = jobj1.getString("socket_id");
Log.e("TAG3", "opponentid in else-if:::" + opponentsocket_id
+ "Dynamicuserid::" + dynamicuserid);
decoyletter = jobj1.getString("letter7array1");

JSONObject timerobj = new JSONObject();
try {
timerobj.put("mysocket_id", mysocket_id);
timerobj.put("opponentsocket_id", opponentsocket_id);
timerobj.put("opponenttype", "real");
timerobj.put("schanel", current_scoreChanel);
Log.i("TAG3", "timerobj" + timerobj);
socket.emit("gameTimer", timerobj);
} catch (JSONException e3) {
e3.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}

myusername = username;
/*
* myusername = prefs.getString("myusername", null);
* opponentusername = prefs.getString("opponentname", null);
*/
Log.e("TAG3", "Myusername::" + username + "opponentusername::"
+ opponentusername + "my_socket_id" + mysocket_id
+ "  opponentsocketid  " + opponentsocket_id);

opponenttype = jobj1.getString("opponenttype");
Log.e("TAG1", "  opponentsocketid  " + opponentsocket_id
+ "mysocket_id  " + mysocket_id + " current_playing_id  "
+ current_playing_id + "  current_scoreChanel  "
+ current_scoreChanel + "  opponenttype  " + opponenttype
+ "  json  " + allWords);
} catch (JSONException e1) {
e1.printStackTrace();
}

intExpLevel = intLevel - 1;
try {
mDBHelper.openDataBase();
mDBHelper.DeletePoints(mDBHelper.myDataBase);
mDBHelper.InsertPoints(mDBHelper.myDataBase, myusername, intLevel,
intCoins, 1, intExpLevel, true);
mDBHelper.close();
} catch (SQLException sqle) {
throw sqle;
}

if (opponenttype.equalsIgnoreCase("real")) {
intCoins = intCoins - 10;
mDBHelper.openDataBase();
mDBHelper.UpdatePoints(mDBHelper.myDataBase, intCoins);
mDBHelper.close();
} else {
intCoins = intCoins - 1;
mDBHelper.openDataBase();
mDBHelper.UpdatePoints(mDBHelper.myDataBase, intCoins);
mDBHelper.close();
}

ArrayList<String> word = new ArrayList<String>();
alstTop = new ArrayList<WordsModel>();

String first = intent.getStringExtra("firstword");
String second = intent.getStringExtra("secondword");
String third = intent.getStringExtra("thirdword");
String fourth = intent.getStringExtra("fourthword");
String fifth = intent.getStringExtra("fifthword");

alstBottom = new ArrayList<WordsModel>();
btnRecall = (Button) findViewById(R.id.btnRecall);
btnRecall.setOnClickListener(this);
alstFinalWordKey = new ArrayList<String>();
alstBottomposition = new ArrayList<Integer>();
alstLetterUsed = new ArrayList<String>();
// alstletterunused = new ArrayList<String>();
DisplayMetrics metrics = getResources().getDisplayMetrics();
int width = metrics.widthPixels;
int height = metrics.heightPixels;
intTopCellWidth = width / 13;
intBottomCellWidth = width / 7;
Log.i("width==>>", "width==" + width);
Log.i("height==>>", "height==" + height);

for (i = 0; i < 169; i++) {
if (i == 57) {
WordsModel wordsModel57 = new WordsModel();
wordsModel57.setWords(first);
wordsModel57.setPoints(setCellPoint(first));
wordsModel57.setIndex(i);
wordsModel57.setPlace("CENTER");
wordsModel57.setFlag(true);

int column = i % total_col;
int row = i / total_col;
wordsModel57.setColumnno(column);
wordsModel57.setRowno(row);
Log.i("OPPENENT", "column==" + column);
Log.i("OPPENENT", "row==" + row);
alstTop.add(wordsModel57);
mWordsHashMap.put(i, wordsModel57);

} else if (i == 58) {
WordsModel wordsModel58 = new WordsModel();
wordsModel58.setWords(second);
wordsModel58.setPoints(setCellPoint(second));
wordsModel58.setIndex(i);
wordsModel58.setPlace("CENTER");
wordsModel58.setFlag(true);

int column = i % total_col;
int row = i / total_col;
wordsModel58.setColumnno(column);
wordsModel58.setRowno(row);
Log.i("OPPENENT", "column==" + column);
Log.i("OPPENENT", "row==" + row);
alstTop.add(wordsModel58);
mWordsHashMap.put(i, wordsModel58);

} else if (i == 59) {
WordsModel wordsModel59 = new WordsModel();
wordsModel59.setWords(third);
wordsModel59.setPoints(setCellPoint(third));
wordsModel59.setIndex(i);
wordsModel59.setPlace("CENTER");
wordsModel59.setFlag(true);
Log.i("OPPENENT", "column==" + column);
Log.i("OPPENENT", "row==" + row);
int column = i % total_col;
int row = i / total_col;
wordsModel59.setColumnno(column);
wordsModel59.setRowno(row);
alstTop.add(wordsModel59);
mWordsHashMap.put(i, wordsModel59);

} else if (i == 60) {
WordsModel wordsModel60 = new WordsModel();
wordsModel60.setWords(fourth);
wordsModel60.setPoints(setCellPoint(fourth));
wordsModel60.setIndex(i);
wordsModel60.setFlag(true);
wordsModel60.setPlace("CENTER");
int column = i % total_col;
int row = i / total_col;
wordsModel60.setColumnno(column);
wordsModel60.setRowno(row);
Log.i("OPPENENT", "column==" + column);
Log.i("OPPENENT", "row==" + row);
alstTop.add(wordsModel60);
mWordsHashMap.put(i, wordsModel60);

} else if (i == 61) {
WordsModel wordsModel61 = new WordsModel();
wordsModel61.setWords(fifth);
wordsModel61.setPoints(setCellPoint(fifth));
wordsModel61.setIndex(i);
wordsModel61.setFlag(true);
wordsModel61.setPlace("CENTER");
int column = i % total_col;
int row = i / total_col;
wordsModel61.setColumnno(column);
wordsModel61.setRowno(row);
Log.i("OPPENENT", "column==" + column);
Log.i("OPPENENT", "row==" + row);
alstTop.add(wordsModel61);
mWordsHashMap.put(i, wordsModel61);
} else {
alstTop.add(null);
// alstRecallTop.add(null);
// WordsModel wordsModel = new WordsModel();
// wordsModel.setWords("");
// wordsModel.setPoints(0);
// top.add(wordsModel);
}
}
// mWordsHashMap.put(i, wordsModel);

bottomLayout = (LinearLayout) findViewById(R.id.bottomlayout);
topLayout = (LinearLayout) findViewById(R.id.toplayout);
gridViewTop = (GridView) findViewById(R.id.top_gridview);

ViewGroup.LayoutParams layoutParams = gridViewTop.getLayoutParams();
layoutParams.height = width;
layoutParams.width = width;
gridViewTop.setLayoutParams(layoutParams);

mWordsAdapter = new WordsAdapter(this, alstTop, intTopCellWidth, temp);
gridViewTop.setAdapter(mWordsAdapter);
gridViewTop.setOnItemLongClickListener(gridTopClickListener);

String bottomfirst = intent.getStringExtra("bottomfirst");
String bottomsecond = intent.getStringExtra("bottomsecond");
String bottomthird = intent.getStringExtra("bottomthird");
String bottomfouth = intent.getStringExtra("bottomfourth");
String bottomfifth = intent.getStringExtra("bottomfifth");
String bottomsixth = intent.getStringExtra("bottomsixth");
String bottomseventh = intent.getStringExtra("bottomseventh");

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

wordsModel1 = new WordsModel();
wordsModel1.setBottomPos(0);
wordsModel1.setWords(bottomfirst);
wordsModel1.setPoints(setCellPoint(bottomfirst));
wordsModel1.setFlag(false);

wordsModel2 = new WordsModel();
wordsModel2.setBottomPos(1);
wordsModel2.setWords(bottomsecond);
wordsModel2.setPoints(setCellPoint(bottomsecond));
wordsModel2.setFlag(false);

wordsModel3 = new WordsModel();
wordsModel3.setBottomPos(2);
wordsModel3.setWords(bottomthird);
wordsModel3.setPoints(setCellPoint(bottomthird));
wordsModel3.setFlag(false);

wordsModel4 = new WordsModel();
wordsModel4.setBottomPos(3);
wordsModel4.setWords(bottomfouth);
wordsModel4.setPoints(setCellPoint(bottomfouth));
wordsModel4.setFlag(false);

wordsModel5 = new WordsModel();
wordsModel5.setBottomPos(4);
wordsModel5.setWords(bottomfifth);
wordsModel5.setPoints(setCellPoint(bottomfifth));
wordsModel5.setFlag(false);

wordsModel6 = new WordsModel();
wordsModel6.setBottomPos(5);
wordsModel6.setWords(bottomsixth);
wordsModel6.setPoints(setCellPoint(bottomsixth));
wordsModel6.setFlag(false);

wordsModel7 = new WordsModel();
wordsModel7.setBottomPos(6);
wordsModel7.setWords(bottomseventh);
wordsModel7.setPoints(setCellPoint(bottomseventh));
wordsModel7.setFlag(false);

alstBottom.add(wordsModel1);
mWordsHashMap.put(1, wordsModel1);
alstBottom.add(wordsModel2);
mWordsHashMap.put(2, wordsModel2);
alstBottom.add(wordsModel3);
mWordsHashMap.put(3, wordsModel3);
alstBottom.add(wordsModel4);
mWordsHashMap.put(4, wordsModel4);
alstBottom.add(wordsModel5);
mWordsHashMap.put(5, wordsModel5);
alstBottom.add(wordsModel6);
mWordsHashMap.put(6, wordsModel6);
alstBottom.add(wordsModel6);
mWordsHashMap.put(7, wordsModel7);

setCellBg();
btnswap = (Button) findViewById(R.id.btnSwap);
btnswap.setOnClickListener(new OnClickListener() {
@SuppressWarnings("static-access")
@Override
public void onClick(View v) {
JSONObject jobjswap = new JSONObject();
JSONArray jsonarr = new JSONArray(decoyid);
try {
JSONArray zf = new JSONArray(decoyletter);
jobjswap.put("mysocket_id", mysocket_id);
jobjswap.put("opponentsocket_id", opponentsocket_id);
jobjswap.put("scoreChanel", current_scoreChanel);
jobjswap.put("decoyid", jsonarr);
jobjswap.put("decoyletter", zf);
socket.emit("swaprack", jobjswap);
Log.e("TAG3", "SWAPRACK:::" + jobjswap);
} catch (JSONException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
});

mWordsAdapter = new WordsAdapter(this, alstBottom, intBottomCellWidth,temp);
gridViewBottom.setAdapter(mWordsAdapter);

gridViewTop.setOnDragListener(myDragListener);
bottomLayout.setOnDragListener(myDragListener);
gridViewBottom.setOnDragListener(myDragListener);
topLayout.setOnDragListener(myDragListener);

final JSONArray arraytile = new JSONArray();
Mainhandler = new Handler(new Handler.Callback() {

@Override
public boolean handleMessage(Message arg0) {
temp = 1;
String opponenttile = arg0.obj.toString();

Log.e("TAG2", "Opponenttile" + opponenttile);
String strr = "WrongWord";

try {
JSONObject jobj = new JSONObject(opponenttile);
String allwordsss = jobj.getString("allWords");
Log.e("TAG2", "allwords" + allwordsss);

// String cut =
// allwordsss.substring(allwordsss.indexOf("}"));
// Log.d("TAG2", "TAG2" + cut);

JSONArray jarry1 = new JSONArray(allwordsss);
JSONObject jobjjjj;

Log.e("TAG2", "jarry1 -" + jarry1.length());
Log.e("TAG2", "mOpponentOneTurnWords -"
+ mOpponentOneTurnWords.size());
if (jarry1.length() != mOpponentOneTurnWords.size()) {
for (int i = 0; i < jarry1.length(); i++) {
String all = jarry1.getString(i).toString();
Log.e("TAG2", "All" + all);
jobjjjj = new JSONObject(all);

String oLetter = jobjjjj.getString("letter");
String oBadge = jobjjjj.getString("badge");
Log.e("TAG2", "OPPONENTARRAYLIST:::" + arraytile);
int row = jobjjjj.getInt("row");
int column = jobjjjj.getInt("col");
int pos = column + (row * total_row);
if (!mWordsHashMap.containsKey(pos)) {
oppWordModel = new WordsModel();
oppWordModel.setWords(oLetter);
int points = Integer.parseInt(oBadge);
oppWordModel.setPoints(points);
oppWordModel.setColumnno(column);
oppWordModel.setRowno(row);

Log.v("NEW", "pos***************" + pos);
Log.i("NEW", "column************" + column);
Log.i("NEW", "row***************" + row);
Log.v("NEW", "pos indexTopBottom**********"
+ indexTopBottom);

alstTop.set(pos, oppWordModel);
mWordsHashMap.put(pos, oppWordModel);
mOpponentOneTurnWords.put(pos, oppWordModel);
// Log.e("SIZE ", "SIZE ::" +
// mWordsHashMap.size());
}
}
} else {
for (Map.Entry<Integer, WordsModel> entry : mOpponentOneTurnWords
.entrySet()) {
int key = entry.getKey();
if (mWordsHashMap.containsKey(key)) {
mWordsHashMap.remove(key);
}
alstTop.remove(key);
}

mOpponentOneTurnWords.clear();
for (int i = 0; i < jarry1.length(); i++) {
String all = jarry1.getString(i).toString();
Log.e("TAG2", "All" + all);
jobjjjj = new JSONObject(all);

String oLetter = jobjjjj.getString("letter");
String oBadge = jobjjjj.getString("badge");
Log.e("TAG2", "OPPONENTARRAYLIST:::" + arraytile);
int row = jobjjjj.getInt("row");
int column = jobjjjj.getInt("col");
int pos = column + (row * total_row);

WordsModel oppWordModel = new WordsModel();
oppWordModel.setWords(oLetter);
int points = Integer.parseInt(oBadge);
oppWordModel.setPoints(points);
oppWordModel.setColumnno(column);
oppWordModel.setRowno(row);
mOpponentOneTurnWords.put(pos, oppWordModel);
}

for (Map.Entry<Integer, WordsModel> entry : mOpponentOneTurnWords.entrySet()) {
alstTop.set(entry.getKey(), entry.getValue());
mWordsHashMap.put(entry.getKey(), entry.getValue());
}
}
Log.e("TAG2", "alstTop -" + alstTop.size());
Log.e("TAG2", "mWordsHashMap -" + mWordsHashMap.size());
mWordsAdapter = new WordsAdapter(MainActivity.this,alstTop, intTopCellWidth, temp);
gridViewTop.setAdapter(mWordsAdapter);
mWordsAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}

return false;
}
});
}

OnItemLongClickListener gridTopClickListener = new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> l, View v, int Position,
long id) {
if (mWordsHashMap.containsKey(Position) && !mWordsHashMap.get(Position).isFlag()) {
intTopPos = Position;
boolGridTop = true;
// Selected item is passed as item in dragData
Log.v("TAG", "Position ::" + Position);
ClipData.Item item = new ClipData.Item(alstTop.get(Position)
.getWords() + alstTop.get(Position).getPoints());
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).getWords();
int strTopItemPoints = alstTop.get(Position).getPoints();
Log.i("strTopItem", "strTopItem==>>" + strTopItem);
Log.i("strTopPoints", "strTopPoints==>>" + strTopItemPoints);

alstTop.remove(intTopPos);
alstTop.add(intTopPos, null);
mWordsAdapter = new WordsAdapter(MainActivity.this, alstTop,intTopCellWidth, temp);
gridViewTop.setAdapter(mWordsAdapter);
mWordsAdapter.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)
.getWords() + alstBottom.get(Position).getPoints());
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).getWords();
int strBottomItemPoints = alstBottom.get(Position).getPoints();
Log.i("strBottomItem", "strBottomItem==>>" + strBottomItem);
Log.i("strBottomPoints", "strBottomPoints==>>"
+ strBottomItemPoints);

alstBottom.remove(intBottomPos);
alstBottom.add(intBottomPos, null);
// PlaySound();
mWordsAdapter = new WordsAdapter(MainActivity.this, alstBottom, intBottomCellWidth, temp);
gridViewBottom.setAdapter(mWordsAdapter);
mWordsAdapter.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:

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:
if (v == bottomLayout) {
// String droppedItem = item.getText().toString();
runOnUiThread(new Runnable() {
public void run() {
PlaySound(R.raw.beep);
}
});

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.remove(index);

WordsModel w = new WordsModel();
w.setWords(strBottom);
int points = Integer.parseInt(strBottomPoins);
w.setPoints(points);
alstBottom.add(index, w);
JSONObject jobj11 = new JSONObject();
try {
jobj11.put("row", row);
jobj11.put("badge", w.getPoints());
jobj11.put("col", column);
jobj11.put("letter", w.getWords().toString());

Log.i("NEW", "row is***********" + row);
Log.i("NEW", "Col is***********" + column);
jarry.put(jobj11);
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject json = new JSONObject();

try {
json.put("allWords", jarry);
json.put("mysocket_id", mysocket_id);
json.put("opponentsocket_id", opponentsocket_id);
json.put("myusername", myusername);
json.put("opponentusername", opponentusername);
json.put("current_playing_id", current_playing_id);
json.put("current_scoreChanel", current_scoreChanel);
json.put("opponenttype", opponenttype);
Log.e("TAG2", "Placetile" + json);
try {
socket.emit("placeTile", json);
Log.d("TAG", "Socket" + socket);
} catch (MalformedURLException e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
// PlaySound();
mWordsAdapter = new WordsAdapter(MainActivity.this, alstBottom,
intBottomCellWidth, temp);
gridViewBottom.setAdapter(mWordsAdapter);
mWordsAdapter.notifyDataSetChanged();
} else {
alstTop.remove(intTopPos);
WordsModel w = new WordsModel();
w.setWords(strTopItem);
alstTop.add(intTopPos, w);

mWordsAdapter = new WordsAdapter(MainActivity.this, alstTop,
intTopCellWidth, temp);
gridViewTop.setAdapter(mWordsAdapter);
mWordsAdapter.notifyDataSetChanged();
}
PlaySound(R.raw.beep);
}

private void updateTopToTopViewsAfterDropComplete(String listItem, int index) {
indexTopBottom = index;

Log.e("TAG", "pre Indexs -- " + intTopPos);
Log.e("TAG", "new Index-- " + index);

Log.e("TAG", "mWordsHashMap size-- " + mWordsHashMap.size());
if (mWordsHashMap.containsKey(intTopPos)) {
WordsModel mwModel = mWordsHashMap.get(intTopPos);
mWordsHashMap.put(index, mwModel);
mWordsHashMap.remove(intTopPos);

Log.e("TAG", "mWordsHashMap size2-- " + mWordsHashMap.size());
}
for (Map.Entry<Integer, WordsModel> entry : mWordsHashMap.entrySet()) {
int key = entry.getKey();
WordsModel value = entry.getValue();
Log.e("UPDATE", "### -- " + key + "   l == " + value.getWords());
}

Log.e("TAG", "mOneTurnWords size-- " + mOneTurnWords.size());
if (mOneTurnWords.containsKey(intTopPos)) {
WordsModel mwModel = mOneTurnWords.get(intTopPos);
mOneTurnWords.put(index, mwModel);
mOneTurnWords.remove(intTopPos);
Log.e("TAG", "mOneTurnWords size2-- " + mOneTurnWords.size());
}
for (Map.Entry<Integer, WordsModel> entry : mOneTurnWords.entrySet()) {
int key = entry.getKey();
WordsModel value = entry.getValue();
Log.e("UPDATE", "### -- " + key + "   l == " + value.getWords());
}

strTop = "" + listItem.charAt(0);
strTopPoints = listItem.substring(1);

if (alstTop.get(indexTopBottom) == null) {
alstTop.remove(indexTopBottom);
WordsModel w = new WordsModel();
w.setWords(strTop);
int points = Integer.parseInt(strTopPoints);
w.setPoints(points);
alstTop.add(indexTopBottom, w);

setData(indexTopBottom);

JSONArray updatedJsonArray = new JSONArray();
for (Map.Entry<Integer, WordsModel> entry : mOneTurnWords
.entrySet()) {
// int key = entry.getKey();
WordsModel value = entry.getValue();
JSONObject jobj11 = new JSONObject();
try {
jobj11.put("row", value.getRowno());
jobj11.put("badge", value.getPoints());
jobj11.put("col", value.getColumnno());
jobj11.put("letter", value.getWords().toString());

Log.i("NEW", "row is***********" + row);
Log.i("NEW", "Col is***********" + column);
updatedJsonArray.put(jobj11);
} catch (JSONException e) {
e.printStackTrace();
}

// Log.e("UPDATE", "### -- " + key + "   l == " +
// value.getWords());
}

/*
* JSONObject jobj11 = new JSONObject(); try { jobj11.put("row",
* row); jobj11.put("badge", w.getPoints()); jobj11.put("col",
* column); jobj11.put("letter", w.getWords().toString());
* Log.i("NEW", "row is***********" + row); Log.i("NEW",
* "Col is***********" + column); jarry.put(jobj11); } catch
* (JSONException e) { e.printStackTrace(); }
*/

Log.e("TAG5", "FULLARRAYLIST::::" + jarry);
JSONObject json = new JSONObject();

try {
json.put("allWords", updatedJsonArray);
json.put("mysocket_id", mysocket_id);
json.put("opponentsocket_id", opponentsocket_id);
json.put("myusername", myusername);
json.put("opponentusername", opponentusername);
json.put("current_playing_id", current_playing_id);
json.put("current_scoreChanel", current_scoreChanel);
json.put("opponenttype", opponenttype);
Log.e("NEW", "Placetile" + json);
try {
Log.d("TAG2", "Socket" + json);
socket.emit("placeTile", json);

} catch (MalformedURLException e) {
e.printStackTrace();
}

} catch (JSONException e) {
e.printStackTrace();
}
mWordsAdapter = new WordsAdapter(MainActivity.this, alstTop,
intTopCellWidth, temp);
gridViewTop.setAdapter(mWordsAdapter);
mWordsAdapter.notifyDataSetChanged();
} else {
alstTop.remove(intTopPos);
WordsModel w = new WordsModel();
w.setWords(strTopItem);
alstTop.add(intTopPos, w);
mWordsAdapter = new WordsAdapter(MainActivity.this, alstTop,
intTopCellWidth, temp);
gridViewTop.setAdapter(mWordsAdapter);
mWordsAdapter.notifyDataSetChanged();
}
PlaySound(R.raw.beep);
}

JSONArray jarry = new JSONArray();

@SuppressWarnings("static-access")
private void updateBottomToTopViewsAfterDropComplete(String listItem,
int index) {
indexTopBottom = index;
toast("index =" + index);
Log.d("NEW", "indexTopBottom : " + indexTopBottom);
strTop = "" + listItem.charAt(0);
strTopPoints = listItem.substring(1);

if (alstTop.get(indexTopBottom) == null) {
alstTop.remove(indexTopBottom);
WordsModel w = new WordsModel();
w.setFlag(false);
w.setIndex(indexTopBottom);
w.setWords(strTop);
w.setBottomPos(intBottomPos);
int points = Integer.parseInt(strTopPoints);
w.setPoints(points);
alstTop.add(indexTopBottom, w);
setData(indexTopBottom);

JSONObject jobj11 = new JSONObject();
try {
jobj11.put("row", row);
jobj11.put("badge", w.getPoints());
jobj11.put("col", column);
jobj11.put("letter", w.getWords().toString());

Log.i("NEW", "row is***********" + row);
Log.i("NEW", "Col is***********" + column);
jarry.put(jobj11);
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject json = new JSONObject();

try {
json.put("allWords", jarry);
json.put("mysocket_id", mysocket_id);
json.put("opponentsocket_id", opponentsocket_id);
json.put("myusername", myusername);
json.put("opponentusername", opponentusername);
json.put("current_playing_id", current_playing_id);
json.put("current_scoreChanel", current_scoreChanel);
json.put("opponenttype", opponenttype);
Log.e("TAG2", "Placetile" + json);
try {
socket.emit("placeTile", json);
Log.d("TAG", "Socket" + socket);
} catch (MalformedURLException e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
mWordsAdapter = new WordsAdapter(MainActivity.this, alstTop,
intTopCellWidth, temp);
gridViewTop.setAdapter(mWordsAdapter);
mWordsAdapter.notifyDataSetChanged();
} else {
alstBottom.remove(intBottomPos);
Log.i("intBottomPos==", "intBottomPos==>" + intBottomPos);
WordsModel w = new WordsModel();
w.setFlag(false);
w.setIndex(indexTopBottom);
w.setBottomPos(intBottomPos);
w.setWords(strBottomItem);
alstBottom.add(intBottomPos, w);
// PlaySound();
mWordsAdapter = new WordsAdapter(MainActivity.this, alstBottom,
intBottomCellWidth, temp);
gridViewBottom.setAdapter(mWordsAdapter);
mWordsAdapter.notifyDataSetChanged();
}

PlaySound(R.raw.beep);
}

private void updateBottomToBottomViewsAfterDropComplete(String listItem,
int index) {
String strBottom = "" + listItem.charAt(0);
String strBottomPoins = listItem.substring(1);
if (alstBottom.get(index) == null) {
alstBottom.remove(index);
WordsModel w = new WordsModel();
w.setFlag(false);
w.setBottomPos(intBottomPos);
w.setIndex(index);
w.setWords(strBottom);
int points = Integer.parseInt(strBottomPoins);
w.setPoints(points);
alstBottom.add(index, w);
Log.i("", "" + listItem.toString());
// PlaySound();
mWordsAdapter = new WordsAdapter(MainActivity.this, alstBottom,
intBottomCellWidth, temp);
gridViewBottom.setAdapter(mWordsAdapter);
mWordsAdapter.notifyDataSetChanged();
} else {
alstBottom.remove(intBottomPos);
WordsModel w = new WordsModel();
w.setWords(strBottomItem);
w.setFlag(false);
w.setIndex(intBottomPos);
w.setBottomPos(intBottomPos);
w.setWords(strBottomItem);
alstBottom.add(intBottomPos, w);
// PlaySound();
mWordsAdapter = new WordsAdapter(MainActivity.this, alstBottom,
intBottomCellWidth, temp);
gridViewBottom.setAdapter(mWordsAdapter);
mWordsAdapter.notifyDataSetChanged();
}
PlaySound(R.raw.beep);
}

private void setData(int position) {
column = position % total_col;
row = position / total_col;
Log.e("NEW :", "column ::" + column);
Log.e("NEW :", "row :" + row);
alstTop.remove(position);
Log.i("New", "remove position: " + position);
WordsModel wordsModel = new WordsModel();
wordsModel.setFlag(false);

Log.e("TAG", "Text -- " + strTop);
wordsModel.setWords(strTop);

int point = Integer.parseInt(strTopPoints);
Log.e("TAG", "Point -- " + strTopPoints);
wordsModel.setPoints(point);
wordsModel.setColumnno(column);
wordsModel.setRowno(row);
wordsModel.setBottomPos(intBottomPos);
wordsModel.setIndex(position);
Log.e("NEW :", "Position -- " + position);
alstTop.add(position, wordsModel);

mWordsHashMap.put(position, wordsModel);
Log.e("TAG", "SIZE HASHMAP -- " + mWordsHashMap.size());

for (Map.Entry<Integer, WordsModel> entry : mWordsHashMap.entrySet()) {
int Main_key = entry.getKey();
WordsModel v = entry.getValue();

Log.e("TAG",
" & Key is : " + Main_key + " Word : " + v.getWords()
+ " Position :" + v.getIndex() + " Row number :"
+ v.getRowno() + " Column Number :"
+ v.getColumnno() + " FLAG :" + v.isFlag());
}
mOneTurnWords.put(position, wordsModel);

// if (position == 3 || position == 9 || position == 39 || position ==
// 51
// || position == 117 || position == 129 || position == 159
// || position == 165) {
//
// // For TRIPLE WORDS
// toast("For TRIPLE WORDS");
//
// } else if (position == 28 || position == 36 || position == 56
// || position == 60 || position == 108 || position == 112
// || position == 132 || position == 140) {
//
// // For TRIPLE LETTER
// toast("For TRIPLE LETTER");
//
// } else if (position == 32 || position == 80 || position == 88
// || position == 136) {
//
// // FOR DOUBLE WORD
// toast("FOR DOUBLE WORD");
//
// } else if (position == 44 || position == 46 || position == 68
// || position == 74 || position == 94 || position == 100
// || position == 122 || position == 124) {
// // FOR DOUBLE LETTER
// toast("FOR DOUBLE LETTER");
// }
// Log.e("TAG", "Size == " + mWordsHashMap.size());
// ** Remove duplicate value from hashmap **
for (Iterator<Map.Entry<Integer, WordsModel>> it = mWordsHashMap
.entrySet().iterator(); it.hasNext();) {
Map.Entry<Integer, WordsModel> entry = it.next();
Log.v("TAG", "Cell Number:" + intTopPos);
if (mWordsHashMap.size() == 1) {
intTopPos = 0;
}
if (entry.getKey().equals(intTopPos)) {
it.remove();
Log.d("TAG", "Remove it....");
}
}
}

public void toast(String msg) {
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
}

public synchronized void checkHorizontallyRight(int position) {
Log.e("", "checkHorizontallyRight..");
Log.v("TAG", "Right position :=" + position);
try {
WordsPosition wordsPosition = checkWordsPosition(position);
if (wordsPosition != WordsPosition.RT
&& wordsPosition != WordsPosition.RB
&& wordsPosition != WordsPosition.RE) {

if (!mMatchedHorizontalWords.containsKey(position + 1)) {
Log.v("HorizontallyRight Word :",
"" + mWordsHashMap.get(position).getWords());
Log.v("HorizontallyRight ContainsKey :",
"" + mWordsHashMap.containsKey(position + 1));
if (mWordsHashMap.containsKey(position + 1)) {
mMatchedHorizontalWords.put(position + 1,
mWordsHashMap.get(position + 1));
checkHorizontallyRight(position + 1);
} else {
checkHorizontallyLeft(position);
}
} else {
checkHorizontallyLeft(position);
}
} else {
checkHorizontallyLeft(position);
}
} catch (Exception e) {
e.printStackTrace();
}
}

public synchronized void checkHorizontallyLeft(final int position) {
Log.e("", "checkHorizontallyLeft..");
Log.v("TAG", "Left position :=" + position);
try {
WordsPosition wordsPosition = checkWordsPosition(position);
if (wordsPosition != WordsPosition.LT
&& wordsPosition != WordsPosition.LB
&& wordsPosition != WordsPosition.LE) {
if (!mMatchedHorizontalWords.containsKey(position - 1)) {
Log.v("HorizontallyLeft Word :",
"" + mWordsHashMap.get(position).getWords());
Log.v("HorizontallyLeft ContainsKey :",
"" + mWordsHashMap.containsKey(position - 1));

if (mWordsHashMap.containsKey(position - 1)) {
mMatchedHorizontalWords.put(position - 1,
mWordsHashMap.get(position - 1));
checkHorizontallyLeft(position - 1);
} else {
WordDetectHorizontaly(position);
}
} else {
checkHorizontallyLeft(position - 1);
}
} else {
WordDetectHorizontaly(position);
}
} catch (Exception e) {
e.printStackTrace();
} /*
* finally { WordDetectHorizontaly(); }
*/
}

private void WordDetectHorizontaly(int position) {
Log.e("", "WordDetectHorizontaly..");
Log.v("TAG", "WordDetectHorizontaly position :=" + position);
if (!mMatchedHorizontalWords.containsKey(position)) {
mMatchedHorizontalWords.put(position, mWordsHashMap.get(position));
}

int total_points = 0;
for (Map.Entry<Integer, WordsModel> wordDetect : mMatchedHorizontalWords
.entrySet()) {
Integer key = wordDetect.getKey();
WordsModel value = wordDetect.getValue();
total_points = total_points + value.getPoints();
Log.e("Horizontally",
" & Key is : " + key + " Word : " + value.getWords()
+ " Points:" + value.getPoints() + " Total Points:"
+ total_points + " FLAG :" + value.isFlag());
}

ArrayList<WordsModel> newArray = new ArrayList<WordsModel>();
newArray.addAll(mMatchedHorizontalWords.values());
mFinalWords.put("H" + hIndex, newArray);
Log.e("TAG", "final added H newArray-- " + newArray.size());
Log.e("TAG", "final added H-- " + mFinalWords.size());
mMatchedHorizontalWords.clear();
}

public synchronized void checkVerticallyUp(int position) {
Log.e("", "checkVerticallyUp..");
Log.v("TAG", "UP position :=" + position);
try {
WordsPosition wordsPosition = checkWordsPosition(position);
if (wordsPosition != WordsPosition.LT
&& wordsPosition != WordsPosition.RT
&& wordsPosition != WordsPosition.TE) {
if (!mMatchedVerticalWords.containsKey(position - total_row)) {
Log.v("VerticallyUp Word :",
"" + mWordsHashMap.get(position).getWords());
Log.v("VerticallyUp ContainsKey :",
""
+ mWordsHashMap.containsKey(position
- total_row));
if (mWordsHashMap.containsKey(position - total_row)) {
mMatchedVerticalWords.put(position - total_row,
mWordsHashMap.get(position - total_row));
checkVerticallyUp(position - total_row);
} else {
checkVerticallyDown(position);
}
} else {
checkVerticallyDown(position);
}
} else {
checkVerticallyDown(position);
}
} catch (Exception e) {
e.printStackTrace();
}
/*
* finally { checkVerticallyDown(position); }
*/
}

public synchronized void checkVerticallyDown(int position) {
Log.e("", "checkVerticallyDown..");
Log.v("TAG", "Down position :=" + position);
try {
WordsPosition wordsPosition = checkWordsPosition(position);
if (wordsPosition != WordsPosition.LB
&& wordsPosition != WordsPosition.RB
&& wordsPosition != WordsPosition.BE) {
if (!mMatchedVerticalWords.containsKey(position + total_row)) {
Log.v("VerticallyDown Word :",
"" + mWordsHashMap.get(position).getWords());
Log.v("VerticallyDown ContainsKey :",
""
+ mWordsHashMap.containsKey(position
+ total_row));
if (mWordsHashMap.containsKey(position + total_row)) {
mMatchedVerticalWords.put(position + total_row,
mWordsHashMap.get(position + total_row));
checkVerticallyDown(position + total_row);
} else {
WordDetectVerticaly(position);
}
} else {
checkVerticallyDown(position + total_row);
// WordDetectVerticaly(position);
}
} else {
WordDetectVerticaly(position);
}
} catch (Exception e) {
e.printStackTrace();
}
}

private void WordDetectVerticaly(int position) {
Log.e("", "WordDetectVerticaly..");
if (!mMatchedVerticalWords.containsKey(position)) {
mMatchedVerticalWords.put(position, mWordsHashMap.get(position));
}
int total_points = 0;
for (Map.Entry<Integer, WordsModel> wordDetect : mMatchedVerticalWords
.entrySet()) {
Integer key = wordDetect.getKey();
WordsModel value = wordDetect.getValue();
// if (value.getWords().equals(value.isFlag())) {

total_points = total_points + value.getPoints();
Log.e("Vertically",
" & Key is : " + key + " Word : " + value.getWords()
+ " Points:" + value.getPoints() + " Total Points:"
+ total_points + " FLAG :" + value.isFlag());
// } else {
// Log.v("FLAG", "Flag not true");
// }
}
ArrayList<WordsModel> newArray = new ArrayList<WordsModel>();
newArray.addAll(mMatchedVerticalWords.values());
mFinalWords.put("V" + hIndex, newArray);
Log.e("TAG", "final added V newArray-- " + newArray.size());
Log.e("TAG", "final added V-- " + mFinalWords.size());
mMatchedVerticalWords.clear();
}

private synchronized WordsPosition checkWordsPosition(int position) {
// Log.e("", "checkWordsPosition..");
int row_no = mWordsHashMap.get(position).getRowno();
int col_no = mWordsHashMap.get(position).getColumnno();

Log.v("ColumnNumber:", "" + col_no);
Log.v("RowNumber :", "" + row_no);

int highest_row = total_row - 1;
int highest_col = total_col - 1;

if (row_no > 0 && row_no < highest_row && col_no > 0
&& col_no < highest_col) {
return WordsPosition.CENTER;
} else if (row_no == 0 && col_no == 0) {
return WordsPosition.LB;
} else if (row_no == highest_row && col_no == highest_col) {
return WordsPosition.RT;
} else if (row_no == 0 && col_no == highest_col) {
return WordsPosition.RB;
} else if (row_no == highest_row && col_no == 0) {
return WordsPosition.LT;
} else if (col_no == 0) {
return WordsPosition.LE;
} else if (col_no == highest_col) {
return WordsPosition.RE;
} else if (row_no == highest_row) {
return WordsPosition.TE;
} else if (row_no == 0) {
return WordsPosition.BE;
}
return null;
}

int hIndex;
Map<String, Boolean> map = new HashMap<String, Boolean>();

public void onSubmit(View view) {

Log.v("OnSubmit", "OnSubmit");

mFinalWords.clear();
PlaySound(R.raw.default_click);

for (Map.Entry<Integer, WordsModel> entry : mOneTurnWords.entrySet()) {
int key = entry.getKey();
Log.e("mOneTurnWords", "mOneTurnWords==" + key);

WordsModel value = entry.getValue();
hIndex = key;
Log.e("SUBMIT", "word -- " + key + "   l == " + value.getWords());
Log.e("SUBMIT",
"word -- " + key + "   l == " + value.getBottomPos());

mMatchedHorizontalWords.clear();
mMatchedVerticalWords.clear();

mMatchedHorizontalWords.put(key, mWordsHashMap.get(key));
mMatchedVerticalWords.put(key, mWordsHashMap.get(key));
checkHorizontallyRight(key);
checkVerticallyUp(key);
}

map.clear();
alstFinalWordKey.clear();
for (Entry<String, ArrayList<WordsModel>> finalWords : mFinalWords
.entrySet()) {
String key = finalWords.getKey();
finalValue = finalWords.getValue();
Log.i("key", "key = " + key);
str = "";
for (int i = 0; i < finalValue.size(); i++) {
str = str + finalValue.get(i).getWords();
Log.i("key", "finalValue Word = "
+ finalValue.get(i).getWords());
if (i == finalValue.size() - 1) {
Log.e("FINAL", "MAP == : " + map.containsKey(str));
int count = 0;
if (!map.containsKey(str) && str.length() > 1) {
map.put(str, false);
if (!alstFinalWordKey.contains(key)) {
alstFinalWordKey.add(key);
}
Log.e("FINAL", "MAP == : " + map.size());
count = count + 1;
Log.e("FINAL", "Count == " + count);
// mScs.getSuggestions(new TextInfo(str), 3);
Toast.makeText(getApplicationContext(), str,
Toast.LENGTH_SHORT).show();
Toast.makeText(MainActivity.this, "String -- " + str,
Toast.LENGTH_SHORT).show();
Log.i("FINAL", "final string -- " + str);
if (str.length() > 1) {
try {
mDBHelper.openDataBase();
} catch (SQLException sqle) {
throw sqle;
}
// mDBHelper.openDataBase();
str = str.toLowerCase();
if (mDBHelper.Selectword(mDBHelper.myDataBase, str)) {
toast("Word is corecttttt");
map.put(str, true);
Boolean allword = false;
for (Entry<String, Boolean> entry : map
.entrySet()) {
Log.v("FINAL", "VALUE :" + entry.getValue());

boolean flag = entry.getValue();
String key1 = entry.getKey();

if (!allword) {
allword = flag;
}
Log.v("FINAL", " ALLWORD : " + allword);
Log.v("FINAL", " FLAG : " + flag);
Log.v("FINAL", " KEY : " + key1);

// opponentflag = true;
}
OnResult(allword);
} else {
Message msg = new Message();
msg.obj = "WrongWord";
MainActivity.Mainhandler.sendMessage(msg);

Recall();
toast("Word is wrong");

}
mDBHelper.close();
}
}
}
}
}
}

private void OnResult(Boolean allword) {
Log.v("OnResult", "OnResult");

JSONArray redecoyjs = new JSONArray();
JSONArray letterusedjs = new JSONArray();
alstLetterUsed.clear();
// alstBottomposition.clear();
if (allword) {
// success
Log.v("FINAL", "SUCCESSFULL");
for (Map.Entry<Integer, WordsModel> entry : mOneTurnWords
.entrySet()) {
int key = entry.getKey();
String strKey = Integer.toString(key);
direction = 0;
if (strKey.charAt(0) == 'H') {
direction = 1;
Log.e("direction", "direction==" + direction);
} else {
direction = 2;
Log.e("direction", "direction==" + direction);
}
Log.i("direction", "direction==" + direction);
alstTop.remove(key);
WordsModel value = entry.getValue();
value.setFlag(true);
// Log.e("TAG",
Log.i("Key",
"mOneTurnWords word = " + key + " l = "
+ value.getWords() + " Flag = "
+ value.isFlag());

alstTop.add(key, value);
alstLetterUsed.add(value.getWords());
letterusedjs.put(value.getWords());
alstBottomposition.add(value.getBottomPos());
mWordsHashMap.put(key, value);
}
Log.i("TAG5", "BottomSize::" + alstBottom.size());

for (int i = 0; i < alstBottom.size(); i++) {
if (alstBottom.get(i) != null) {
redecoyjs.put(alstBottom.get(i).getWords().toString());
/*
* ArrayList<String> alstletterunused11 = new
* ArrayList<String>();
* alstletterunused.add(alstBottom.get(i
* ).getWords().toString());
* addresses.add(alstletterunused);
*/
// Log.d("TAG5" , "Bottomletters" +
// alstletterunused.add(alstBottom.get(i).getWords()));
Log.e("TAG5", "BottomLetters" + redecoyjs);
}

}

Log.i("alstLetterUsed=",
"alstLetterUsed==" + alstLetterUsed.toString());
Log.i("alstBottomposition=", "alstBottomposition=="
+ alstBottomposition.toString());
for (Map.Entry<Integer, WordsModel> entry1 : mWordsHashMap
.entrySet()) {
int key = entry1.getKey();
WordsModel wordsModel = entry1.getValue();
Log.e("Key",
"mWordsHashMap word = " + key + " l = "
+ wordsModel.getWords() + "Flag = "
+ wordsModel.isFlag());
}
setCellBg();
// for (Entry<String, ArrayList<WordsModel>> finalWords :
// mFinalWords.entrySet()){

for (Entry<String, ArrayList<WordsModel>> finalwords : mFinalWords
.entrySet()) {
String Key = finalwords.getKey();
Log.i("Key", "KeyTop=" + Key);
for (int j = 0; j < alstFinalWordKey.size(); j++) {
if (alstFinalWordKey.get(j).equalsIgnoreCase(Key)) {
Log.i("Key", "Key==" + Key);
Log.i("Key",
"alstFinalWordKey==" + alstFinalWordKey.get(j));
finalValue = finalwords.getValue();

// get First Word Position;
strFWPostion = "";
String word = "";
String strTripleWord = "";
String strDoubleWord = "";
int point = 0, wordPos;
int total = 0;
int intSize = 0;
for (int i = 0; i < finalValue.size(); i++) {
word = finalValue.get(i).getWords();
point = finalValue.get(i).getPoints();
wordPos = finalValue.get(i).getIndex();
strFWPostion = "space_"
+ finalValue.get(0).getRowno() + "_"
+ finalValue.get(0).getColumnno();
// Log.i("Key", "strFWPostion==" + word);
// Log.i("Key", "word==" + word);
// Log.i("Key", "Point==" + point);
if (wordPos == 3 || wordPos == 9 || wordPos == 39
|| wordPos == 51 || wordPos == 117
|| wordPos == 129 || wordPos == 159
|| wordPos == 165) {
total = total + point;
// Log.i("Key", "word=" + word + "total==>>" +
// total);
strTripleWord = "TW";
// For TRIPLE WORDS
toast("FOR TRIPLE WORDS");
} else if (wordPos == 28 || wordPos == 36
|| wordPos == 56 || wordPos == 60
|| wordPos == 108 || wordPos == 112
|| wordPos == 132 || wordPos == 140) {
total = total + point * 3;
Log.i("Key", "word=" + word + "total==>>"
+ total);
// For TRIPLE LETTER
toast("FOR TRIPLE LETTER");
} else if (wordPos == 32 || wordPos == 80
|| wordPos == 88 || wordPos == 136) {
total = total + point;
Log.i("Key", "word=" + word + "total==>>"
+ total);
strDoubleWord = "DW";
// FOR DOUBLE WORD
toast("FOR DOUBLE WORD");
} else if (wordPos == 44 || wordPos == 46
|| wordPos == 68 || wordPos == 74
|| wordPos == 94 || wordPos == 100
|| wordPos == 122 || wordPos == 124) {
total = total + point * 2;
Log.i("Key", "word=" + word + "total==>>"
+ total);
// FOR DOUBLE LETTER
toast("FOR DOUBLE LETTER");
} else {
total = total + point;
Log.i("Key", "word=" + word + "total==>>"
+ total);
}
}

if (strDoubleWord.equalsIgnoreCase("DW")) {
total = total * 2;
Log.i("Key", "word=" + word + "total==DW>>" + total);
} else if (strTripleWord.equalsIgnoreCase("TW")) {
total = total * 3;
Log.i("Key", "word=" + word + "total==TW>>" + total);
} else {

}

toast("Final total==>>" + total);
Log.i("Key", "Final total==>>" + total);
intGrandTotal = intGrandTotal + total;
toast("intGrandTotal==>>" + intGrandTotal);
Log.i("Key", "intGrandTotal==>>" + intGrandTotal);
}
}
}

// setCellBg();
// setPoints();
// PlaySound();
mWordsAdapter = new WordsAdapter(MainActivity.this, alstBottom,
intBottomCellWidth, temp);
gridViewBottom.setAdapter(mWordsAdapter);
mWordsAdapter.notifyDataSetChanged();

mWordsAdapter = new WordsAdapter(this, alstTop, intTopCellWidth,
temp);
gridViewTop.setAdapter(mWordsAdapter);
mWordsAdapter.notifyDataSetChanged();

mOneTurnWords.clear();
finalValue.clear();
// mFinalWords.clear();
alstFinalWordKey.clear();
} else {
Recall();
Log.v("FINAL", "UN-SUCCESSFULL");
}

JSONObject connectjson = new JSONObject();
try {
connectjson.put("connected", true);
connectjson.put("direction", direction);
connectjson.put("playpoints", intGrandTotal);
connectjson.put("startpoint", strFWPostion);
connectjson.put("playword", str);
connectjson.put("message", "You created the words" + str);
Log.i("TAG4", "connectjson" + connectjson);

} catch (JSONException e) {
e.printStackTrace();
}
JSONObject submitjson = new JSONObject();

try {
submitjson.put("mysocket_id", dynamicuserid);
submitjson.put("opponentsocket_id", opponentsocket_id);
submitjson.put("myusername", myusername);
submitjson.put("opponentusername", opponentusername);
submitjson.put("current_playing_id", current_playing_id);
submitjson.put("current_scoreChanel", current_scoreChanel);
submitjson.put("opponenttype", opponenttype);
// ArrayList<String> reqdecoy = new
// ArrayList<String>(Arrays.asList("0","3"));
/*
* JSONArray jsonarr = new JSONArray(); jsonarr.put("a");
* jsonarr.put("b"); jsonarr.put("b"); jsonarr.put("b");
* jsonarr.put("b");
*/
submitjson.put("reqdecoy", redecoyjs);
ArrayList<String> letterused = new ArrayList<String>(Arrays.asList(
"P", "I"));
JSONArray jsonarr1 = new JSONArray(alstLetterUsed);
submitjson.put("letterused", letterusedjs);
submitjson.put("connectedwords", connectjson);
Log.i("TAG5", "submitjson" + submitjson);
socket.emit("submitPlay", submitjson);
} catch (JSONException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
}

map.clear();
// finalValue.clear();
// mFinalWords.clear();
mMatchedHorizontalWords.clear();
mMatchedVerticalWords.clear();

}

public void Recall() {
PlaySound(R.raw.default_click);
Log.v("FINAL", "Recall");
for (Map.Entry<Integer, WordsModel> entry : mOneTurnWords.entrySet()) {
int key = entry.getKey();
mWordsHashMap.remove(key);
WordsModel value = entry.getValue();
hIndex = key;
if (!value.isFlag()) {
alstTop.remove(value.getIndex());
alstTop.add(value.getIndex(), null);
alstBottom.remove(value.getBottomPos());
// WordsModel w = new WordsModel();
// w.setIndex(value.getBottomPos());
// w.setBottomPos(value.getBottomPos());
// w.setWords(value.getWords());
// w.setPoints(value.getPoints());
// w.setFlag(false);
alstBottom.add(value.getBottomPos(), value);
} else {
Log.v("FINAL", "FLAG FALSE");
}
}

// PlaySound();
mWordsAdapter = new WordsAdapter(MainActivity.this, alstBottom,
intBottomCellWidth, temp);
gridViewBottom.setAdapter(mWordsAdapter);
mWordsAdapter.notifyDataSetChanged();

mWordsAdapter = new WordsAdapter(this, alstTop, intTopCellWidth, temp);
gridViewTop.setAdapter(mWordsAdapter);
mWordsAdapter.notifyDataSetChanged();

mOneTurnWords.clear();
finalValue.clear();
// mFinalWords.clear();
alstFinalWordKey.clear();
Log.v("FINAL", "SIZE of mOneTurnWords:" + mOneTurnWords.size());
Log.v("FINAL", "SIZE of mWordsHashMap:" + mWordsHashMap.size());
// toast("SIZE of mOneTurnWords:" + mOneTurnWords.size());
// toast("SIZE of mWordsHashMap:" + mWordsHashMap.size());
}

public void PlaySound(int id) {
if (Constants.getPref(Constants.Music, this) == 1) {
mp = MediaPlayer.create(this, id);
if (mp.isPlaying()) {
mp.stop();
try {
mp.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
mp.start();
}
} else {

}
}

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnRecall:
Recall();
break;
default:
break;
}
}

@Override
protected void onDestroy() {
editor.clear();
super.onDestroy();
}

public void setCellBg() {
for (Map.Entry<Integer, WordsModel> hashmap : mWordsHashMap.entrySet()) {
int key = hashmap.getKey();
WordsModel wordsModel = hashmap.getValue();
if (wordsModel.isFlag()) {
// four corners
if (checkWordsPosition(key) == WordsPosition.LT) {
wordsModel.setPlace("LT");
} else if (checkWordsPosition(key) == WordsPosition.LB) {
wordsModel.setPlace("LB");
} else if (checkWordsPosition(key) == WordsPosition.RT) {
wordsModel.setPlace("RT");
} else if (checkWordsPosition(key) == WordsPosition.RB) {
wordsModel.setPlace("RB");
}

// T, L, R, B
else {
WordsPosition wordsPosition = checkWordsPosition(key);
boolean left, right, top, bottom;
if (wordsPosition != WordsPosition.LT
&& wordsPosition != WordsPosition.RT
&& wordsPosition != WordsPosition.TE) {
if (mWordsHashMap.containsKey(key - total_row)) {
if (mWordsHashMap.get(key - total_row) != null
&& mWordsHashMap.get(key - total_row)
.isFlag() == true) {
top = true;
} else {
top = false;
}
} else {
top = false;
}
} else {
top = false;
}

if (wordsPosition != WordsPosition.LB
&& wordsPosition != WordsPosition.RB
&& wordsPosition != WordsPosition.BE) {
if (mWordsHashMap.containsKey(key + total_row)) {
if (mWordsHashMap.get(key + total_row) != null
&& mWordsHashMap.get(key + total_row)
.isFlag() == true) {
bottom = true;
} else {
bottom = false;
}
} else {
bottom = false;
}
} else {
bottom = false;
}

if (wordsPosition != WordsPosition.LT
&& wordsPosition != WordsPosition.LB
&& wordsPosition != WordsPosition.LE) {
if (mWordsHashMap.containsKey(key - 1)) {
if (mWordsHashMap.get(key - 1) != null
&& mWordsHashMap.get(key - 1).isFlag() == true) {
left = true;
} else {
left = false;
}
} else {
left = false;
}
} else {
left = false;
}

if (wordsPosition != WordsPosition.RT
&& wordsPosition != WordsPosition.RB
&& wordsPosition != WordsPosition.RE) {
if (mWordsHashMap.containsKey(key + 1)) {
if (mWordsHashMap.get(key + 1) != null
&& mWordsHashMap.get(key + 1).isFlag() == true) {
right = true;
} else {
right = false;
}
} else {
right = false;
}
} else {
right = false;
}

// check conditions
// T
if (top == false && bottom == true && left == false
&& right == false) {
wordsModel.setPlace("T");
}

// B
else if (top == true && bottom == false && left == false
&& right == false) {
wordsModel.setPlace("B");
}

// R
else if (top == false && bottom == false && left == true
&& right == false) {
wordsModel.setPlace("R");
}

// L
else if (top == false && bottom == false && left == false
&& right == true) {
wordsModel.setPlace("L");
}

// Center
else if (top == true && bottom == true && left == true
&& right == true) {
wordsModel.setPlace("C");
}

// Center Horizontal
else if (top == true && bottom == true && left == false
&& right == false) {
wordsModel.setPlace("CH");
}

// Center Vertical
else if (top == false && bottom == false && left == true
&& right == true) {
wordsModel.setPlace("CV");
}

// LT
else if (top == false && bottom == true && left == false
&& right == true) {
wordsModel.setPlace("LT");
}
// LB
else if (top == true && bottom == false && left == false
&& right == true) {
wordsModel.setPlace("LB");
}

// RT
else if (top == false && bottom == true && left == true
&& right == false) {
wordsModel.setPlace("RT");
}

// RB
else if (top == true && bottom == false && left == true
&& right == false) {
wordsModel.setPlace("RB");
}
// BE
else if (top == true && bottom == false && left == true
&& right == true) {
wordsModel.setPlace("BE");
}

// TE
else if (top == false && bottom == true && left == true
&& right == true) {
wordsModel.setPlace("TE");
}

// RE
else if (top == true && bottom == true && left == true
&& right == false) {
wordsModel.setPlace("RE");
}

// LE
else if (top == true && bottom == true && left == false
&& right == true) {
wordsModel.setPlace("LE");
} else {
wordsModel.setPlace("TILE");
}
}
}
mWordsHashMap.put(key, wordsModel);
}
}

// This method is used for cell points
int cellPoint = 0;

public int setCellPoint(String word) {
if (word.equalsIgnoreCase("A") || word.equalsIgnoreCase("E")
|| word.equalsIgnoreCase("I") || word.equalsIgnoreCase("N")
|| word.equalsIgnoreCase("O") || word.equalsIgnoreCase("R")
|| word.equalsIgnoreCase("S") || word.equalsIgnoreCase("T")) {
cellPoint = 1;
} else if (word.equalsIgnoreCase("D") || word.equalsIgnoreCase("L")
|| word.equalsIgnoreCase("U")) {
cellPoint = 2;
} else if (word.equalsIgnoreCase("B") || word.equalsIgnoreCase("F")
|| word.equalsIgnoreCase("G") || word.equalsIgnoreCase("H")
|| word.equalsIgnoreCase("M") || word.equalsIgnoreCase("P")
|| word.equalsIgnoreCase("Y")) {
cellPoint = 3;
} else if (word.equalsIgnoreCase("C") || word.equalsIgnoreCase("W")) {
cellPoint = 4;
} else if (word.equalsIgnoreCase("K") || word.equalsIgnoreCase("V")) {
cellPoint = 5;
} else if (word.equalsIgnoreCase("J") || word.equalsIgnoreCase("X")) {
cellPoint = 8;
} else if (word.equalsIgnoreCase("Q") || word.equalsIgnoreCase("Z")) {
cellPoint = 10;
}
return cellPoint;
}

public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}

@Override
public void onFinish() {

if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
// dialog.dismiss();
// text.setVisibility(View.GONE);

// countDownTimer.onFinish();

}

@Override
public void onTick(long millisUntilFinished) {
text.setText("" + millisUntilFinished / 1000);
// if (text.getText().toString().equalsIgnoreCase("1")) {
// // countDownTimer.cancel();
// // dialog.dismiss();
// }
}

// @Override
// public void onBackPressed() {
// super.onBackPressed();
// handler.removeCallbacks(runnable);
// }
}
}