Friday, 26 February 2016


MapFrag


package com.explorebeverlyhills.fragments;

import static com.explorebeverlyhills.database.ApplicationContext.getDBObject;

import java.io.ByteArrayInputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;











import com.explore.beverlyhills.R;
import com.explorebeverlyhills.common.CommonMethods;
import com.explorebeverlyhills.common.Constants;
import com.explorebeverlyhills.common.ProgressTask;
import com.explorebeverlyhills.dao.PedometerDAO;
import com.explorebeverlyhills.dto.AttractionsDTO;
import com.explorebeverlyhills.dto.LocationDTO;
import com.explorebeverlyhills.dto.MyApplication;
import com.explorebeverlyhills.gui.ExploreBeverlyHillsActivity;
import com.explorebeverlyhills.gui.ListScreenActivity;
import com.explorebeverlyhills.gui.WebViewActivity;
import com.explorebeverlyhills.handler.DownloadService;
import com.explorebeverlyhills.handler.RequestHandler;
import com.explorebeverlyhills.handler.UpdatePedometer;
import com.explorebeverlyhills.metaioar.ArView;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.BitmapFactory;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MapScreenFragment extends Fragment implements OnClickListener{
private static View view;
private GoogleMap googleMap;
private RelativeLayout pedoLayout,mapHolder;
private ImageView pedometerIcon,directViewIcon,tilesIcon,listIcon,pedoSwitchImage,bevHillsOnMoveImage;
private TextView pedoMilesText,bevOnMoveText;
private ArrayList attractionsList;
HashMap mapMarkersList;
AttractionsDTO selectedDto;
private Timer myTimer3;
MyApplication myapp ;
FragmentManager fm;
HashMap categoryPushPinList;
SharedPreferences sharedpreferences;
Marker mayorMarker;
private static int pedoRunningCounter = 0;
private Timer myTimer,mayorTimer;
String mayorAvailabilityFlag = "";
String POISelectedFlag = "";
double mayor_current_lat, mayor_current_long;
Context context;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
System.out.println("am in oncreateview...");
// if (view != null) {
// ViewGroup parent = (ViewGroup) view.getParent();
// if (parent != null)
// parent.removeView(view);
// }
try{
view = inflater.inflate(R.layout.map_screen_fragment, container, false);
pedoLayout = (RelativeLayout)view.findViewById(R.id.pedoLayout);
mapHolder = (RelativeLayout)view.findViewById(R.id.map_rel);
pedometerIcon = (ImageView)view.findViewById(R.id.pedometerIcon3);
directViewIcon = (ImageView)view.findViewById(R.id.directViewIcon3);
tilesIcon = (ImageView)view.findViewById(R.id.tilesIcon3);
listIcon = (ImageView)view.findViewById(R.id.listIcon3);
pedoSwitchImage = (ImageView)view.findViewById(R.id.pedoSwitch);
bevHillsOnMoveImage = (ImageView)view.findViewById(R.id.bevOnMoveImage);
pedoMilesText = (TextView)view.findViewById(R.id.pedometerMilesText);
bevOnMoveText = (TextView)view.findViewById(R.id.bevOnMoveText);
bevOnMoveText.setText(Constants.PEDOMETER_TEXT);
getActivity().findViewById(R.id.homeBtn).setVisibility(View.VISIBLE);
try{
mayorAvailabilityFlag = getArguments().getString("mayorAvailability");
}
catch(Exception e)
{
mayorAvailabilityFlag = "";
e.printStackTrace();
}
if(null != getArguments().getString("POISelected"))
{
POISelectedFlag = getArguments().getString("POISelected");
}
else
{
POISelectedFlag = "";
}

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

try {
initilizeMap();
googleMap.getUiSettings().setZoomControlsEnabled(false);
googleMap.setMyLocationEnabled(true);
pedometerIcon.setOnClickListener(this);
directViewIcon.setOnClickListener(this);
tilesIcon.setOnClickListener(this);
listIcon.setOnClickListener(this);
bevHillsOnMoveImage.setOnClickListener(this);
bevOnMoveText.setOnClickListener(this);
pedoSwitchImage.setOnClickListener(this);
} catch (Exception e) {
e.printStackTrace();

}

sharedpreferences = getActivity().getSharedPreferences(Constants.shared_preferences_name, Context.MODE_PRIVATE);

if (sharedpreferences.contains("pedometerStatus"))
{
String value = sharedpreferences.getString("pedometerStatus", "");
if(value.equalsIgnoreCase("yes"))
{
pedoSwitchImage.setImageResource(R.drawable.stop_pedo);
pedoRunningCounter = 1;
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
@Override
public void run() {
PedoMilesUpdateMethod();
}
}, 0, 5000);
}
else if(value.equalsIgnoreCase("no"))
{
pedoRunningCounter = 0;
pedoSwitchImage.setImageResource(R.drawable.start_pedo);
}

}
else
{
pedoRunningCounter = 0;
pedoSwitchImage.setImageResource(R.drawable.start_pedo);
}

