Tuesday, 4 February 2014

Google map

1)Create Activity ContactUsActivity.java
import android.os.Bundle;

import com.google.android.gms.common.GooglePlayServicesUtil;
import com.rws.ohmsantihyoga.R;
import com.rwsutil.masterview.MyBaseActivity;

public class ContactUsActivity extends MyBaseActivity {
private ContactContentFrag mContent;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("Contact Us");
setContentView(R.layout.base_layout);
hideMenuIcon();
GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getApplicationContext());
mContent = new ContactContentFrag();
getSupportFragmentManager().beginTransaction()
.replace(R.id.content_frame, mContent).commit();
getSlidingMenu().setSlidingEnabled(false);
}
}
2)ContactContentFrag.java
===================

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

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.rws.localwsutils.AppUtil;
import com.rws.ohmsantihyoga.R;
import com.rwsutil.masterview.GroupPrefrences.ContactPref;
import com.rwsutil.masterview.MyBaseFragment;
import com.rwsutil.masterview.WebServiceUrl;

public class ContactContentFrag extends MyBaseFragment implements
OnClickListener, WebServiceUrl, ContactPref {

private int contact_info_responcCode = 900;

private TextView txtTitle, txtAddress;
private Button abtMapType;
private EditText edtName, edtEmail, edtMessage;
private ImageView abtRefresh;
private CheckBox chkSendcopy;
private Button btnSubmit;
private GoogleMap mGooleMap;
private double mlat = 0;
private double mlng = 0;
private String mapTitle = "Ohm Santih", map_maptype = "";

@Override
public void onStop() {
putPref(ABT_NAME, edtName.getText().toString());
putPref(ABT_EMAIL, edtEmail.getText().toString());
putPref(ABT_MSG, edtMessage.getText().toString());
putPref(ABT_IS_CHECKED, chkSendcopy.isChecked());
super.onStop();
}

@Override
public void onStart() {
edtName.setText(getPrefString(ABT_NAME));
edtEmail.setText(getPrefString(ABT_EMAIL));
edtMessage.setText(getPrefString(ABT_MSG));
chkSendcopy.setChecked(getPrefBoolean(ABT_IS_CHECKED));
super.onStart();
}

private void clearPrefrenc() {
edtName.setText("");
edtEmail.setText("");
edtMessage.setText("");
chkSendcopy.setChecked(false);
putPref(ABT_NAME, "");
putPref(ABT_EMAIL, "");
putPref(ABT_MSG, "");
putPref(ABT_IS_CHECKED, false);
}

// [{"bStatus":"0","sMessage":"Contact Info fetch Successfully.","sData":{""
// +
// "contact_number":"9336 2556 (available from 9 am to 9 pm only)","" +
// "map_callout_text":"OhmSantih Yoga Pte Ltd\r\n",
// "title":" Ltd","" +
// "contactform_map_coords":"1.30065236072045, 103.85920733213425",
// "address":"10A, Ha<br \/>\r\nEmail us at : " +
// "enquiries@abc.com <br \/>\r\n",
// "contact_fax":"","map_maptype":"G_SATELLITE_MAP"}}]
//

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.contact_us_frag, null);

txtTitle = (TextView) v.findViewById(R.id.abtTitle);
Typeface font = Typeface.createFromAsset(getActivity().getAssets(),
"fonts/Chalet Comprime Cologne Sixty.otf");
txtTitle.setTypeface(font);
txtAddress = (TextView) v.findViewById(R.id.abtAddress);

abtMapType = (Button) v.findViewById(R.id.abtMapType);
abtMapType.setOnClickListener(this);

edtName = (EditText) v.findViewById(R.id.abtName);
observeText(edtName);
edtEmail = (EditText) v.findViewById(R.id.abtEmail);
observeText(edtEmail);
edtMessage = (EditText) v.findViewById(R.id.abtMessage);
observeText(edtMessage);

chkSendcopy = (CheckBox) v.findViewById(R.id.abtCheckMail);
abtRefresh = (ImageView) v.findViewById(R.id.abtRefresh);
abtRefresh.setOnClickListener(this);

btnSubmit = (Button) v.findViewById(R.id.abtSubmit);
btnSubmit.setOnClickListener(this);
mGooleMap = ((SupportMapFragment) getActivity()
.getSupportFragmentManager().findFragmentById(R.id.abtmapfragment)).getMap();
mGooleMap.setMyLocationEnabled(true);
CameraUpdate zoom = CameraUpdateFactory.zoomTo(15);
mGooleMap.animateCamera(zoom);
return v;
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
callWsPost(CONTACT_INFO_URL, new JSONObject(), contact_info_responcCode);
}

