Friday, 26 February 2016


Custom Alerts

package com.sollet.buzz.main;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.sollet.buzz.common.Common;
import com.sollet.buzz.dto.MyApplication;
import com.sollet.buzz.utils.UiUtility;

import java.util.Enumeration;
import java.util.Vector;

public class MyAlertDialog extends Activity {
UiUtility uiUtility= new UiUtility();
MyApplication myapp;
Button closeButton;
Button readButton;
TextView sender;
TextView message;
Intent myIntent;
Vector pendingVector = new Vector();
Button attachButton = null;
OnClickListener attachmentOnClickListener=null;
String linkString ;

protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);

setContentView(R.layout.mydialog);
myapp = (MyApplication)getApplication();
getWindow().getAttributes().windowAnimations = R.style.Alertstyle;

Window window = this.getWindow();
WindowManager.LayoutParams wlp = window.getAttributes();
window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
window.setAttributes(wlp);
String headerfontPath = "fonts/titlefont.ttf";

// Loading Font Face
Typeface headerTF = Typeface.createFromAsset(getAssets(), headerfontPath);

myIntent = getIntent();
sender=(TextView) findViewById(R.id.from);
sender.setTypeface(headerTF);

message=(TextView) findViewById(R.id.message);
message.setMovementMethod(new ScrollingMovementMethod());
sender.setText(myIntent.getExtras().getString("from"));

String message_=myIntent.getExtras().getString("messgaebody");
int msgIndex = message_.indexOf("|||F");

if (msgIndex != -1) {

message_ = message_.substring(0, msgIndex);
}
message.setText(message_);

try{
if(!Common.isAscii(myIntent.getExtras().getString("messgaebody").substring(0, 1))){
message.setTextSize(20);
message.setMaxLines(9);
}
}catch (Exception e) {

}


// if(!uiUtility.isAscii(myIntent.getExtras().getString("messgaebody"))){
// message.setTextSize(20);
// message.setMaxLines(9);
// }

attachButton = (Button) findViewById(R.id.attachment);
linkString = myIntent.getExtras().getString("link");
if(linkString.trim().length() > 0) {
attachmentOnClickListener = new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

uiUtility.showProgressBar(MyAlertDialog.this, "Downloading Wait...");
Thread t = new Thread() {

public void run() {
uiUtility.saveAndOpenFile(MyAlertDialog.this, linkString);
}
};

t.start();


}
};
attachButton.setOnClickListener(attachmentOnClickListener);
}

if(linkString.trim().length()>0){
attachButton.setVisibility(View.VISIBLE);

String fileName = uiUtility.getFileNameFromURL(linkString);
String fileExtenString= uiUtility.getFileExtensionFromFile(fileName);
if(fileExtenString.equalsIgnoreCase("image/*")){
uiUtility.setDrawableToButton(this, attachButton, "LEFT", R.drawable.ic_image_attach);
attachButton.setText(" (Click here to view attachment)");
}else if(fileExtenString.equalsIgnoreCase("video/*")){
uiUtility.setDrawableToButton(this, attachButton, "LEFT", R.drawable.ic_video_attach);
attachButton.setText(" (Click here to play video)");
}else if(fileExtenString.equalsIgnoreCase("audio/*")){
uiUtility.setDrawableToButton(this, attachButton, "LEFT", R.drawable.ic_audio_attach);
attachButton.setText(" (Click here to play audio)");
}else if(fileExtenString.equalsIgnoreCase("application/*")){
uiUtility.setDrawableToButton(this, attachButton, "LEFT", R.drawable.ic_docfiles);
attachButton.setText(" (Click here to Open doc)");
}else{
uiUtility.setDrawableToButton(this, attachButton, "LEFT", R.drawable.ic_attachment);
attachButton.setText(" (Click here for attachment)");
}

}else{
attachButton.setVisibility(View.GONE);
}





