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
HashMap
AttractionsDTO selectedDto;
private Timer myTimer3;
MyApplication myapp ;
FragmentManager fm;
HashMap
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
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
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
MarkerOptions mopt ;
try{
mapMarkersList = new HashMap
for(int i=0;i
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);
}
}
}