I have a google map with markers, I wanted to intergrade it with ebanx
/swipe-button but When I try to swipe the button I get the following error
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.ebanx.swipebtn.SwipeButton.setOnStateChangeListener(com.ebanx.swipebtn.OnStateChangeListener)' on a null object reference
Bellow is my Code
MapsActivity.java
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private List<LocationModel> mListMarker = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
getAllDataLocationLatLng();
swipe(); // I call it from here
}
private void getAllDataLocationLatLng(){
final ProgressDialog dialog = new ProgressDialog(this);
dialog.setMessage("Menampilkan data marker ..");
dialog.show();
ApiService apiService = ApiClient.getClient().create(ApiService.class);
Call<ListLocationModel> call = apiService.getAllLocation();
call.enqueue(new Callback<ListLocationModel>() {
#Override
public void onResponse(Call<ListLocationModel> call, Response<ListLocationModel> response) {
dialog.dismiss();
mListMarker = response.body().getmData();
initMarker(mListMarker);
}
#Override
public void onFailure(Call<ListLocationModel> call, Throwable t) {
dialog.dismiss();
Toast.makeText(MapsActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void initMarker(List<LocationModel> listData){
for (int i=0; i<mListMarker.size(); i++){
LatLng location = new LatLng(Double.parseDouble(mListMarker.get(i).getLatutide()), Double.parseDouble(mListMarker.get(i).getLongitude()));
mMap.addMarker(new MarkerOptions().position(location).title(mListMarker.get(i).getImageLocationName()));
LatLng latLng = new LatLng(Double.parseDouble(mListMarker.get(0).getLatutide()), Double.parseDouble(mListMarker.get(0).getLongitude()));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latLng.latitude,latLng.longitude), 11.0f));
}
}
//ebanx /swipe-button code
private void swipe(){
SwipeButton swipeButton = (SwipeButton)findViewById(R.id.swipe_button);
swipeButton.setOnStateChangeListener(new OnStateChangeListener() {
#Override
public void onStateChange(boolean active) {
/*
More code here*/
}
});
}
}
Activity_Maps.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MapsActivity" />
<com.ebanx.swipebtn.SwipeButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="18sp"
android:layout_alignParentBottom="true"
app:inner_text_background="#drawable/inner_text_shape"
app:button_image_disabled="#drawable/ic_lock_open_black_24dp"
app:button_image_enabled="#drawable/ic_lock_outline_black_24dp"
app:button_background="#drawable/shape_button2"
app:inner_text="Swipe to Unlock"
app:inner_text_size="20sp"
app:inner_text_bottom_padding="15dp"
app:inner_text_top_padding="15dp"
app:button_top_padding="15dp"
app:button_right_padding="15dp"
app:button_bottom_padding="15dp"
app:button_left_padding="15dp"
/>
</RelativeLayout>
Related
Recently I changed from andoroid to androidx. After that, my app crash after successfully sign in. The following quotes are the errors:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.material.tabs.TabLayout.setupWithViewPager(androidx.viewpager.widget.ViewPager)' on a null object reference
After a lot of research, some suggest that use finishUpdate method but my app still crashes.
#Override public void finishUpdate(ViewGroup container) {
try{
super.finishUpdate(container);
}
catch (NullPointerException nullPointerException){
System.out.println("Catch the NullPointerException in MainActivityFragmentsAdapter.finishUpdate");
}
}
I also have tried to replace code tabLayout.setupWithViewPager(viewPager); to codes below but same error
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
//tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
The codes below are my MainActivity class
public class MainActivity extends BaseActivity {
MainActivityFragmentsAdapter mainActivityFragmentsAdapter;
ViewPager viewPager;
String SAVE_INSTANCE_STATE_KEY = "MainActivityFragmentConfig";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainActivityFragmentsAdapter = new MainActivityFragmentsAdapter(getSupportFragmentManager());
viewPager = findViewById(R.id.main_view_pager);
viewPager.setAdapter(mainActivityFragmentsAdapter);
if(savedInstanceState != null ) {
position = savedInstanceState.getInt(SAVE_INSTANCE_STATE_KEY);
viewPager.setCurrentItem(position);
}
final TabLayout tabLayout = findViewById(R.id.main_tab_layout);
tabLayout.setupWithViewPager(viewPager); // This is the ERROR LINE
viewPager.setOffscreenPageLimit(4);
setTabIcons(tabLayout);
ActivityCompat.requestPermissions(MainActivity.this, new String[]
{android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION}, 100);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onRestoreInstanceState(savedInstanceState, persistentState);
if(savedInstanceState != null ) {
int position = savedInstanceState.getInt(SAVE_INSTANCE_STATE_KEY);
viewPager.setCurrentItem(position);
}
}
#Override
public void onStart() {
super.onStart();
}
int position;
#Override
protected void onPause() {
super.onPause();
position = viewPager.getCurrentItem();
}
#Override
protected void onResume() {
super.onResume();
viewPager.setCurrentItem(position);
}
public void setTabIcons(TabLayout tabLayout) {
int icons[]= {
R.drawable.ic_calendar,
R.drawable.ic_task_complete,
R.drawable.ic_alarm_clock,
R.drawable.ic_man_user
};
for(int i = 0; i < icons.length; i++) {
tabLayout.getTabAt(i).setIcon(icons[i]);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Log.d("MAIN ACTIVITY", "Saving instance state");
outState.putInt(SAVE_INSTANCE_STATE_KEY, viewPager.getCurrentItem());
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.fyp.selfzenapp.MainActivity">
<androidx.viewpager.widget.ViewPager
android:id="#+id/main_view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="60dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<include
android:id="#+id/main_tab_layout_include"
layout="#layout/main_tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
I'm new in coding and I'm trying to make my first app so I say sorry in advance if it could sound stupid to the most.
My app should basically recollect datas (Edit Text) from the add client Activity and show markers in the map Activity.
To do this I thought to put all the informations in Array and then show it on the map.
The question is "how can I do that?" everything I do gives me lots of errors :/
This is where I'm stuck
MapsActivity.java
public class MapsActivity extends FragmentActivity implements
OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener
{
private GoogleMap mMap;
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
private Location lastLocation;
private static final int Request_User_Location_Code = 99;
private Button button;
public MapsActivity() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
checkUserlLocationPermission();
}
// 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);
//set onclicklistener on the button
button = (Button) findViewById(R.id.btnAddClient);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent intent =new Intent(MapsActivity.this,AddClient.class);
startActivity(intent);
}
});
}
#Override
public void onMapReady(GoogleMap googleMap)
{
mMap = googleMap;
//Asking for permission and set current location
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
//Checking permission
private boolean checkUserlLocationPermission()
{
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION))
{
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, Request_User_Location_Code);
}
else
{
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, Request_User_Location_Code);
}
return false;
}
else
{
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults)
{
switch (requestCode)
{
case Request_User_Location_Code:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
if (googleApiClient == null)
{
buildGoogleApiClient();
}
mMap.setBuildingsEnabled(true);
}
}
else
{
Toast.makeText(this,"DENIED", Toast.LENGTH_SHORT).show();
}
return;
}
}
protected synchronized void buildGoogleApiClient()
{
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
}
#Override
public void onLocationChanged(Location location)
{
lastLocation = location;
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate center=CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude()));
CameraUpdate zoom=CameraUpdateFactory.zoomTo(16);
mMap.moveCamera(center);
mMap.animateCamera(zoom);
if (googleApiClient != null)
{
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
}
}
//Set interval location
#Override
public void onConnected(#Nullable Bundle bundle)
{
locationRequest = new LocationRequest();
locationRequest.setInterval(1100);
locationRequest.setFastestInterval(1100);
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
{
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}
activity_map.xml
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MapsActivity" >
<Button
android:id="#+id/btnAddClient"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|right"
android:layout_marginRight="20dp"
android:layout_marginBottom="20dp"
android:background="#drawable/mybutton"
android:text="Add client"
/>
</fragment>
AddClient.java
public class AddClient extends AppCompatActivity {
public Button btnDone;
public EditText name;
public EditText address;
public LatLng latLng;
public GoogleMap mMap;
public Marker marker;
ArrayList<String> clientNames = new ArrayList<>();
ArrayList<String> clientAddress = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addclient);
btnDone = (Button) findViewById(R.id.done_button);
name = (EditText) findViewById(R.id.edit_name);
btnDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clientNames.add(name.getText().toString());
clientAddress.add(address.getText().toString());
getLocationFromAddress();
}
public void getLocationFromAddress(String strAddress) {
//Create coder with Activity context - this
Geocoder coder = new Geocoder(this);
List<Address> address;
try {
//Get latLng from String
address = coder.getFromLocationName(strAddress, 5);
//check for null
if (address == null) {
return;
}
//Lets take first possibility from the all possibilities.
Address location = address.get(0);
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
//Put marker on map on that LatLng
Marker srchMarker = mMap.addMarker(new MarkerOptions().position(latLng).title("name"));
//Animate and Zoon on that map location
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
addclient.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dip"
android:layout_marginBottom="25dip"
android:text="NEW CLIENT DETAILS"
android:textStyle="bold"
android:textSize="30dp"
android:gravity="center_horizontal"/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Client name:"
android:textSize="20dp"/>
<EditText
android:id="#+id/edit_name"
android:layout_width="fill_parent"
android:layout_height="60dp"
android:text=""
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dip"
android:text="Client address"
android:textSize="20dp"/>
<EditText
android:id="#+id/edit_lastname"
android:layout_width="fill_parent"
android:layout_height="60dp"
android:text=""
/>
<Button
android:id="#+id/done_button"
android:layout_height="wrap_content"
android:text="DONE"
android:layout_width="130dip"
android:background="#drawable/mybutton"
android:layout_gravity="center"
/>
</LinearLayout>
You should use Google Places API which has an auto complete adapter and predictions for places, below link shows a similar app.
Google-Maps-Google-Places
I cannot add markers to my map using the recommended documentation, I have no errors however markers are not appearing on the map.
I have tried the following:
gmap = googleMap;
gmap.setMinZoomPreference(12);
LatLng ny = new LatLng(40.7143528, -74.0059731);
gmap.moveCamera(CameraUpdateFactory.newLatLng(ny));
and
gmap.addMarker(new MarkerOptions()
.position(new LatLng(10, 10))
.title("Hello world"));
Neither of these are working.
Here is my main activity,
private static MapView mapView;
private GoogleMap gmap;
private static final String MAP_VIEW_BUNDLE_KEY = "MapViewBundleKey";
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
session = new SessionHandler(getApplicationContext());
final User user = session.getUserDetails();
final View background = findViewById(R.id.home_background_view);
final ViewPager viewPager = (ViewPager) findViewById(R.id.home_view_pager);
MainPagerAdapter adapter = new MainPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
final int colourGreen = ContextCompat.getColor(this, R.color.Green);
final int colourPink = ContextCompat.getColor(this, R.color.Pink);
final int colourBlue = ContextCompat.getColor(this, R.color.CafeSeaBlue);
TabLayout tabLayout = (TabLayout) findViewById(R.id.am_tab_layout);
tabLayout.setupWithViewPager(viewPager);
loadLocations();
// SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
// .findFragmentById(R.id.map);
// mapFragment.getMapAsync(this);
viewPager.setCurrentItem(1);
//mapView = findViewById(R.id.mapView);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//if on first screen
if (position == 0)
{
background.setBackgroundColor(colourBlue);
//background.setAlpha(1-positionOffset);
}
//if on mid screen
else if (position == 1) {
background.setBackgroundColor(colourPink);
//background.setAlpha(positionOffset);
}
//if on last screen
else if (position == 2) {
background.setBackgroundColor(colourGreen);
//background.setAlpha(1+positionOffset);
}
}
#Override
public void onPageSelected(int position) {
if(position == 0)
{
}if(position == 2){
// gmap.addMarker(new MarkerOptions()
// .position(new LatLng(50, 50))
// .title("Hello world"));
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
#Override
public void onConnected(#Nullable Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
}
#Override
public void onLocationChanged(Location location) {
double currentLatitude = location.getLatitude();
double currentLongitude = location.getLongitude();
globalLat = location.getLatitude();
globalLong = location.getLongitude();
Log.d("Location","Longitude = "+currentLongitude);
Log.d("Location","Latitude = "+currentLatitude);
if(tv1 != null)
tv1.setText(Double.toString(currentLatitude));
if(tv2 != null)
tv2.setText(Double.toString(currentLongitude));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
//progress bar
private void displayLoader() {
pDialog = new ProgressDialog(HomeActivity.this);
pDialog.setMessage("Loading.. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
public void onItemClick(View view, int position) {
Toast.makeText(this, "You clicked " + adapter.getItem(position) + " on row number " + position, Toast.LENGTH_SHORT).show();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Bundle mapViewBundle = outState.getBundle(MAP_VIEW_BUNDLE_KEY);
if (mapViewBundle == null) {
mapViewBundle = new Bundle();
outState.putBundle(MAP_VIEW_BUNDLE_KEY, mapViewBundle);
}
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
}
#Override
public void onMapReady(GoogleMap map) {
gmap.addMarker(new MarkerOptions()
.position(new LatLng(10, 10))
.title("Hello world"));
}
}
And my layout:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
tools:background="#color/CafeSeaBlue"
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:tools="http://schemas.android.com/tools">
<View
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="80dp"
android:background="#drawable/card_background" />
<android.support.v7.widget.AppCompatTextView
android:id="#+id/latText1"
android:layout_width="match_parent"
android:layout_height="32dp"
android:layout_below="#+id/longText"
android:layout_marginTop="100dp"
android:layout_marginBottom="50dp"
android:background="#color/White"
android:text="Map Screen"
android:textAlignment="center"/>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="150dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="40dp"
tools:context=".HomeActivity"
/>
</FrameLayout>
// SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
// .findFragmentById(R.id.map);
// mapFragment.getMapAsync(this);
having this uncommented in the section it is currently in crashes it unexpectedly, saying null object reference
The map itself loads however I cannot get pins on it. I have tried so many methods and probably have quite a bit of unnecessary code.
The map displays on the screen, i would attach an image but i require 10 points before I am able to. I cannot add markers to my map using the recommended documentation, I have no errors however markers are not appearing on the map.
I have tried the following:
gmap = googleMap;
gmap.setMinZoomPreference(12);
LatLng ny = new LatLng(40.7143528, -74.0059731);
gmap.moveCamera(CameraUpdateFactory.newLatLng(ny));
and
gmap.addMarker(new MarkerOptions()
.position(new LatLng(10, 10))
.title("Hello world"));
Neither of these are working.
Here is my main activity,
private static MapView mapView;
private GoogleMap gmap;
private static final String MAP_VIEW_BUNDLE_KEY = "MapViewBundleKey";
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
session = new SessionHandler(getApplicationContext());
final User user = session.getUserDetails();
final View background = findViewById(R.id.home_background_view);
final ViewPager viewPager = (ViewPager) findViewById(R.id.home_view_pager);
MainPagerAdapter adapter = new MainPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
final int colourGreen = ContextCompat.getColor(this, R.color.Green);
final int colourPink = ContextCompat.getColor(this, R.color.Pink);
final int colourBlue = ContextCompat.getColor(this, R.color.CafeSeaBlue);
TabLayout tabLayout = (TabLayout) findViewById(R.id.am_tab_layout);
tabLayout.setupWithViewPager(viewPager);
loadLocations();
// SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
// .findFragmentById(R.id.map);
// mapFragment.getMapAsync(this);
viewPager.setCurrentItem(1);
//mapView = findViewById(R.id.mapView);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//if on first screen
if (position == 0)
{
background.setBackgroundColor(colourBlue);
//background.setAlpha(1-positionOffset);
}
//if on mid screen
else if (position == 1) {
background.setBackgroundColor(colourPink);
//background.setAlpha(positionOffset);
}
//if on last screen
else if (position == 2) {
background.setBackgroundColor(colourGreen);
//background.setAlpha(1+positionOffset);
}
}
#Override
public void onPageSelected(int position) {
if(position == 0)
{
}if(position == 2){
// gmap.addMarker(new MarkerOptions()
// .position(new LatLng(50, 50))
// .title("Hello world"));
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
#Override
public void onConnected(#Nullable Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
}
#Override
public void onLocationChanged(Location location) {
double currentLatitude = location.getLatitude();
double currentLongitude = location.getLongitude();
globalLat = location.getLatitude();
globalLong = location.getLongitude();
Log.d("Location","Longitude = "+currentLongitude);
Log.d("Location","Latitude = "+currentLatitude);
if(tv1 != null)
tv1.setText(Double.toString(currentLatitude));
if(tv2 != null)
tv2.setText(Double.toString(currentLongitude));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
//progress bar
private void displayLoader() {
pDialog = new ProgressDialog(HomeActivity.this);
pDialog.setMessage("Loading.. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
public void onItemClick(View view, int position) {
Toast.makeText(this, "You clicked " + adapter.getItem(position) + " on row number " + position, Toast.LENGTH_SHORT).show();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Bundle mapViewBundle = outState.getBundle(MAP_VIEW_BUNDLE_KEY);
if (mapViewBundle == null) {
mapViewBundle = new Bundle();
outState.putBundle(MAP_VIEW_BUNDLE_KEY, mapViewBundle);
}
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
}
#Override
public void onMapReady(GoogleMap map) {
gmap.addMarker(new MarkerOptions()
.position(new LatLng(10, 10))
.title("Hello world"));
}
}
And my layout:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
tools:background="#color/CafeSeaBlue"
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:tools="http://schemas.android.com/tools">
<View
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="80dp"
android:background="#drawable/card_background" />
<android.support.v7.widget.AppCompatTextView
android:id="#+id/latText1"
android:layout_width="match_parent"
android:layout_height="32dp"
android:layout_below="#+id/longText"
android:layout_marginTop="100dp"
android:layout_marginBottom="50dp"
android:background="#color/White"
android:text="Map Screen"
android:textAlignment="center"/>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="150dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="40dp"
tools:context=".HomeActivity"
/>
</FrameLayout>
// SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
// .findFragmentById(R.id.map);
// mapFragment.getMapAsync(this);
having this uncommented in the section it is currently in crashes it unexpectedly, saying null object reference
The map itself loads however I cannot get pins on it. I have tried so many methods and probably have quite a bit of unnecessary code.
I would attach an image of the displaying and interatable map here but I do not have 10 points.
https://i.imgur.com/mpp9aAY.png
It appears that you are focusing your map on the NY City area, but are pinning your marker in the middle of Nigeria. Are you sure that the marker is not successfully added? Try setting your marker near where you position the map focus.
mapFragment = (SupportMapFragment) getChildFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
these codes are necessary, else you won't get any callback to
onMapReady(GoogleMap googleMap) {}
I think the crash occurs because the variable gmap is not initialised. Just add gmap = map before adding the marker in the onMapReady.
I am trying to create one flipview which is contain one side Google Map and one side Recyclerview.
I am getting an error while i try i call an Map fragment. it give nullpointer while map has to load at initialization time.
File 1 : fragment_left.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#android:color/transparent">
<fragment
android:id="#+id/map_fragment"
android:layout_below="#+id/header"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_above="#+id/footer"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
File 2 : fragment_right.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/transparent"
android:orientation="vertical" >
<android.support.v7.widget.RecyclerView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/header"
android:background="#mipmap/back"
android:layout_above="#+id/footer"/>
</LinearLayout>
File 3 : flipscreen.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".flipscreen" >
<RelativeLayout
android:id="#+id/header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="#mipmap/gradiant"
android:layout_alignParentTop="true"
android:padding="6dp">
<TextView
android:id="#+id/activity_registration_txtTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textSize="16sp"
android:textStyle="bold"
android:text="#string/events"/>
<ImageView
android:id="#+id/listOfEvent"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_alignParentRight="true"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="#mipmap/menu"/>
</RelativeLayout>
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_below="#+id/header"
android:layout_above="#+id/footer"
android:layout_height="wrap_content"
android:layout_centerInParent="true" >
</FrameLayout>
</RelativeLayout>
Java Files
File 1 : flipscreen.java :
public class flipscreen extends FragmentActivity {
private boolean showingBack;
private FragmentLeft left = new FragmentLeft();
private FragmentRight right = new FragmentRight();
private Context context;
private Handler handler;
private FlipAnimation flipAnimation;
private FlipAnimation backFlip;
private GoogleMap map;
private FragmentManager mFragmrg;
List<Event> lsEvent=new ArrayList<Event>();
private double latitude = 0;
private double longitude = 0;
FrameLayout mapLayout;
ImageView flipView;
ImageButton btnAddEvent;
String strUserId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.flipscreen);
context = this;
handler = new Handler(getMainLooper());
mapLayout = (FrameLayout)findViewById(R.id.fragment_container);
getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, right, "fragmentRight").commit();
getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, left, "fragmentLeft").commit();
flipView=(ImageView) findViewById(R.id.listOfEvent);
btnAddEvent=(ImageButton)findViewById(R.id.btnAddEvent);
btnAddEvent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!(strUserId.equals(""))){
startActivity(new Intent(flipscreen.this,AddEventActivity.class));
// finish();
}else{
startActivity(new Intent(flipscreen.this,LoginActivity.class));
}
}
});
flipView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
flipAnimation = new FlipAnimation(left.getView(), right.getView());
backFlip = new FlipAnimation(left.getView(), right.getView());
handler.removeCallbacks(rotate);
handler.postDelayed(rotate, 100);
}
});
}
private Runnable rotate = new Runnable() {
#Override
public void run() {
if (!showingBack) {
left.getView().startAnimation(flipAnimation);
right.getView().startAnimation(flipAnimation);
// Toast.makeText(context, "flip", Toast.LENGTH_LONG).show();
flipView.setImageResource(R.mipmap.nav_map);
showingBack = true;
} else {
showingBack = false;
backFlip.reverse();
// Toast.makeText(context, "backflip", Toast.LENGTH_LONG).show();
left.getView().startAnimation(backFlip);
right.getView().startAnimation(backFlip);
flipView.setImageResource(R.mipmap.menu);
}
}
};
}
File 2 : fragmentLeft.java :
public class FragmentLeft extends Fragment {
private GoogleMap map;
private FragmentManager mFragmrg;
List<Event> lsEvent=new ArrayList<Event>();
private double latitude = 0;
private double longitude = 0;
private SupportMapFragment mMapFragment;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View flipMap =inflater.inflate(R.layout.fragment_left, container,false);
SupportMapFragment mapFragment = (SupportMapFragment) getFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
// // Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(latitude, longitude);
map.clear();
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 8);
map.animateCamera(cameraUpdate);
System.out.println("Latitude "+latitude+ " \n Longitude "+longitude);
}
});
return flipMap;
}
}
File 3 : FragmentRight.java :
public class FragmentRight extends Fragment {
private static final String TAG ="NearByActivityList" ;
RecyclerView recyclerView;
List<Event> lsEvent=new ArrayList<Event>();
protected GoogleApiClient mGoogleApiClient;
protected Location mLastLocation;
ImageView listOfEvent;
double latitude = 0;
double longitude = 0;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View fillData =inflater.inflate(R.layout.fragment_right, container,false);
recyclerView = (RecyclerView) fillData.findViewById(R.id.list);
GridLayoutManager manager = new GridLayoutManager(getActivity(), 3);
manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
#Override
public int getSpanSize(int position) {
return (3 - position % 3);
}
});
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return fillData;
}
}
My issue is in fragmentLeft.java it's getting null
SupportMapFragment mapFragment = (SupportMapFragment) getFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(new OnMapReadyCallback() {
I have review your code and I think the error is R.id.map, you have not, #+id/map in xml you have #+id/map_fragment:
SupportMapFragment mapFragment = (SupportMapFragment) getFragmentManager().findFragmentById(R.id.map_fragment)
mapFragment.getMapAsync(new OnMapReadyCallback() {
I found this solution of my problem.. Here is the ans of that.
I found it in https://code.google.com/p/gmaps-api-issues/issues/detail?id=5064 Link.
FragmentLeft.java :
public class FragmentLeft extends Fragment {
private GoogleMap map;
GPSTracker gps;
private SupportMapFragment fragment;
List<Event> lsEvent=new ArrayList<Event>();
private double latitude = 0;
private double longitude = 0;
private GoogleMap mMap;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View flipMap =inflater.inflate(R.layout.fragment_left, container,false);
gps = new GPSTracker(getActivity());
latitude = gps.getLatitude();
longitude = gps.getLongitude();
return flipMap;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
FragmentManager fm = getChildFragmentManager();
fragment = (SupportMapFragment) fm.findFragmentById(R.id.map_fragment);
if (fragment == null) {
fragment = SupportMapFragment.newInstance();
fm.beginTransaction().replace(R.id.map_fragment, fragment).commit();
}
}
#Override
public void onResume() {
super.onResume();
if (map == null) {
map = fragment.getMap();
System.out.println("Latitude : = "+latitude+" Longitude : ="+longitude);
map.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)));
LatLng sydney = new LatLng(latitude, longitude);
map.clear();
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 12);
map.animateCamera(cameraUpdate);
}
}
}
I'm trying to show a GoogleMap in my App but I get problems right at the beginning of this task.
The line:
SupportMapFragment mapFrag = (SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map);
always returns null.
I have tried a lot of things but nothing works. Could you please help me to find the Problem?
Here is my Code:
public class MapSectionFragment extends Fragment implements
ConnectionCallbacks,
OnConnectionFailedListener,
LocationListener,
OnMyLocationButtonClickListener,
OnMapReadyCallback{
private GoogleMap map;
Location location;
GoogleApiClient mGoogleApiClient;
private static final LocationRequest REQUEST = LocationRequest.create()
.setInterval(5000) // 5 seconds
.setFastestInterval(16) // 16ms = 60fps
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
private void createMapView(){
try{
//here it comes
SupportMapFragment mapFrag = (SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map);
map = mapFrag.getMap(); //throws NullPointerException
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_section_map,
container, false);
createMapView();
return rootView;
}
#Override
public void onPause() {
super.onPause();
mGoogleApiClient.disconnect();
}
#Override
public void onResume() {
super.onResume();
mGoogleApiClient.connect();
}
#Override
public void onConnected(Bundle bundle) {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient,
REQUEST,
this); // LocationListener
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
#Override
public void onMapReady(GoogleMap googleMap) {
map.setMyLocationEnabled(true);
}
#Override
public boolean onMyLocationButtonClick() {
Toast.makeText(getActivity(), "MyLocation button clicked", Toast.LENGTH_SHORT).show();
// Return false so that we don't consume the event and the default behavior still occurs
// (the camera animates to the user's current position).
return false;
}
}
And here is the XML "fragment_section_map" with the mapID:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:id="#+id/refresh_map_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:text="#string/refresh_map" />
<fragment
android:id="#+id/map"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
class="com.google.android.gms.maps.SupportMapFragment"/>
</LinearLayout>
Thanks for your help!
please try this replace
SupportMapFragment mapFrag = (SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map);
With
SupportMapFragment mapFrag = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
because
getChildFragmentManager()
will managing fragments inside an fragment because your are using SupportMapFragment inside a fragment, so please try this solution
Hope this will help you