closeButton=(Button) findViewById(R.id.ok);
closeButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (!pendingVector.isEmpty()) {

String messageContent = pendingVector.firstElement().toString();
int index = messageContent.indexOf("|||");
int linkindex = messageContent.indexOf("$|$");
String pendingfrom = messageContent.substring(0, index);
String pendingmessage = messageContent.substring(index + 3,linkindex);
linkString = messageContent.substring(linkindex+3);
UiUtility.printMe("title===" + pendingfrom + "body===" + pendingmessage);

sender.setText(pendingfrom);


String message_ = pendingmessage;
int msgIndex = message_.indexOf("|||F");

if (msgIndex != -1) {

message_ = message_.substring(0, msgIndex);
}


message.setText(message_);
if(!Common.isAscii(pendingmessage)){
message.setTextSize(20);
message.setMaxLines(9);
}else{
message.setTextSize(15);
message.setMaxLines(15);
}

if( linkString.trim().length() > 0){
attachButton.setVisibility(View.VISIBLE);
String fileName = uiUtility.getFileNameFromURL(linkString);
String fileExtenString= uiUtility.getFileExtensionFromFile(fileName);
if(fileExtenString.equalsIgnoreCase("image/*")){
uiUtility.setDrawableToButton(MyAlertDialog.this, attachButton, "LEFT", R.drawable.ic_image_attach);
attachButton.setText(" (Click here to view attachment)");
}else if(fileExtenString.equalsIgnoreCase("video/*")){
uiUtility.setDrawableToButton(MyAlertDialog.this, attachButton, "LEFT", R.drawable.ic_video_attach);
attachButton.setText(" (Click here to play video)");
}else if(fileExtenString.equalsIgnoreCase("audio/*")){
uiUtility.setDrawableToButton(MyAlertDialog.this, attachButton, "LEFT", R.drawable.ic_audio_attach);
attachButton.setText(" (Click here to play audio)");
}else if(fileExtenString.equalsIgnoreCase("application/*")){
uiUtility.setDrawableToButton(MyAlertDialog.this, attachButton, "LEFT", R.drawable.ic_docfiles);
attachButton.setText(" (Click here to Open doc)");
}else{
uiUtility.setDrawableToButton(MyAlertDialog.this, attachButton, "LEFT", R.drawable.ic_attachment);
attachButton.setText(" (Click here for attachment)");
}

}else{
attachButton.setVisibility(View.GONE);
}

pendingVector.removeElement(pendingVector.firstElement());
} else {
finish();
}
}
});

readButton=(Button) findViewById(R.id.read);
readButton.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
boolean isDataRemoved = pendingVector.removeAll(pendingVector);

Intent intent =new Intent(MyAlertDialog.this, ACTMainScreen.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
});

final LinearLayout adLinLay = (LinearLayout) findViewById(R.id.slider);
myapp.loadAd(adLinLay);

}

@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
myIntent = getIntent();
UiUtility.printMe("----------------" + myIntent.getExtras().getString("messgaebody"));
pendingVector.addElement(myIntent.getExtras().getString("from") + "|||" + myIntent.getExtras().getString("messgaebody")+"$|$"+myIntent.getExtras().getString("link"));

Enumeration vEnum = pendingVector.elements();
while (vEnum.hasMoreElements()) {
UiUtility.printMe(vEnum.nextElement());
}
}


@Override
public void onBackPressed() {
// TODO Auto-generated method stub

}


}



layout





HTTP Request


package com.sollet.buzz.utils;

import android.content.Context;
import android.net.ConnectivityManager;

import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Hashtable;
import java.util.Iterator;