return view;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
context = getActivity();
fm = ((ExploreBeverlyHillsActivity)context).getSupportFragmentManager();
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
System.out.println("am in activity created...");
myapp = (MyApplication) getActivity().getApplication();
selectedDto = myapp.getSelectedAttraction();
googleMap.clear();
myTimer3 = new Timer();
myTimer3.schedule(new TimerTask() {
@Override
public void run() {
TimerMethod3();
}
}, 0, 3000);






double lat2=0,long2=0;
if(null != POISelectedFlag && !POISelectedFlag.equals(""))
{
lat2 = selectedDto.getLatitude();
long2 = selectedDto.getLongitude();
if(null != mapMarkersList){
Marker clickedMarker = mapMarkersList.get(selectedDto.getId());

if(null != clickedMarker)
{
clickedMarker.showInfoWindow();
}
}
}
else
{
lat2 = Constants.city_hall_latitude;
long2 = Constants.city_hall_longitude;
}
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat2, long2), 15.0f));

attractionsList = myapp.getSearchResults();
if(null != mayorAvailabilityFlag && !mayorAvailabilityFlag.equals(""))
{
//show mayor marker in map
// if(mayorAvailabilityFlag.equalsIgnoreCase("True"))
// {

changeMayorMarkerPosition();

// }
}
}
@Override
public void onDestroyView() {
super.onDestroyView();
Fragment f = (Fragment)getFragmentManager().findFragmentById(R.id.mapshyam);
if (f != null)
{
try{
getFragmentManager().beginTransaction().remove(f).commit();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
@Override
public void onStop() {
super.onStop();
if(mayorTimer != null)
{
mayorTimer.cancel();
}
if(mayorMarker != null)
{
mayorMarker.remove();
}
}
public void changeMayorMarkerPosition()
{

if(mayorTimer == null)
{
mayorTimer = new Timer();
mayorTimer.schedule(new TimerTask() {
@Override
public void run() {
updateMayorLocation();
}
}, 0, 3000);
}
else
{
moveMapToLocation(mayor_current_lat,mayor_current_long,17.0f);
showMayorInfoWindow();
}

}
public void updateMayorLocation()
{
try{
getActivity().runOnUiThread(mayorLocation);
}
catch(Exception e)
{
e.printStackTrace();
}

}
private Runnable mayorLocation = new Runnable() {
public void run() {
mayor_current_lat = myapp.getMainActivityObject().mayor_latitude;
mayor_current_long = myapp.getMainActivityObject().mayor_longitude;

if(null != mayorMarker)
{
mayorMarker.remove();
}
MarkerOptions mopt = new MarkerOptions();
mopt.position(new LatLng(mayor_current_lat, mayor_current_long));
mopt.title("Mayor");
mopt.icon(BitmapDescriptorFactory.fromResource(R.drawable.mayor_location));
mayorMarker = googleMap.addMarker(mopt);

}
};
public void showMayorInfoWindow()
{
mayorMarker.showInfoWindow();
}
private void moveMapToLocation(double latitude,double longitude,float zoomlevel) {
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), zoomlevel));

}
@Override
public void onDestroy() {

super.onDestroy();
googleMap.clear();
if(categoryPushPinList != null)
{
// categoryPushPinList.clear();
// categoryPushPinList = null;
}
System.out.println("am in map destroy...............");
}