@Override
public void onResult(int mResponceCode, JSONArray mResponce) {
try {
JSONObject mJsonObject = mResponce.getJSONObject(0);
if (mResponceCode == contact_info_responcCode) {
onContactInfoResponce(mJsonObject);
} else if (mResponceCode == R.id.abtSubmit&& showMessage(mJsonObject)) 
clearPrefrenc();
}
} catch (Exception e) {
e.printStackTrace();
}
}

public void onContactInfoResponce(JSONObject mJsonObject) {
try {
JSONObject mData = mJsonObject.getJSONObject("sData");
txtTitle.setText(mapTitle = mData.getString("title"));
map_maptype = mData.getString("map_maptype");

String address = Html.fromHtml(mData.getString("address"))
.toString();
address += "Tel:" + mData.getString("contact_number");
txtAddress.setText(address + "\n");
// address = "\nemail : enquiries@ohmsantih.com";
txtAddress
.append(Html
.fromHtml("Email : <a href=\"enquiries@abc.com\">enquiries@abc.com</a>"));
txtAddress.setMovementMethod(LinkMovementMethod.getInstance());

String[] latlng = mData.getString("contactform_map_coords").split(
",");
mlat = Double.parseDouble(latlng[0]);
mlng = Double.parseDouble(latlng[1]);
refreshMap();
} catch (Exception e) {
e.printStackTrace();
parseError();
}
}

private void refreshMap() {
if (mlat != 0 && mlng != 0 && mGooleMap != null) {
CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(
mlat, mlng));
if (selectedType != -1)
mGooleMap.setMapType(selectedType);
else if (TextUtils.equals(map_maptype, "G_NORMAL_MAP"))
mGooleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
else if (TextUtils.equals(map_maptype, "G_SATELLITE_MAP"))
mGooleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
else if (TextUtils.equals(map_maptype, "G_HYBRID_MAP"))
mGooleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
else if (TextUtils.equals(map_maptype, "G_PHYSICAL_MAP"))
mGooleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
else
mGooleMap.setMapType(GoogleMap.MAP_TYPE_NONE);
mGooleMap.addMarker(new MarkerOptions().position(
new LatLng(mlat, mlng)).title(mapTitle));
mGooleMap.moveCamera(center);
CameraUpdate zoom = CameraUpdateFactory.zoomTo(15);
mGooleMap.animateCamera(zoom);
}
}

@Override
public void onResume() {
super.onResume();
clearPrefrenc();
}

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.abtSubmit:
JSONObject validResponce = getValidResponce();
if (validResponce != null) {
clearPrefrenc();
callWsPost(CONTACT_US_URL, validResponce, R.id.abtSubmit)
.setCacheEnable(false);
}
break;
case R.id.abtRefresh:
refreshMap();
break;
case R.id.abtMapType:
showMapTypeDaiog();
break;
}
}

private int selectedType = -1;

public void showMapTypeDaiog() {
// GoogleMap.MAP_TYPE_NONE,
final int[] mapType = new int[] { GoogleMap.MAP_TYPE_NORMAL,
GoogleMap.MAP_TYPE_SATELLITE, GoogleMap.MAP_TYPE_TERRAIN,
GoogleMap.MAP_TYPE_HYBRID, };
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Map Type").setItems(
// "None",
new String[] { "Normal", "Satellite", "Terrain", "Hybrid", },
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (mGooleMap != null)
mGooleMap.setMapType(selectedType = mapType[which]);
}
});
builder.create().show();
}

public JSONObject getValidResponce() {
String name = edtName.getText().toString();
String email = edtEmail.getText().toString();
String message = edtMessage.getText().toString();

if (TextUtils.isEmpty(name)) {
edtName.requestFocus();
edtName.setError("Please Enter Valid Name");
return null;
} else if (!AppUtil.isValidEmail(email)) {
edtEmail.requestFocus();
edtEmail.setError("Please Enter Valid Email");
return null;
} else if (TextUtils.isEmpty(message)) {
edtMessage.requestFocus();
edtMessage.setError("Please Enter Message");
return null;
} else {
JSONObject mJsonObject = new JSONObject();
try {
mJsonObject.put("name", name);
mJsonObject.put("email", email);
mJsonObject.put("message", message);
mJsonObject
.put("sendcopy", chkSendcopy.isChecked() ? "0" : "1");
return mJsonObject;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
}

public void clearData() {
edtName.setText("");
edtEmail.setText("");
edtMessage.setText("");
}
}
3)MyBaseFragment.java
=====================

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

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.Toast;