public class HttpRequest {

/**
* Request Handler Here the Request is in JSON Format
*
* @param requestURL
* @param xmlRequest
* @return
*/
public Hashtable httpRequestJsonHandler(Context context,String requestURL, String xmlRequest) {

UiUtility.printMe("Inside HTTP Request Handler ");
UiUtility.printMe("ReqURL:" + requestURL);
UiUtility.printMe("XMLReq:" + xmlRequest);

Hashtable response_Ht = new Hashtable();
URL url = null;
HttpURLConnection urlConnection = null;
InputStream iStrm = null;
int reqResponsecode = 300;

if (requestURL == null || requestURL.equals("")) {
response_Ht.clear();
response_Ht.put("STATUS", "" + reqResponsecode);
response_Ht.put("REASON", "PASSED URL IS NULL");
return response_Ht;
}

try {

ConnectivityManager connec = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);

// ARE WE CONNECTED TO THE NET
if (connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTED
|| connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTED) {

UiUtility.printMe("is connected");

// String encodedUrl = URLEncoder.encode(requestURL, "UTF-8");

url = new URL(requestURL);
urlConnection = (HttpURLConnection) url.openConnection();

urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setUseCaches(false);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
if (xmlRequest != null) {

OutputStream out = new DataOutputStream(urlConnection.getOutputStream());
out.write(xmlRequest.getBytes());
out.flush();
out.close();

}

// get the response if respons code =200 it goes to loop
// otherwise
// returns response code
reqResponsecode = urlConnection.getResponseCode();
if (reqResponsecode == HttpURLConnection.HTTP_OK) {
iStrm = urlConnection.getInputStream();
int rsplength = (int) urlConnection.getContentLength();
if (rsplength == 0) {
response_Ht.clear();
response_Ht.put("STATUS", "300");
response_Ht.put("REASON",
"Server Exception : Response Length Zero");

} else {
try {

response_Ht.clear();
StringBuffer parsingSting = new StringBuffer();
int c = 0;
while (((c = iStrm.read()) != -1)) {

parsingSting.append((char) c);
}
JSONObject mainJson = new JSONObject(
parsingSting.toString());

Iterator keys = mainJson.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
String value = mainJson.getString(key);

if (key != null) {
key = key.toUpperCase();
}

response_Ht.put(key, value);
}
// END of pull Parser
} catch (Exception e) {
response_Ht.clear();
response_Ht.put("STATUS", "300");
response_Ht.put("REASON",
"JSON Parsing Error:" + e.getMessage());

}

}
} else if (reqResponsecode == 500) {
response_Ht.clear();
response_Ht.put("STATUS", "500");
response_Ht
.put("REASON",
"Server Response Message : Service Down \n Please Try Later");

} else if (reqResponsecode == 504) {
response_Ht.clear();
response_Ht.put("STATUS", "504");
response_Ht
.put("REASON",
"Server Response Message : Request Timed Out \n Please Try Later");

} else {
response_Ht.clear();
response_Ht.put("STATUS", "" + reqResponsecode);
response_Ht.put("REASON", "Server Response Message :"
+ urlConnection.getResponseMessage());

}

} else {
response_Ht.clear();
response_Ht.put("STATUS", "0110");
response_Ht.put("REASON",
"Please Switch On The INTERNET CONNECTION");

}
} catch (Exception e) {
response_Ht.clear();
response_Ht.put("STATUS", "" + reqResponsecode);
response_Ht.put("REASON", "Http Error :" + e.getMessage());

} finally {
try {
if (iStrm != null) {
iStrm.close();
}
if (urlConnection != null) {
urlConnection.disconnect();
}
} catch (Exception e) {
}
}

UiUtility.printMe("HTTP HashTable:" + response_Ht);
return response_Ht;
}