@Override
public void onClick(View v) {
int viewId = v.getId();

FragmentTransaction ft ;


//FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
switch(viewId)
{
case R.id.pedometerIcon3:
if(pedoLayout.getVisibility()==View.GONE)
{
pedoLayout.setVisibility(View.VISIBLE);
}
else{
pedoLayout.setVisibility(View.GONE);
}
break;
case R.id.directViewIcon3:
try{
SensorManager sensorMgr = (SensorManager)getActivity().getSystemService(getActivity().SENSOR_SERVICE);
Sensor sensorMag = null;
List sensors = sensorMgr.getSensorList(Sensor.TYPE_MAGNETIC_FIELD);
if (sensors.size() > 0) {
sensorMag = sensors.get(0);
}

if(sensorMag!=null){
ProgressTask.getInstance(getActivity()).execute(getActivity());

myapp.setSearchResults(attractionsList);
Intent getmsgIntent = new Intent(getActivity(), ArView.class);
startActivity(getmsgIntent);
}else{
CommonMethods.getToast("Direct View is not available", getActivity(), Toast.LENGTH_SHORT);
}
}
catch(Exception e)
{
e.printStackTrace();
}
break;
case R.id.tilesIcon3:
showLoading();

ft = fm.beginTransaction();
TilesScreenFragment tilesscreenFragment = new TilesScreenFragment();
ft.replace(R.id.total_frame_content, tilesscreenFragment);
ft.commit();
fm = null;
ft = null;
tilesscreenFragment = null;
break;
case R.id.listIcon3:
showLoading();

// ft = fm.beginTransaction();
// ListScreenFragment listscreenFragment = new ListScreenFragment();
//
// ft.replace(R.id.total_frame_content, listscreenFragment,Constants.LIST_FRAGMENT_TAG);
// ft.commit();
// fm = null;
// ft = null;
// listscreenFragment = null;

((ExploreBeverlyHillsActivity)context).finish();
Intent getmsgIntent = new Intent(getActivity(), ListScreenActivity.class);
startActivity(getmsgIntent);

break;
case R.id.pedoSwitch:
Intent serviceIntent = new Intent(getActivity(),UpdatePedometer.class);
if(pedoRunningCounter == 0) // pedometer is not running, so start it
{
pedoSwitchImage.setImageResource(R.drawable.stop_pedo);
pedoRunningCounter++;
pedoMilesText.setText(Html.fromHtml("PEDOMETER : 0.0 miles"));
UpdatePedometer.mContext = getActivity();
LocationDTO temp = new LocationDTO();
temp.setLatitude("0");
temp.setLongitude("0");
temp.setDistance(0);
PedometerDAO.getInstance().addLocataion(temp, getDBObject(1));
getActivity().startService(serviceIntent);
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
@Override
public void run() {
PedoMilesUpdateMethod();
}
}, 0, 5000);
}
else //pedometer is running, so stop it
{
pedoSwitchImage.setImageResource(R.drawable.start_pedo);
pedoRunningCounter--;
myTimer.cancel();
boolean flag = getActivity().stopService(serviceIntent);
Double distance = (double) PedometerDAO.getInstance().getDistance(getDBObject(0));
new SendPedometerMiles(distance).execute();
// System.out.println("service status:::"+flag);
}
break;
case R.id.bevOnMoveImage:
Intent in = new Intent(getActivity(),WebViewActivity.class);
in.putExtra("URL", Constants.BHONMOVE_URL);
startActivity(in);
break;
case R.id.bevOnMoveText:
Intent in1 = new Intent(getActivity(),WebViewActivity.class);
in1.putExtra("URL", Constants.BHONMOVE_URL);
startActivity(in1);
break;
}

}
private void showLoading()
{
LoadingFragment loadingFragment = new LoadingFragment();
// FragmentManager fm1 = getFragmentManager();
FragmentTransaction ft1 = fm.beginTransaction();
ft1.replace(R.id.total_frame_content, loadingFragment);
ft1.commit();

ft1 = null;
loadingFragment = null;
}
/**
* function to load map If map is not created it will create it for you
* */
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.mapshyam)).getMap();

// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getActivity().getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
}

protected void TimerMethod3() {
try{
getActivity().runOnUiThread(downloadPushPins);
}catch(Exception e)
{
e.printStackTrace();
}
}


