I think I have done all using the Google Maps API v2 but the position is not shown and the camera doesn't changes its position.
The map loads normally but stays only in 0,0 location and it never moves.
In the device, I see the GPS signal only looking for position and I have already tested outside.
Here is my code:
MainActivity.java:
public class MainActivity extends FragmentActivity implements LocationSource,LocationListener, OnMapClickListener, OnMyLocationChangeListener
{
final int RQS_GooglePlayServices = 1;
private GoogleMap myMap;
private LocationManager lm;
public Location myLocation;
public TipoBusca busca;
private enum TipoBusca {BUSCA_PARADA, BUSCA_LOCALIZACAO_INICIAL, BUSCA_LOCALIZACAO, BUSCA_ENDERECO, BUSCA_DRAG};
public String tipoRequest;
private Criteria myCriteria;
public TextView textView;
public OnMyLocationChangeListener locationListener;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Define textView wich will receive test messages
textView = (TextView) findViewById(R.id.textView1);
// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
// Showing status
if(status!=ConnectionResult.SUCCESS)
{ // Google Play Services are not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();
}
else
{
//Defining fragment for map
FragmentManager myFragmentManager = getSupportFragmentManager();
SupportMapFragment mySupportMapFragment = (SupportMapFragment)myFragmentManager.findFragmentById(R.id.map);
myMap = mySupportMapFragment.getMap();
myMap.setMyLocationEnabled(true);
myMap.setIndoorEnabled(true);
myMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
myMap.setLocationSource(this);
//myMap.setOnMyLocationChangeListener(this);
myMap.setOnMyLocationChangeListener((OnMyLocationChangeListener) locationListener);
myCriteria = new Criteria();
myCriteria.setAccuracy(Criteria.ACCURACY_FINE);
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
//lm.requestLocationUpdates(0, 50.0f, myCriteria, this, null);
lm.requestLocationUpdates(250, 1, myCriteria, this, null);
textView.setText("Localizando usuário...");
myLocation = myMap.getMyLocation();
}
}
#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
}
#Override
public void activate(OnLocationChangedListener listener) {
// TODO Auto-generated method stub
}
#Override
public void deactivate() {
// TODO Auto-generated method stub
}
#Override
public void onMapClick(LatLng point) {
// TODO Auto-generated method stub
myMap.animateCamera(CameraUpdateFactory.newLatLng(point));
}
#Override
public void onMyLocationChange(Location location) {
// TODO Auto-generated method stub
Log.i("onMyLocationChanged", "my location changed");
LatLng latlng= new LatLng(location.getLatitude(), location.getLongitude());
myMap.moveCamera(CameraUpdateFactory.newLatLng(latlng));
myMap.animateCamera(CameraUpdateFactory.zoomTo(15));
textView.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude() );
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Log.i("onLocationChanged", "location changed");
}
}
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="myPackage"
android:versionCode="1"
android:versionName="1.0" >
<!-- Setting Permissions -->
<permission
android:name="myPackage.permission.MAPS_RECEIVE" android:protectionLevel="signature"></permission>
<uses-permission android:name="myPackage.permission.MAPS_RECEIVE"/>
<!-- Setting versions requirements -->
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<!-- External storage for caching. -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<!-- My Location -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<!-- Maps API needs OpenGL ES 2.0. -->
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<!-- setting icon for application -->
<application android:allowBackup="true" android:icon="#drawable/ic_launcher" android:label="#string/app_name" android:theme="#android:style/Theme.NoTitleBar" >
<meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="myApiKey_Code_Inserted_here"/>
<activity android:name="myPackage.MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
If what you're trying to accomplish is to have the camera automatically update when the user (My Location dot) changes location, then you only need the following:
implement OnMyLocationChangeListener
myMap.setMyLocationEnabled(true) (enable the my-location layer, which has a built-in location provider)
myMap.setOnMyLocationChangeListener(this) (register to receive updates when My Location dot changes location)
in your callback method onMyLocationChange(Location location) update the camera accordingly.
You already have the code for all of this, but I see you have commented the line in step 3, and this is probably the reason why you don't see the camera updating.
You don't need to implement LocationSource and LocationListener (because the my-location layer has its own location provider), and you need OnMapClickListener only if you want to respond to a user tapping on a point on the map.
Related
I am trying to make my program able to get the user's current longitude and latitude and then place a marker to it. I have used various method in the Internet but none of them seemed to work. From what I have observed I suspect the reason the trouble is that the program fails to get the permission, despite I have already set it in the manifest
Here is the code, I currently only use setMyLocationEnabled to demonstrate the problem
package com.example.user.googlemaptest2;
import android.*;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.IOException;
import java.util.List;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private double longitudeDefaultLocation;
private double latitudeDefaultLocation;
private static final int MY_PERMISSION_ACCESS_COARSE_LOCATION = 11;
private static final int MY_PERMISSION_ACCESS_FINE_LOCATION = 12;
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
longitudeDefaultLocation = location.getLongitude();
latitudeDefaultLocation = location.getLatitude();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions( this, new String[] { android.Manifest.permission.ACCESS_COARSE_LOCATION },
MapsActivity.MY_PERMISSION_ACCESS_COARSE_LOCATION );
ActivityCompat.requestPermissions( this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION },
MapsActivity.MY_PERMISSION_ACCESS_FINE_LOCATION );
}
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
mMap.animateCamera(CameraUpdateFactory.zoomTo(14));
}
else
{
Toast.makeText(MapsActivity.this,"FAIL", Toast.LENGTH_LONG).show();
}
}
public void onSearch(View view)
{
EditText location_tf = (EditText)findViewById(R.id.TFaddress);
String location = location_tf.getText().toString();
List<Address> addressList = null;
if (location !=null || location.equals("")) {
Geocoder geocoder = new Geocoder(this);
try {
addressList = geocoder.getFromLocationName(location,1);
} catch (IOException e) {
e.printStackTrace();
}
Address address = addressList.get(0);
LatLng latLng = new LatLng( address.getLatitude(), address.getLongitude());
mMap.addMarker(new MarkerOptions().position(latLng).title("Marker"));
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
}
}
public void changeType (View view)
{
if (mMap.getMapType() == GoogleMap.MAP_TYPE_NORMAL)
{
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
}
else
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
public void onZoom(View view)
{
if (view.getId() == R.id.zoomInButton);
{
mMap.animateCamera(CameraUpdateFactory.zoomIn());
}
if (view.getId() == R.id.zoomOutButton)
{
mMap.animateCamera(CameraUpdateFactory.zoomOut());
}
}
This is the content of my Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.user.googlemaptest2">
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="My Key is Here" />
<activity
android:name=".MapsActivity"
android:label="#string/title_activity_maps">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Alas! after a lots of efforts and search I couldn't find my problem. I want to find current location in google map but I am still getting an error(required permissions).
call requires permission which may be rejected by user: code should
explicitly check to see if permission is available (with check
permission) or explicitly handle a potential 'security Exception'
at gMap.setMyLocationEnable(true); Please anybody guide me how can I fix it? My code is given below.
AddMasjid.java
package com.example.saroosh.masjidnow.Tabs;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.saroosh.masjidnow.R;
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.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class AddMasjid extends Fragment implements OnMapReadyCallback{
MapView gMapView;
GoogleMap gMap = null;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v =inflater.inflate(R.layout.add_masjid,container,false);
gMapView = (MapView) v.findViewById(R.id.map);
gMapView.getMapAsync(this);
gMapView.onCreate(savedInstanceState);
gMapView.onResume(); // needed to get the map to display immediately
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
return v;
}
#Override
public void onMapReady(GoogleMap map) {
gMap = map;
gMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
gMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new
LatLng(0, 0), 0));
if (gMap != null) {
gMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
gMap.setMyLocationEnabled();
}
}
#Override
public void onResume() {
super.onResume();
gMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
gMapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
gMapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
gMapView.onLowMemory();
}
}
add_masjid.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#000000">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/editText1"
android:layout_alignBottom="#+id/editText1"
android:layout_alignParentStart="true"
android:text="#string/xyz"
android:textColor="#FFFFFF"
android:textSize="20sp"
/>
<Button
android:id="#+id/generalId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:background="#drawable/rect1"
android:onClick="geoLocate"
android:text="#string/abc"
android:textColor="#FFFFFF"
android:textSize="20sp" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="#+id/textView1"
android:layout_toStartOf="#+id/generalId"
android:ems="10"
android:inputType="text"
android:background="#FFFFFF"
android:labelFor="#+id/editText1"
android:layout_above="#+id/map"
android:layout_alignParentTop="true" />
<com.google.android.gms.maps.MapView
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/generalId">
</com.google.android.gms.maps.MapView>
</RelativeLayout>
I have just solved my problem by adding some permissions in it.
#Override
public void onMapReady(GoogleMap map) {
gMap = map;
gMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
gMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new
LatLng(0, 0), 0));
//add this code...
if (gMap != null) {
gMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
if (ActivityCompat.checkSelfPermission(getActivity().getApplicationContext()
, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity().getApplicationContext()
, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
gMap.setMyLocationEnabled(true);
gMap.getUiSettings().setMyLocationButtonEnabled(true);
}
}
I don't see any thing on google map,lines type some is shown,
my first map view project is running successfully where only map is show and here when i add some more code as the tutorial goes on it is not working ..
here is the
public class MainActivity extends FragmentActivity {
private static final int GPS_ERRORDIALOG_REQUEST = 9001;
GoogleMap mMap;
#SuppressWarnings("unused")
private static final double SEATTLE_LAT = 47.60621,
SEATTLE_LNG = -122.33207, SYDNEY_LAT = -33.867487,
SYDNEY_LNG = 151.20699, NEWYORK_LAT = 40.714353,
NEWYORK_LNG = -74.005973;
private static final float DEFAULTZOOM = 5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (servicesOK()) {
setContentView(R.layout.activity_main);
if (initMap()) {
Toast.makeText(this, "Ready to map !", Toast.LENGTH_LONG)
.show();
gotoLocation(SEATTLE_LAT, SEATTLE_LNG, DEFAULTZOOM);
} else {
Toast.makeText(this, "Ready to map !", Toast.LENGTH_LONG)
.show();
}
} else {
setContentView(R.layout.activity_map_xml_control);
}
}
private void gotoLocation(double lat, double lng,
float zoom) {
LatLng ll = new LatLng(lat, lng);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll, zoom);
mMap.moveCamera(update);
}
public boolean servicesOK() {
int isAvailable = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this);
if (isAvailable == ConnectionResult.SUCCESS) {
return true;
} else if (GooglePlayServicesUtil.isUserRecoverableError(isAvailable)) {
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(isAvailable,
this, GPS_ERRORDIALOG_REQUEST);
dialog.show();
} else {
Toast.makeText(this, "Can't connect to Google play servieces",
Toast.LENGTH_LONG).show();
}
return false;
}
private boolean initMap() {
if (mMap == null) {
// setContentView(R.layout.activity_main);
SupportMapFragment mapFrag = (SupportMapFragment)
getSupportFragmentManager()
.findFragmentById(R.id.map1);
// gotoLocation(SEATTLE_LAT, SEATTLE_LNG);
mMap = mapFrag.getMap();
}
return (mMap != null);
}
private void gotoLocation(double lat, double lag) {
LatLng ll = new LatLng(lat, lag);
CameraUpdate update = CameraUpdateFactory.newLatLng(ll);
mMap.moveCamera(update);
}
}
manifest file
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission a
ndroid:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="my keyy" />
</application>
Have you retrieved a gray map on your phone? If so, your API_KEY for your map did not set correctly.
Please try to follow this step by step, you will finally get a map on your phone.
For MainAcitivity, sample code:
public class MainActivity extends Activity {
private static LatLng goodLatLng = new LatLng(37, -120);
private GoogleMap googleMap;
private EditText et_address, et_finalAddress;
LatLng addressPos, finalAddressPos;
Marker addressMarker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_address = (EditText) findViewById(R.id.addressEditText);
et_finalAddress = (EditText) findViewById(R.id.finalAddressEditText);
// Initial Map
try {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
}
} catch (Exception e) {
e.printStackTrace();
}
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// Put a dot on my current location
googleMap.setMyLocationEnabled(true);
googleMap.setIndoorEnabled(true);
googleMap.setTrafficEnabled(true);
// 3D building
googleMap.setBuildingsEnabled(true);
// Get zoom button
googleMap.getUiSettings().setZoomControlsEnabled(true);
Marker marker = googleMap.addMarker(new MarkerOptions()
.position(goodLatLng)
.title("Hello"));
}
For more details, please refer to my github here.
I have three layouts:
1. calculate_actionbar_layout.xml
2. purchasingmanager_actionbar_layout.xml
3. usermanagement_layout.xml
When I select a tab from action bar the relate layout for this tab with item show in action bar. I want handle the event of items in action bar.for example when I click plus icon do a operation.
this is MainActivity:
public class MainActivity extends FragmentActivity implements
TabListener,OnPageChangeListener,OnClickListener {
ViewPager viewpager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewpager=(ViewPager)findViewById(R.id.pager);
viewpager.setAdapter(new customefragmentAdapterPager(getSupportFragmentManager()));
viewpager.setOnPageChangeListener(this);
ActionBar actionbar = getActionBar();
actionbar.setDisplayShowTitleEnabled(false);
actionbar.setDisplayUseLogoEnabled(false);
actionbar.setDisplayHomeAsUpEnabled(false);
actionbar.setDisplayShowCustomEnabled(true);
actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionbar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
actionbar.setCustomView(R.layout.usermanagement_layout);
ImageView i=(ImageView) getActionBar().getCustomView().findViewById(R.id.imageviewadduser);
i.setOnClickListener(this);
ActionBar.Tab tab1=actionbar.newTab();
tab1.setTabListener(this);
tab1.setCustomView(R.layout.custom_tab);
View v=tab1.getCustomView();
TextView t=(TextView)v.findViewById(R.id.tab_title);
t.setText("محاسبه");
ActionBar.Tab tab2=actionbar.newTab();
tab2.setText("خریدها");
tab2.setTabListener(this);
ActionBar.Tab tab3=actionbar.newTab();
tab3.setText("کاربران");
tab3.setTabListener(this);
actionbar.addTab(tab1);
actionbar.addTab(tab2);
actionbar.addTab(tab3);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
final ActionBar actionbar = getActionBar();
switch (tab.getPosition()) {
case 0:
actionbar.setCustomView(R.layout.calculate_actionbar_layout);
break;
case 1:
actionbar.setCustomView(R.layout.purchasingmanager_actionbar_layout);
break;
case 2:
actionbar.setCustomView(R.layout.usermanagement_layout);
break;
default:
break;
}
viewpager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 3;
}}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int id=v.getId();
int d=id;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
if(item.getItemId() == R.id.imageviewadduser){
// ( 1 ) add a new item
// ( 2 ) change add to remove
}
else{
// if a the new item is clicked show "Toast" message.
}
return super.onOptionsItemSelected(item);
}
}
all layouts have this template:
<?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:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:background="#0d93d2"
android:weightSum="4"
android:gravity="center"
android:layout_gravity="fill_horizontal"
tools:context="MainActivity"
>
<ImageView
android:id="#+id/imageviewusermanagment"
android:layout_width="0sp"
android:layout_weight="2.5"
android:layout_height="wrap_content"
android:src="#drawable/usermanagment"
android:scaleType="fitStart"
android:paddingLeft="20sp"
/>
<ImageView
android:id="#+id/imageviewdeleteuser"
android:layout_width="0sp"
android:layout_weight=".5"
android:layout_height="wrap_content"
android:src="#drawable/deleteuser"
/>
<ImageView
android:id="#+id/imageviewedituser"
android:layout_width="0sp"
android:layout_weight=".5"
android:layout_height="wrap_content"
android:src="#drawable/edituser"/>
<ImageView
android:id="#+id/imageviewadduser"
android:layout_width="0sp"
android:layout_weight=".5"
android:layout_height="wrap_content"
android:src="#drawable/adduser"
/>
</LinearLayout>
and images of selected tab with different icon that I want to handle event of them. You can see them in below links :
selected usermanagement_layout.xml for custom action bar
selected purchasingmanager_actionbar_layout.xml for custom actionbar
1- change this function :
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
final ActionBar actionbar = getActionBar();
View cView=null;
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
switch (tab.getPosition()) {
case 0:
cView = getLayoutInflater().inflate(R.layout.calculate_actionbar_layout, null);
cView.setLayoutParams(param);
actionbar.setCustomView(cView);
//actionbar.setCustomView(R.layout.calculate_actionbar_layout);
break;
case 1:
cView = getLayoutInflater().inflate(R.layout.purchasingmanager_actionbar_layout, null);
cView.setLayoutParams(param);
actionbar.setCustomView(cView);
//actionbar.setCustomView(R.layout.purchasingmanager_actionbar_layout);
break;
case 2:
cView = getLayoutInflater().inflate(R.layout.usermanagement_layout, null);
cView.setLayoutParams(param);
actionbar.setCustomView(cView);
//actionbar.setCustomView(R.layout.usermanagement_layout);
break;
default:
break;
}
viewpager.setCurrentItem(tab.getPosition());
}
2- add android:onClick="onClick" to each imageview in layout
3- change mainactivity to this
View userView = getLayoutInflater().inflate(R.layout.usermanagement_layout, null);
ImageView adduser=(ImageView) userView.findViewById(R.id.imageviewadduser);
adduser.setOnClickListener(this);
ImageView deleteuser=(ImageView) userView.findViewById(R.id.imageviewdeleteuser);
deleteuser.setOnClickListener(this);
ImageView edituser=(ImageView) userView.findViewById(R.id.imageviewedituser);
edituser.setOnClickListener(this);
I'm relitivly new to coding so I'm trying to recreate the tutorial for Google maps using api v3. When I run the tutorial I am getting a null point error which seems to be (from log cat) due to the line setupWebView();
I have defined webview in the .xml and given the appropriate permissions. Here is the WebMapActivity class -
public class WebMapActivity extends Activity implements LocationListener {
private static final String MAP_URL = "http://gmaps-samples.googlecode.com/svn/trunk/articles- android-webmap/simple-android-map.html";
private WebView webView;
private Location mostRecentLocation;
#Override
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
getLocation();
setupWebView();
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
/** Sets up the WebView object and loads the URL of the page **/
private void setupWebView(){
final String centerURL = "javascript:centerAt(" +
mostRecentLocation.getLatitude() + "," +
mostRecentLocation.getLongitude()+ ")";
webView = (WebView) findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
//Wait for the page to load then send the location information
webView.setWebViewClient(new WebViewClient());
webView.loadUrl(MAP_URL);
}
/** The Location Manager manages location providers. This code searches
for the best provider of data (GPS, WiFi/cell phone tower lookup,
some other mechanism) and finds the last known location.
**/
private void getLocation() {
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
String provider = locationManager.getBestProvider(criteria,true);
//In order to make sure the device is getting location, request updates.
locationManager.requestLocationUpdates(provider, 1, 0, this);
mostRecentLocation = locationManager.getLastKnownLocation(provider);
}
/** Sets the mostRecentLocation object to the current location of the device **/
#Override
public void onLocationChanged(Location location) {
mostRecentLocation = location;
}
/** The following methods are only necessary because WebMapActivity implements
LocationListener
**/
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
And here is the .xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<WebView android:id="#+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
I hope, and sure, you can help.
Please let me know if any more info is required...
Thanks,
Jamie