/**
* Request Handler :Here the Response is in XML Format
*
* @param requestURL
* @param xmlRequest
* @return
*/
public Hashtable httpRequestXMLHandler(Context context,
String requestURL, String xmlRequest) {

UiUtility.printMe("Inside HTTP Request Handler ");
UiUtility.printMe("ReqURL:" + requestURL);
UiUtility.printMe("XMLReq:" + xmlRequest);

Hashtable response_Ht = new Hashtable();
URL url = null;
HttpURLConnection urlConnection = null;
InputStream iStrm = null;
int reqResponsecode = 300;

if (requestURL == null || requestURL.equals("")) {
response_Ht.clear();
response_Ht.put("STATUS", "" + reqResponsecode);
response_Ht.put("REASON", "PASSED URL IS NULL");
return response_Ht;
}

try {

ConnectivityManager connec = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

// ARE WE CONNECTED TO THE NET
if (connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTED
|| connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTED) {

url = new URL(requestURL);
urlConnection = (HttpURLConnection) url.openConnection();

urlConnection.setUseCaches(false);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");

urlConnection.setDoInput(true);
// Allow Outputs
urlConnection.setDoOutput(true);
// Don't use a cached copy.
urlConnection.setUseCaches(false);

if (xmlRequest != null) {


OutputStream out = new DataOutputStream(urlConnection.getOutputStream());
out.write(xmlRequest.getBytes());
out.flush();
out.close();

}

// get the response if respons code =200 it goes to loop
// otherwise
// returns response code
reqResponsecode = urlConnection.getResponseCode();

if (reqResponsecode == HttpURLConnection.HTTP_OK) {
iStrm = urlConnection.getInputStream();
int rsplength = (int) urlConnection.getContentLength();
if (rsplength == 0) {
response_Ht.clear();
response_Ht.put("STATUS", "300");
response_Ht.put("REASON",
"Server Exception : Response Length Zero");

} else {
try {

response_Ht.clear();
XmlPullParserFactory factory = XmlPullParserFactory
.newInstance();
XmlPullParser parser = factory.newPullParser();
Reader iStrm_reader = new InputStreamReader(iStrm);
parser.setInput(iStrm_reader);
int eventType = parser.getEventType();
parser.nextTag();
// parser.require(XmlPullParser.START_TAG, null,
// "SUBK_GATEWAY");
while (eventType != XmlPullParser.END_DOCUMENT) {

String name = parser.getName();
if (eventType == XmlPullParser.START_TAG
&& name != null) {

String temp = parser.nextText();

if (name != null) {
name = name.toUpperCase();
}

if (temp == null) {

temp = "";
}

response_Ht.put(name.trim(), temp.trim());
UiUtility.printMe("Name:" + name.trim()
+ "|Value:" + temp.trim());
}

eventType = parser.next();

}

// END of pull Parser
} catch (Exception e) {
response_Ht.clear();
response_Ht.put("STATUS", "300");
response_Ht.put("REASON",
"Parsing Error:" + e.getMessage());

}

}
} else if (reqResponsecode == 500) {
response_Ht.clear();
response_Ht.put("STATUS", "500");
response_Ht
.put("REASON",
"Server Response Message : Service Down \n Please Try Later");

} else if (reqResponsecode == 504) {
response_Ht.clear();
response_Ht.put("STATUS", "504");
response_Ht
.put("REASON",
"Server Response Message : Request Timed Out \n Please Try Later");

} else {
response_Ht.clear();
response_Ht.put("STATUS", "" + reqResponsecode);
response_Ht.put("REASON", "Server Response Message :"
+ urlConnection.getResponseMessage());

}
} else {
response_Ht.clear();
response_Ht.put("STATUS", "0110");
response_Ht.put("REASON",
"Please Switch On The INTERNET CONNECTION");

}
} catch (Exception e) {
response_Ht.clear();
response_Ht.put("STATUS", "" + reqResponsecode);
response_Ht.put("REASON", "Http Error :" + e.getMessage());

} finally {
try {
if (iStrm != null) {
iStrm.close();
}
if (urlConnection != null) {
urlConnection.disconnect();
}
} catch (Exception e) {
}
}

UiUtility.printMe("HTTP HashTable:" + response_Ht);

return response_Ht;
}
}


GPS Tracker

package com.sollet.buzz.utils;

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;

public class GPSTracker extends Service implements LocationListener {

private Context mContext;

// Flag for GPS status
boolean isGPSEnabled = false;

// Flag for network status
boolean isNetworkEnabled = false;

// Flag for GPS status
boolean canGetLocation = false;

Location location; // Location
double latitude; // Latitude
double longitude; // Longitude

// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker() {

}
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}

public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);

// Getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);

// Getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

if (!isGPSEnabled && !isNetworkEnabled) {
// No network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// If GPS enabled, get latitude/longitude using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
}
catch (Exception e) {

}