private Runnable downloadPushPins = new Runnable() {
public void run() {
boolean downloadServiceFlag = isDownloadServiceRunning();
if(downloadServiceFlag)//service is running
{

}
else{//Intent service stopped running, then display markers on map.
// MyApplication myapp = (MyApplication) getApplication();
// categoryPushPinList = myapp.getCategoryPushPinResults();
myTimer3.cancel();
categoryPushPinList = getCategoryPushPins();
System.out.println("push pins size:::"+categoryPushPinList.size());

addMapMarkers(categoryPushPinList);
myTimer3.cancel();
}
}
};
private HashMap getCategoryPushPins() {
HashMap pushPinList = new HashMap();
SQLiteDatabase myDB = getActivity().openOrCreateDatabase(Constants.databaseName, SQLiteDatabase.OPEN_READWRITE, null);
String categoryIconsQuery = "SELECT ID, PushPinFile FROM MOBILEAPP_CATEGORIES;";
Cursor c1 = myDB.rawQuery(categoryIconsQuery, null);
try{
if (c1 != null && c1.getCount()>0) {
int Column1 = c1.getColumnIndex("PushPinFile");
int Column2 = c1.getColumnIndex("ID");
// Check if our result was valid.
c1.moveToFirst();
// Loop through all Results
do {
pushPinList.put(Integer.parseInt(c1.getString(Column2)),c1.getBlob(Column1));
} while (c1.moveToNext());
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally{
if (myDB != null)
myDB.close();
}
return pushPinList;
}
private void addMapMarkers(HashMap categoryPushPinList2) {
MarkerOptions mopt ;
try{
mapMarkersList = new HashMap();
for(int i=0;i0.0 miles"));
UpdatePedometer.mContext = getActivity();
LocationDTO temp = new LocationDTO();
temp.setLatitude("0");
temp.setLongitude("0");
temp.setDistance(0);
PedometerDAO.getInstance().addLocataion(temp, getDBObject(1));
getActivity().startService(serviceIntent);
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
@Override
public void run() {
PedoMilesUpdateMethod();
}
}, 0, 5000);
}
else //pedometer is running, so stop it
{
pedoSwitchImage.setImageResource(R.drawable.start_pedo);
pedoRunningCounter--;
myTimer.cancel();
boolean flag = getActivity().stopService(serviceIntent);
Double distance = (double) PedometerDAO.getInstance().getDistance(getDBObject(0));
new SendPedometerMiles(distance).execute();
// System.out.println("service status:::"+flag);
}
}
private void PedoMilesUpdateMethod()
{
//This method is called directly by the timer
//and runs in the same thread as the timer.

//We call the method that will work with the UI
//through the runOnUiThread method.
try{
((ExploreBeverlyHillsActivity)context).runOnUiThread(PedoMilesUpdater);
}
catch(Exception e)
{
e.printStackTrace();
}
}


private Runnable PedoMilesUpdater = new Runnable() {
public void run() {

Float distance = PedometerDAO.getInstance().getDistance(getDBObject(0));
pedoMilesText.setText(Html.fromHtml("PEDOMETER : "+new DecimalFormat("##.##").format(distance)+" miles"));
}
};
public class SendPedometerMiles extends AsyncTask
{
double distance;
public SendPedometerMiles(double distance) {
this.distance = distance;
}

@Override
protected Void doInBackground(Void... params) {
RequestHandler.sendPedometerMiles(distance);
return null;
}
@Override
protected void onPreExecute() {
super.onPreExecute();

}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);

}
}
}


DrawPathOn Map


package main.rodeo.com.rodeo.main;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import main.rodeo.com.rodeo.R;
import main.rodeo.com.rodeo.utils.DirectionsJSONParser;

@SuppressLint("NewApi")
public class DrawPathonMap extends Activity implements LocationListener,GoogleMap.OnMapLoadedCallback {

GoogleMap mGoogleMap;
ArrayList mMarkerPoints;
double mLatitude=0;
double mLongitude=0;
LatLng orgPoint = new LatLng(17.361452,78.386990);
LatLng destPoint = new LatLng(17.431563,78.488688 );

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

// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

if(status!= ConnectionResult.SUCCESS){ // Google Play Services are not available

int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();

}else { // Google Play Services are available

// Initializing
mMarkerPoints = new ArrayList();
mMarkerPoints.add(orgPoint);
mMarkerPoints.add(destPoint);
// Getting reference to SupportMapFragment of the activity_main
MapFragment mapFragment = ((MapFragment) getFragmentManager().findFragmentById(R.id.map));
mGoogleMap = mapFragment.getMap();

// Enable MyLocation Button in the Map
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.setOnMapLoadedCallback(this);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();

// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);

// Getting Current Location From GPS
Location location = locationManager.getLastKnownLocation(provider);

// if(location!=null){
// onLocationChanged(location);
//
// }

locationManager.requestLocationUpdates(provider, 20000, 0, this);

// Setting onclick event listener for the map
mGoogleMap.setOnMapClickListener(new OnMapClickListener() {

@Override
public void onMapClick(LatLng point) {

// Already map contain destination location
if(mMarkerPoints.size()>1){

// mMarkerPoints.clear();
// mGoogleMap.clear();
// LatLng startPoint = new LatLng(mLatitude, mLongitude);
//
// // draw the marker at the current position
// // drawMarker(startPoint);
// drawMarker(orgPoint);
}

// draws the marker at the currently touched location
// drawMarker(point);

// Checks, whether start and end locations are captured
if(mMarkerPoints.size() >= 2){
LatLng origin = mMarkerPoints.get(0);
LatLng dest = mMarkerPoints.get(1);

// Getting URL to the Google Directions API
String url = getDirectionsUrl(origin, dest);

DownloadTask downloadTask = new DownloadTask();

// Start downloading json data from Google Directions API
downloadTask.execute(url);
}
}
});
}
}