import com.rws.localwsutils.AppUtil;
import com.rws.wsutil.AsyncData;
import com.rws.wsutil.AsyncData.PostType;
import com.rws.wsutil.PostAndGetData;
import com.rws.wsutil.PostAndGetData.onJsonResult;

public abstract class MyBaseFragment extends AppPreferenceFrag implements
onJsonResult {

public abstract void onResult(int mResponceCode, JSONArray mResponce);

public AsyncData callWsPost(String BaseUrl, JSONObject mJsonData) {
return callWsPost(BaseUrl, mJsonData, (int) System.currentTimeMillis());
}

public AsyncData callWsPost(String BaseUrl, JSONObject mJsonData,
int responceCode) {
PostAndGetData mAndGetData = new PostAndGetData(getActivity(), this);
AsyncData mAsyncData = new AsyncData(PostType.POST, true, responceCode);
mAsyncData.setBASEURL(BaseUrl);
mAsyncData.setParams(mJsonData);
mAsyncData.setRootParam("webdata");
mAsyncData.setCacheEnable(true);
mAndGetData.execute(true, mAsyncData);
return mAsyncData;
}

public AsyncData callWsPost(String BaseUrl, JSONObject mJsonData,
onJsonResult onJsonResult) {
PostAndGetData mAndGetData = new PostAndGetData(getActivity(),
onJsonResult);
AsyncData mAsyncData = new AsyncData(PostType.POST, true);
mAsyncData.setBASEURL(BaseUrl);
mAsyncData.setParams(mJsonData);
mAsyncData.setRootParam("webdata");
mAsyncData.setCacheEnable(true);
mAndGetData.execute(true, mAsyncData);
return mAsyncData;

}

public boolean isSuccess(JSONObject mJsonObject) {
String message = "web responce error";
try {
message = mJsonObject.getString("sMessage");
if (mJsonObject.has("bStatus")
&& TextUtils.equals(mJsonObject.getString("bStatus"), "0")) {
return true;
} else
return alertMessage(message);
} catch (JSONException e) {
return alertMessage(message);
}
}

public boolean showMessage(JSONObject mJsonObject) {
String message = "web responce error";
try {
message = mJsonObject.getString("sMessage");
if (mJsonObject.has("bStatus")
&& TextUtils.equals(mJsonObject.getString("bStatus"), "0")) {
return !alertMessage(message);
} else
return alertMessage(message);
} catch (JSONException e) {
return alertMessage(message);
}
}

public boolean alertMessage(String message) {
AppUtil mAppUtil = AppUtil.getInstance();
mAppUtil.showAlertDialog(getActivity(), message);
return false;
}

public void parseError() {
Toast.makeText(getActivity(), "Responce Parse Error", Toast.LENGTH_LONG)
.show();
}

public void toast(String message){
Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show();
}

public void observeText(final EditText editText) {
editText.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
if (!editText.getText().toString().equals("")) {
editText.setError(null);
}
}

@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}

@Override
public void afterTextChanged(Editable s) {

}
});
}
}
4)AppPreferenceFrag.java
=====================

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;

public class AppPreferenceFrag extends Fragment {

private SharedPreferences preferences;

@Override
public void onCreate(Bundle arg0) {
super.onCreate(arg0);
preferences = getActivity().getSharedPreferences("AppPref",
Context.MODE_MULTI_PROCESS);
}

public void putPref(String KEY, String VAL) {
SharedPreferences.Editor editor = preferences.edit();
editor.putString(KEY, VAL);
editor.commit();
}

public void putPref(String KEY, int VAL) {
SharedPreferences.Editor editor = preferences.edit();
editor.putInt(KEY, VAL);
editor.commit();
}

public void putPref(String KEY, boolean VAL) {
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(KEY, VAL);
editor.commit();
}

public String getPrefString(String KEY) {
return preferences.getString(KEY, "");
}

public String getPrefString(String KEY, String _default) {
return preferences.getString(KEY, _default);
}

public int getPrefInt(String KEY) {
return preferences.getInt(KEY, 0);
}

public int getPrefInt(String KEY, int _default) {
return preferences.getInt(KEY, _default);
}

public boolean getPrefBoolean(String KEY) {
return preferences.getBoolean(KEY, false);
}

public boolean getPrefBoolean(String KEY, boolean _default) {
return preferences.getBoolean(KEY, _default);
}
}
6)base_layout.xml
=============
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/content_frame"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_marginTop="-4dp"
    android:background="@drawable/aboutus_bg" >