return location;
}


/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app.
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}


/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}

// return latitude
return latitude;
}


/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}

// return longitude
return longitude;
}

/**
* Function to check GPS/Wi-Fi enabled
* @return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}


/**
* Function to show settings alert dialog.
* On pressing the Settings button it will launch Settings Options.
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

// Setting Dialog Title
alertDialog.setTitle("GPS is settings");

// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

// On pressing the Settings button.
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});

// On pressing the cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});

// Showing Alert Message
alertDialog.show();
}


@Override
public void onLocationChanged(Location location) {
}


@Override
public void onProviderDisabled(String provider) {
}


@Override
public void onProviderEnabled(String provider) {
}


@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}


@Override
public IBinder onBind(Intent arg0) {
return null;
}
}

DB Tables





CREATE TABLE USER_INFO(USERNAME TEXT NOT NULL,PASSWORD TEXT NOT NULL,NAME TEXT,SEX TEXT,DOB TEXT,STATUS TEXT,PICINFO TEXT);\n
CREATE TABLE HISTORY_MESSAGE(ID INTEGER PRIMARY KEY AUTOINCREMENT, MESSAGE TEXT NOT NULL, SENDER TEXT NOT NULL, LINKS TEXT NOT NULL, TIME TEXT NOT NULL, MYINFO TEXT); \n
CREATE TABLE USERCHAT_HISTORY_MESSAGE(ID INTEGER PRIMARY KEY AUTOINCREMENT, MESSAGE TEXT NOT NULL, SENDER_ID TEXT NOT NULL, RECIEVER_ID TEXT NOT NULL, LINKS TEXT NOT NULL, STATUS TEXT NOT NULL, DATETIME TEXT NOT NULL, MESSAGEID TEXT, MESSAGEDLVRY TEXT, FILETYPE TEXT, LOCALPATH TEXT, FILEUPLOADSTATUS TEXT);\n
CREATE TABLE USER_FRIENDS_LIST(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, USER_ID TEXT NOT NULL, STATUS_MESSAGE TEXT NOT NULL, DISPLAY_PIC TEXT NOT NULL,CONTACT_NUMBER TEXT,BUZZ_USER TEXT, IS_CHAT_AVAILABLE TEXT, IS_PHONE_CONTACT TEXT); \n
CREATE TABLE BLOCKED_USERS_LIST(ID INTEGER PRIMARY KEY AUTOINCREMENT, USER_ID TEXT NOT NULL, NAME TEXT, DISPLAY_PIC TEXT); \n





CREATE TABLE USERCHAT_HISTORY_MESSAGE(ID INTEGER PRIMARY KEY AUTOINCREMENT, MESSAGE TEXT NOT NULL, SENDER_ID TEXT NOT NULL, RECIEVER_ID TEXT NOT NULL, LINKS TEXT NOT NULL, STATUS TEXT NOT NULL, DATETIME TEXT NOT NULL);



ALTER TABLE USER_INFO ADD NAME TEXT;\n
ALTER TABLE USER_INFO ADD STATUS TEXT;\n
ALTER TABLE USER_INFO ADD PICINFO TEXT;\n
ALTER TABLE USERCHAT_HISTORY_MESSAGE ADD MESSAGEID TEXT;\n
ALTER TABLE USERCHAT_HISTORY_MESSAGE ADD MESSAGEDLVRY TEXT;\n
CREATE TABLE USER_FRIENDS_LIST(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, USER_ID TEXT NOT NULL, STATUS_MESSAGE TEXT NOT NULL, DISPLAY_PIC TEXT NOT NULL); \n
CREATE TABLE BLOCKED_USERS_LIST(ID INTEGER PRIMARY KEY AUTOINCREMENT, USER_ID TEXT NOT NULL); \n



ALTER TABLE HISTORY_MESSAGE ADD MYINFO TEXT;\n







ALTER TABLE USERCHAT_HISTORY_MESSAGE ADD FILETYPE TEXT;\n
ALTER TABLE USERCHAT_HISTORY_MESSAGE ADD LOCALPATH TEXT;\n
ALTER TABLE USERCHAT_HISTORY_MESSAGE ADD FILEUPLOADSTATUS TEXT;\n



ALTER TABLE BLOCKED_USERS_LIST ADD NAME TEXT;\n
ALTER TABLE BLOCKED_USERS_LIST ADD DISPLAY_PIC TEXT;


ALTER TABLE USER_INFO ADD SEX TEXT;\n
ALTER TABLE USER_INFO ADD DOB TEXT;\n
ALTER TABLE USER_FRIENDS_LIST ADD CONTACT_NUMBER TEXT;\n
ALTER TABLE USER_FRIENDS_LIST ADD BUZZ_USER TEXT;\n
ALTER TABLE USER_FRIENDS_LIST ADD IS_CHAT_AVAILABLE TEXT;\n
ALTER TABLE USER_FRIENDS_LIST ADD IS_PHONE_CONTACT TEXT;\n
DELETE FROM USER_FRIENDS_LIST;\n
DELETE FROM USER_INFO;\n





DB Handler


package com.sollet.buzz.database;


import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.sollet.buzz.main.R;

public class DBHelper extends SQLiteOpenHelper {
/*
* 7 - 2.8.5
* 8 - 2.8.6
*
* */
private static String DATABASE_NAME ="SOLLETDB";
private static int DATABASE_VERSION = 8; // by shyam date:7/7/2015 for release 2.8.6
private Context mContext;
private String LOG_TAG = "DATABASE_LOG";
public static DBHelper INSTANCE = null;

private DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.mContext = context;
}

/**
* Get Instance of DBHelper
*
* @param context
* @return
*/
public synchronized static DBHelper getInstanceDbHelper(Context context) {

if (INSTANCE == null) {
INSTANCE = new DBHelper(context);
}
return INSTANCE;
}

@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub

String[] sql = mContext.getString(R.string.Database_onCreate).split("\n");
db.beginTransaction();
try {
execMultipleSQL(db, sql);
// System.out.println("Db Tables Created..");
db.setTransactionSuccessful();
} catch (SQLException e) {
// Log.e("Error creating tables and debug data", e.toString());
// Log.v(LOG_TAG,e.toString());
throw e;
} finally {
db.endTransaction();
}

}

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

if(oldVersion<2) { db.beginTransaction(); try{ String sql = mContext.getString(R.string.Database_onUpgrade); db.execSQL(sql); // System.out.println("Db Tables Updated.."); db.setTransactionSuccessful(); } catch (Exception e) { } finally { db.endTransaction(); } }if(oldVersion<3){ String[] sql = mContext.getString(R.string.Database_onUpgrade_v3).split("\n"); db.beginTransaction(); try { execMultipleSQL(db, sql); db.setTransactionSuccessful(); } catch (Exception e) { } finally { db.endTransaction(); } } if(oldVersion<4){ String[] sql = mContext.getString(R.string.Database_onUpgrade_v4).split("\n"); db.beginTransaction(); try { execMultipleSQL(db, sql); db.setTransactionSuccessful(); } catch (Exception e) { } finally { db.endTransaction(); } } if(oldVersion<5){ String[] sql = mContext.getString(R.string.Database_onUpgrade_v5).split("\n"); db.beginTransaction(); try { execMultipleSQL(db, sql); db.setTransactionSuccessful(); } catch (Exception e) { } finally { db.endTransaction(); } } if(oldVersion<6){ String[] sql = mContext.getString(R.string.Database_onUpgrade_v6).split("\n"); db.beginTransaction(); try { execMultipleSQL(db, sql); db.setTransactionSuccessful(); } catch (Exception e) { } finally { db.endTransaction(); } } if(oldVersion<7){ String[] sql = mContext.getString(R.string.Database_onUpgrade_v7).split("\n"); db.beginTransaction(); try { execMultipleSQL(db, sql); db.setTransactionSuccessful(); } catch (Exception e) { } finally { db.endTransaction(); } } if(oldVersion<8){ String[] sql = mContext.getString(R.string.Database_onUpgrade_v8).split("\n"); db.beginTransaction(); try { execMultipleSQL(db, sql); db.setTransactionSuccessful(); } catch (Exception e) { } finally { db.endTransaction(); } } } /** * Execute all of the SQL statements in the String[] array * * @param db * The database on which to execute the statements * @param sql * An array of SQL statements to execute */ private void execMultipleSQL(SQLiteDatabase db, String[] sql) { for (String s : sql) if (s.trim().length() > 0){
// Log.v(LOG_TAG, s);
db.execSQL(s);
}
}