private String getDirectionsUrl(LatLng origin, LatLng dest){

// Origin of route
String str_origin = "origin="+origin.latitude+","+origin.longitude;

// Destination of route
String str_dest = "&destination="+dest.latitude+","+dest.longitude;

// Sensor enabled
String sensor = "&sensor=false";

// Building the parameters to the web service
String parameters = str_origin+str_dest+sensor;

// Output format
String output = "json";

// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/"+output+"?"+parameters;

return url;
}

/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException{
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try{
URL url = new URL(strUrl);

// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();

// Connecting to url
urlConnection.connect();

// Reading data from url
iStream = urlConnection.getInputStream();

BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

StringBuffer sb = new StringBuffer();

String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}

data = sb.toString();

br.close();

}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
urlConnection.disconnect();
}
return data;
}

@Override
public void onMapLoaded() {
if (mGoogleMap != null) {
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(orgPoint));
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(12));

drawMarker(orgPoint);
drawMarker(destPoint);

// Checks, whether start and end locations are captured
if(mMarkerPoints.size() >= 2){
LatLng origin = mMarkerPoints.get(0);
LatLng dest = mMarkerPoints.get(1);

// Getting URL to the Google Directions API
String url = getDirectionsUrl(origin, dest);

DownloadTask downloadTask = new DownloadTask();

// Start downloading json data from Google Directions API
downloadTask.execute(url);
}
}
}

/** A class to download data from Google Directions URL */
private class DownloadTask extends AsyncTask{

// Downloading data in non-ui thread
@Override
protected String doInBackground(String... url) {

// For storing data from web service
String data = "";

try{
// Fetching the data from web service
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}

// Executes in UI thread, after the execution of
// doInBackground()
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);

ParserTask parserTask = new ParserTask();

// Invokes the thread for parsing the JSON data
parserTask.execute(result);
}
}

/** A class to parse the Google Directions in JSON format */
private class ParserTask extends AsyncTask>> >{

// Parsing the data in non-ui thread
@Override
protected List>> doInBackground(String... jsonData) {

JSONObject jObject;
List>> routes = null;

try{
jObject = new JSONObject(jsonData[0]);
DirectionsJSONParser parser = new DirectionsJSONParser();

// Starts parsing data
routes = parser.parse(jObject);
}catch(Exception e){
e.printStackTrace();
}
return routes;
}

// Executes in UI thread, after the parsing process
@Override
protected void onPostExecute(List>> result) {
ArrayList points = null;
PolylineOptions lineOptions = null;

// Traversing through all the routes
for(int i=0;i();
lineOptions = new PolylineOptions();

// Fetching i-th route
List> path = result.get(i);

// Fetching all the points in i-th route
for(int j=0;j point = path.get(j);

double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);

points.add(position);
}

// Adding all the points in the route to LineOptions
lineOptions.addAll(points);
lineOptions.width(20);
if(i % 2 == 0)
lineOptions.color(Color.RED);
else
lineOptions.color(Color.BLUE);
}

// Drawing polyline in the Google Map for the i-th route
mGoogleMap.addPolyline(lineOptions);

}
}



private void drawMarker(LatLng point){
// mMarkerPoints.add(point);

// Creating MarkerOptions
MarkerOptions options = new MarkerOptions();

// Setting the position of the marker
options.position(point);

/**
* For the start location, the color of marker is GREEN and
* for the end location, the color of marker is RED.
*/
if(mMarkerPoints.size()==1){
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
}else if(mMarkerPoints.size()==2){
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
}

// Add new marker to the Google Map Android API V2
mGoogleMap.addMarker(options);
}