</FrameLayout>
7)contact_us_frag
===========
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@android:id/list"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/aboutus_bg"
    android:orientation="vertical"
    android:paddingBottom="8dp"
    android:paddingLeft="8dp"
    android:paddingRight="8dp" >

    <RelativeLayout
        android:id="@+id/mapLayour"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="0.4" >

        <fragment
            android:id="@+id/abtmapfragment"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            class="com.google.android.gms.maps.SupportMapFragment" />

        <ImageView
            android:id="@+id/abtRefresh"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_marginTop="7dp"
            android:background="@drawable/refresh_map"
            android:contentDescription="@string/app_name"
            android:singleLine="true"
            android:textColor="#945C44" />

        <Button
            android:id="@+id/abtMapType"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_below="@+id/abtRefresh"
            android:layout_marginBottom="30dp"
            android:layout_marginLeft="5dp"
            android:layout_marginTop="10dp"
            android:background="@drawable/mape_type"
            android:padding="4dp"
            android:text="@string/type" />
    </RelativeLayout>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_margin="@dimen/val_10"
        android:layout_weight="0.6" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            tools:ignore="UselessLeaf" >

            <TextView
                android:id="@+id/abtTitle"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="@color/brn_dark"
                android:textSize="@dimen/t_val_28"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/abtAddress"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:textColor="@color/brn_dark"
                android:textSize="18sp" />

            <EditText
                android:id="@+id/abtName"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="7dp"
                android:hint="@string/name"
                android:singleLine="true"
                android:textColor="@color/brn_dark" />

            <EditText
                android:id="@+id/abtEmail"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="7dp"
                android:hint="@string/email"
                android:inputType="textEmailAddress"
                android:singleLine="true"
                android:textColor="@color/brn_dark" />

            <EditText
                android:id="@+id/abtMessage"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_marginTop="7dp"
                android:gravity="bottom"
                android:hint="@string/message"
                android:inputType="textMultiLine"
                android:minLines="3"
                android:singleLine="false"
                android:textColor="@color/brn_dark"
                android:verticalScrollbarPosition="right" />

            <CheckBox
                android:id="@+id/abtCheckMail"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="7dp"
                android:checked="false"
                android:minLines="6"
                android:text="@string/send_a_copy_of_this_email_to_yourself"
                android:textColor="@color/brn_dark" />

            <Button
                android:id="@+id/abtSubmit"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:background="@drawable/submit_btn"
                android:padding="@dimen/val_10" />
        </LinearLayout>
    </ScrollView>

</LinearLayout>
9)MyBaseActivity.java
====================

import org.json.JSONArray;

import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.actionbarsherlock.app.ActionBar;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.rws.ohmsantihyoga.R;

public class MyBaseActivity extends MyBaseActivityWS implements OnClickListener {

private CharSequence title = "Title";

public void setTitle(CharSequence title) {
this.title = title;
if (txtTitle != null)
txtTitle.setText(title);
}
public TextView txtTitle;
public ImageView menuIcon, homeIcon;
public ImageView imgLeftDivider, imgRightDivider;

@Override
public void onCreate(Bundle arg0) {
super.onCreate(arg0);
setBehindContentView(R.layout.menu_frame);
getSlidingMenu().setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getActionBar().setCustomView(R.layout.headder);
getActionBar().setBackgroundDrawable(new ColorDrawable(R.color.brn_lite));
setSlidingActionBarEnabled(false);
SlidingMenu sm = getSlidingMenu();
sm.setBehindOffsetRes(R.dimen.slidingmenu_offset);
sm.setShadowWidthRes(R.dimen.shadow_width);
sm.setShadowDrawable(R.drawable.shadow);
sm.setBehindScrollScale(0.75f);
sm.setFadeDegree(0.25f);
sm.setBackgroundColor(getResources().getColor(R.color.brn_lite));
}

public void hideMenuIcon() {
menuIcon.setVisibility(View.INVISIBLE);
imgLeftDivider.setVisibility(View.INVISIBLE);
}

public void hideHomeIcon() {
homeIcon.setVisibility(View.INVISIBLE);
imgRightDivider.setVisibility(View.INVISIBLE);
}

@Override
public void setContentView(int id) {
super.setContentView(id);
txtTitle = (TextView) findViewById(R.id.headderTitle);
txtTitle.setText(title);

menuIcon = (ImageView) findViewById(R.id.iconMenu);
menuIcon.setOnClickListener(this);

homeIcon = (ImageView) findViewById(R.id.iconHome);
homeIcon.setOnClickListener(this);

imgLeftDivider = (ImageView) findViewById(R.id.imgLeftDivider);
imgRightDivider = (ImageView) findViewById(R.id.imgRightDivider);
}

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.iconMenu:
toggle();
break;
case R.id.iconHome:
finish();
break;
default:
break;
}
}

@Override
public void onResult(int mResponceCode, JSONArray mResponce) {
}
}

No comments:

Post a Comment