/**
* Execute the SQL statements to insert data
*
* @param sql
* An SQL statements to execute
*/
public void insert(String sql) {
getWritableDatabase().execSQL(sql);

// Log.v(LOG_TAG , sql);
}

/**
* Execute the SQL statements to update data
*
* @param sql
* An SQL statements to execute
*/
public void update(String sql) {
getWritableDatabase().execSQL(sql);
// Log.v(LOG_TAG, sql);
}

/**
* Execute the SQL statements to delete data
*
* @param sql
* An SQL statements to execute
*/
public void delete(String sql) {
getWritableDatabase().execSQL(sql);
// Log.v(LOG_TAG, sql);
}

}


Wednesday, 2 April 2014

Improve Performance of PhoneGap Application







PhoneGap when combined with jQuery Mobile sometimes exhibits sluggish performance. Overriding some css from Jquery can give you better performance in terms of page loading, page transitions etc. It may not give a 100% improvement but it will definitely improve your app by a great extent.


Add the following code in your css:


/* disable shadows for better android performance */
.ui-body-a,
.ui-bar-a,
.ui-btn-up-a,
.ui-btn-hover-a,
.ui-btn-down-a,

.ui-body-b,
.ui-bar-b,
.ui-btn-up-b,
.ui-btn-hover-b,
.ui-btn-down-b,

.ui-body-c,
.ui-bar-c,
.ui-btn-up-c,
.ui-btn-hover-c,
.ui-btn-down-c,

.ui-body-d,
.ui-bar-d,
.ui-btn-up-d,
.ui-btn-hover-d,
.ui-btn-down-d,

.ui-body-e,
.ui-bar-e,
.ui-btn-up-e,
.ui-btn-hover-e,
.ui-btn-down-e,

.ui-shadow-inset,
.ui-icon-shadow,
.ui-focus,
.ui-overlay-shadow,
.ui-shadow,
.ui-btn-active,
* {
text-shadow: none !important;
box-shadow: none !important;
-moz-box-shadow: none !important;
-webkit-box-shadow: none !important;
}


And add the following code in your onDeviceReady event function:


function onDeviceReady() {


// for performance boosting
$.mobile.autoInitializePage = false;
$.mobile.defaultPageTransition = 'none';
$.mobile.touchOverflowEnabled = false;
$.mobile.defaultDialogTransition = 'none';

}


Clear Application cache in android

There are two ways you can remove your application cache which piles up during the active state of application and free your device memory from running low on space.

1)One way you can delete cache on app exit using the following code.

@Override
    public void onDestroy() {
        super.onDestroy();

        try {
            trimCache(this);
           // Toast.makeText(this,"onDestroy " ,Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    public static void trimCache(Context context) {
        try {
           File dir = context.getCacheDir();
           if (dir != null && dir.isDirectory()) {
              deleteDir(dir);
           }
        } catch (Exception e) {
           // TODO: handle exception
        }
     }

     public static boolean deleteDir(File dir) {
        if (dir != null && dir.isDirectory()) {
           String[] children = dir.list();
           for (int i = 0; i < children.length; i++) {
              boolean success = deleteDir(new File(dir, children[i]));
              if (!success) {
                 return false;
              }
           }
        }

        // The directory is now empty so delete it
        return dir.delete();
     }


2)Another way to manage cache is to listen for the ACTION_DEVICE_STORAGE_LOW broadcast through a &ltreceiver>.