@Override
public void onLocationChanged(Location location) {
// Draw the marker, if destination location is not set
if(mMarkerPoints.size() < 2){ mLatitude = location.getLatitude(); mLongitude = location.getLongitude(); LatLng point = new LatLng(mLatitude, mLongitude); mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(point)); mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(12)); drawMarker(point); } } @Override public void onProviderDisabled(String provider) { // TODO Auto-generated method stub } @Override public void onProviderEnabled(String provider) { // TODO Auto-generated method stub } @Override public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } }


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


Tuesday, 12 March 2013

Triple Des Encryption In J2me


Enter your pages Title here




TripleDes.java



import org.bouncycastle.crypto.CryptoException;
import org.bouncycastle.crypto.engines.DESedeEngine;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.bouncycastle.crypto.params.KeyParameter;

/**
 *
 * @author Pradeep
 */
public class TripleDes {

    PaddedBufferedBlockCipher encryptCipher;
    PaddedBufferedBlockCipher decryptCipher;
    // Buffers used to transport the bytes from one stream to another
    byte[] key = null;              //secret key for secure encryption and decryption
 
     public TripleDes() {
     
        key = "MYTESTTRIPLEDESENCRYPTO".getBytes();
        // calling the InitCiphers() method to initilize the PaddedBufferedBlockCipher
        InitCiphers();
    }

 
    /**
     *
     * @param keyBytes      Key value
     */
    public TripleDes(byte[] keyBytes) {
        // TripleDES Key
        key = new byte[keyBytes.length];
        System.arraycopy(keyBytes, 0, key, 0, keyBytes.length);
        // calling the InitCiphers() method to initilize the PaddedBufferedBlockCipher
        InitCiphers();
    }
   /**
     *
     * Encrypt
     *
     * This method encrypt the plain text and returns the encrypted data in base64
     *
     * @param plainText
     * @return String
     * @throws Exception
     */
    public String encrypt(String plainText) throws Exception {

        byte[] input = plainText.getBytes();
        encryptCipher.init(true, new KeyParameter(key));
        byte[] cipherText = new byte[encryptCipher.getOutputSize(input.length)];
        int outputLen = encryptCipher.processBytes(input, 0, input.length, cipherText, 0);

        try {
            encryptCipher.doFinal(cipherText, outputLen);
        } catch (CryptoException ce) {          
            System.err.println(ce);
            throw new Exception(ce.toString());          
        } catch (Exception ce) {          
            System.err.println(ce);
            throw new Exception(ce.toString());          
        } finally {
           ResetCiphers();
        }
        return new String(Base64Coder.encode(cipherText)).trim();
    }
 
    /**
     * decrypt
     * Decrypt the encrypted string
     * @param enctryptedText
     * @return
     * @throws Exception
     */
    public String decrypt(String enctryptedText) throws Exception {

        byte[] input = Base64Coder.decode(enctryptedText);
        decryptCipher.init(false, new KeyParameter(key));
        byte[] cipherText = new byte[decryptCipher.getOutputSize(input.length)];
        int outputLen = decryptCipher.processBytes(input, 0, input.length, cipherText, 0);
        try {
            decryptCipher.doFinal(cipherText, outputLen);
        } catch (CryptoException ce) {          
            System.err.println(ce);
            throw new Exception(ce.toString());          
        } catch (Exception ce) {          
            System.err.println(ce);
            throw new Exception(ce.toString());          
        } finally {
           ResetCiphers();
        }
        return bytes2String(cipherText);
    }
 
    /**
     * Initilize the ciphers for encryption and decryption
     *
     */
    private void InitCiphers() {
        //Creates encryptCipher Object  DESEDE
        encryptCipher = new PaddedBufferedBlockCipher(new DESedeEngine());
     
//        encryptCipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new DESedeEngine()));  //  DESEDE CBC MODE CIPHER
        //set Key parameters and Encrypt mode
        encryptCipher.init(true, new KeyParameter(key));
        //Creates decryptCipher Object
        decryptCipher = new PaddedBufferedBlockCipher(new DESedeEngine());
     
//        decryptCipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new DESedeEngine()));  //  DESEDE CBC MODE CIPHER
        //set Key parameters and Encrypt mode
        decryptCipher.init(false, new KeyParameter(key));
    }
 
    /**
     * Reset the cipher Objects
     */
    private void ResetCiphers() {
        if (encryptCipher != null) {
            encryptCipher.reset();
        }
        if (decryptCipher != null) {
            decryptCipher.reset();
        }
    }
 
    /**
     * bytes2String
     * convert byte array to string
     * @param bytes
     * @return
     */
    private static String bytes2String(byte[] bytes) {
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            stringBuffer.append((char) bytes[i]);
        }
        return stringBuffer.toString();
    }
}





Note:Triple Des (DESede) Encryption in J2me


Source code Download Link

Tuesday, 27 November 2012

Select Image from gallery and display in lwuit Form

HelloMidlet.java
-----------------------
package main;

/*
 * To change this template, choose Tools | Templates and open the template in
 * the editor.
 */

import com.sun.lwuit.*;
import javax.microedition.midlet.MIDlet;

public class HelloMidlet extends MIDlet {

    public static int dwidth;
    public static int dheight;
    public static javax.microedition.lcdui.Display lcduiDisplay;
    public static HelloMidlet midlet;
   
    public void startApp() {
        try {
            midlet = this;
            Display.init(this);
            lcduiDisplay = javax.microedition.lcdui.Display.getDisplay(this);
         
            dwidth = Display.getInstance().getDisplayWidth();
            dheight = Display.getInstance().getDisplayHeight();

            } catch (Exception ex) {
        }
        ImageClass imgform = new ImageClass();
        imgform.showLcduiImageForm(null);
    }
    public void pauseApp() {
    }
    public void destroyApp(boolean unconditional) {
    }
}


ImageClass.java
-------------------
package main;
import com.sun.lwuit.*;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.layouts.BoxLayout;

/*
 * To change this template, choose Tools | Templates and open the template in
 * the editor.
 */

public class ImageClass {
    public static Form imgForm;

    public void showLcduiImageForm(Object img) {
        try {
//            Display.init(HelloMidlet.midlet);
            imgForm = new Form("Hello World");

            Container middleContainer = new Container();
            middleContainer.setLayout(new BoxLayout(BoxLayout.Y_AXIS));
            middleContainer.setUIID("middleContainer");
            middleContainer.setScrollableY(true);
            middleContainer.getStyle().setBgColor(0XDEDBDE);
            //

            Label empty2 = new Label("");
            empty2.setFocusable(true);
            middleContainer.addComponent(empty2);

            Button browse = new Button("browse");
            browse.setUIID("actionButton");
            browse.setHeight(25);
            browse.setAlignment(Button.CENTER);
            browse.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent ae) {
                    ImgBrowser browser = new ImgBrowser();
                    browser.browseForImage(HelloMidlet.midlet);
                }
            });

            Container cp_details = new Container(new BoxLayout(BoxLayout.X_AXIS));
            Image img1 = null;
            try {
                img1 = Image.createImage(img);               
                Label l1 = new Label(img1.scaled(30, 30));
                cp_details.addComponent(l1);
            } catch (Exception ex) {
              //  Dialog.show("Error", "Error creating Image from lcdui", "OK", null);
            }

            cp_details.addComponent(browse);
            middleContainer.addComponent(cp_details);

            imgForm.addComponent(middleContainer);
            imgForm.show();
        } catch (Exception ex) {
            Dialog.show("Exception", "" + ex.getMessage(), "OK", null);
        }

    }
}


ImgBrowser.java
--------------------
package main;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.io.file.FileSystemRegistry;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;

/*
 * To change this template, choose Tools | Templates and open the template in
 * the editor.
 */

public class ImgBrowser implements CommandListener {

    private Image dirIcon;
    private Image fileIcon;
    private Image[] iconList;
    private String currDirName;
    /*
     * separator string as defined by FC specification
     */
    private static final String SEP_STR = "/";

    /*
     * separator character as defined by FC specification
     */
    private static final char SEP = '/';
    /*
     * special string that denotes upper directory accessible by this browser.
     * this virtual directory contains all roots.
     */
    private static final String MEGA_ROOT = "/";
    /*
     * special string denotes upper directory
     */
    private static final String UP_DIRECTORY = "..";
    private Command view = new Command("Select", Command.ITEM, 1);
    private Command cancel = new Command("Cancel", Command.ITEM, 2);
    private Command back = new Command("Back", Command.BACK, 2);
    MIDlet midletObj;

    public ImgBrowser() {
        currDirName = MEGA_ROOT;

        try {
            dirIcon = Image.createImage("/dir.png");
        } catch (IOException e) {
            dirIcon = null;
        }

        try {
            fileIcon = Image.createImage("/file.png");
        } catch (IOException e) {
            fileIcon = null;
        }

        iconList = new Image[]{fileIcon, dirIcon};
    }

    public void browseForImage(MIDlet midlet) {
        midletObj = midlet;
        try {
            showCurrDir();
        } catch (SecurityException e) {
            Alert alert =
                    new Alert("Error", "You are not authorized to access the restricted API", null,
                    AlertType.ERROR);
            alert.setTimeout(Alert.FOREVER);

            Form form = new Form("Cannot access FileConnection");
            form.append(new StringItem(null,
                    "You cannot run this MIDlet with the current permissions. "
                    + "Sign the MIDlet suite, or run it in a different security domain"));
//            form.addCommand(exit);
//            form.setCommandListener(this);
            Display.getDisplay(midletObj).setCurrent(alert, form);
        } catch (Exception e) {
        }
    }

    /**
     * Show file list in the current directory .
     */
    void showCurrDir() {
        Enumeration e;
        FileConnection currDir = null;
        List browser;

        try {
            if (MEGA_ROOT.equals(currDirName)) {
                e = FileSystemRegistry.listRoots();
                browser = new List(currDirName, List.IMPLICIT);
            } else {
                currDir = (FileConnection) Connector.open("file://localhost/" + currDirName);
                e = currDir.list();
                browser = new List(currDirName, List.IMPLICIT);
                // not root - draw UP_DIRECTORY
                browser.append(UP_DIRECTORY, dirIcon);
            }

            while (e.hasMoreElements()) {
                String fileName = (String) e.nextElement();

                if (fileName.charAt(fileName.length() - 1) == SEP) {
                    // This is directory
                    browser.append(fileName, dirIcon);
                } else {
                    // this is regular file
                    browser.append(fileName, fileIcon);
                }
            }

            browser.setSelectCommand(view);
            browser.addCommand(cancel);

            //Do not allow creating files/directories beside root
            if (!MEGA_ROOT.equals(currDirName)) {
//                browser.addCommand(prop);
//                browser.addCommand(creat);
//                browser.addCommand(delete);
            }

//            browser.addCommand(exit);
//
            browser.setCommandListener(this);

            if (currDir != null) {
                currDir.close();
            }

            Display.getDisplay(midletObj).setCurrent(browser);
        } catch (IOException ioe) {
        }
    }

    public void commandAction(Command c, Displayable d) {
        if (c == view) {
            List curr = (List) d;
            final String currFile = curr.getString(curr.getSelectedIndex());
            new Thread(new Runnable() {

                public void run() {
                    if (currFile.endsWith(SEP_STR) || currFile.equals(UP_DIRECTORY)) {
                        traverseDirectory(currFile);
                    } else {
                        // Show file contents
                        showFile(currFile);
                    }
                }
            }).start();
        } else if (c == back) {
            showCurrDir();
        }
        else if (c == cancel) {
            com.sun.lwuit.Display.init(midletObj);
            ImageClass.imgForm.show();
        }
    }

    void traverseDirectory(String fileName) {
        /*
         * In case of directory just change the current directory and show it
         */
        if (currDirName.equals(MEGA_ROOT)) {
            if (fileName.equals(UP_DIRECTORY)) {
                // can not go up from MEGA_ROOT
                return;
            }

            currDirName = fileName;
        } else if (fileName.equals(UP_DIRECTORY)) {
            // Go up one directory
            int i = currDirName.lastIndexOf(SEP, currDirName.length() - 2);

            if (i != -1) {
                currDirName = currDirName.substring(0, i + 1);
            } else {
                currDirName = MEGA_ROOT;
            }
        } else {
            currDirName = currDirName + fileName;
        }

        showCurrDir();
    }

    void showFile(String fileName) {
//        Form mForm = new Form("Image");
        FileConnection fc = null;
        DataInputStream in = null;
        DataOutputStream out = null;
        try {
            fc = (FileConnection) Connector.open("file://localhost/" + currDirName + fileName);
            int length = (int) fc.fileSize();//possible loss of precision may throw error
            byte[] data = null;
            if (length != -1) {
                data = new byte[length];
                in = new DataInputStream(fc.openInputStream());
                in.readFully(data);
            } else {
                int chunkSize = 512;
                int index = 0;
                int readLength = 0;
                in = new DataInputStream(fc.openInputStream());
                data = new byte[chunkSize];
                do {
                    if (data.length < index + chunkSize) {
                        byte[] newData = new byte[index + chunkSize];
                        System.arraycopy(data, 0, newData, 0, data.length);
                        data = newData;
                    }
                    readLength = in.read(data, index, chunkSize);
                    index += readLength;
                } while (readLength == chunkSize);
                length = index;
            }
            Image image = Image.createImage(data, 0, length);
            ImageItem imageItem = new ImageItem(null, image, 0, null);
            com.sun.lwuit.Display.init(midletObj);
            ImageClass imgForm=new ImageClass();
            imgForm.showLcduiImageForm(image);
//            mForm.append(imageItem);
//            mForm.setTitle("Done.");
//            mForm.addCommand(select);
//            mForm.addCommand(back);
//            mForm.setCommandListener(this);

            //fc = (FileConnection) Connector.open("file:///root1/x.PNG");
            if (!fc.exists()) {
                try {
                    fc.create();
                } catch (Exception ce) {
                    System.out.print("Create Error: " + ce);
                }
            }
            out = new DataOutputStream(fc.openOutputStream());
            out.write(data);
        } catch (IOException ioe) {
            StringItem stringItem = new StringItem(null, ioe.toString());
//            mForm.append(stringItem);
//            mForm.addCommand(back);
//            mForm.setCommandListener(this);
//            mForm.setTitle("Done.");
            com.sun.lwuit.Display.init(midletObj);
            ImageClass.imgForm.show();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (fc != null) {
                    fc.close();
                }
            } catch (IOException ioe) {
            }
        }
//        StringItem stringItem = new StringItem(null, "\nfile://localhost/" + currDirName + fileName);
//        mForm.append(stringItem);
//        Display.getDisplay(midletObj).setCurrent(mForm);
    }
}


icons:
-----------
file.png


dir.png