I'm new in android so please help me. I want to open fragment with map inside another fragment so I made a transaction in the first fragment:
View rootView = inflater.inflate(R.layout.fragment_location, container, false);
btn = rootView.findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MapsFragment gMaps = new MapsFragment();
assert getFragmentManager() != null;
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.mainlayout, gMaps()); //HERE IS A PROBLEM
transaction.commit();
}
});
return rootView;
When gMaps() is called it shows an error Method call expected
Screenshot
Here is MapsFragment.java code
public class MapsFragment extends FragmentActivity implements OnMapReadyCallback, APIService.fetchResults {
private GoogleMap mMap;
private APIService apiService;
private IntentFilter connectivityIntentFilter;
private BottomSheetDialog bottomSheetDialog;
private View dialogView;
private Boolean isOpenOnly;
private Integer maxPrice;
private Integer radius;
private Place previousPlace;
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (!NetworkChecker.getInstance().isNetworkAvailable(context)) {
Snackbar.make(findViewById(R.id.main_map), getString(R.string.no_active_connection), Snackbar.LENGTH_SHORT).show();
}
}
};
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_maps);
apiService = new APIService(this);
connectivityIntentFilter = new IntentFilter(CONNECTIVITY_ACTION);
GooglePlayServiceChecker googlePlayServiceChecker = new GooglePlayServiceChecker();
if (!googlePlayServiceChecker.checkGooglePlayServices(this)) {
Snackbar.make(findViewById(R.id.main_map), getString(R.string.no_google_play_services), Snackbar.LENGTH_SHORT).show();
finish();
}
final SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
assert mapFragment != null;
mapFragment.getMapAsync(this);
PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment) getFragmentManager().findFragmentById(R.id.place_autocomplete);
AutocompleteFilter typeFilter = new AutocompleteFilter.Builder()
.setTypeFilter(AutocompleteFilter.TYPE_FILTER_REGIONS)
.build();
autocompleteFragment.setFilter(typeFilter);
autocompleteFragment.setHint(getString(R.string.default_city));
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
String s = (String) place.getName();
//Update place data.
previousPlace = place;
apiService.getPlaceSearch(s, getString(R.string.place_type), radius, maxPrice, isOpenOnly);
}
#Override
public void onError(Status status) {
}
});
bottomSheetDialog = new BottomSheetDialog(MapsFragment.this);
dialogView = getLayoutInflater().inflate(R.layout.bottom_sheet, null);
bottomSheetDialog.setContentView(dialogView);
FloatingActionButton floatingActionButton = findViewById(R.id.fab_filter);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialogView.setVisibility(View.VISIBLE);
bottomSheetDialog.show();
}
});
final Switch swOpenOnly = dialogView.findViewById(R.id.openCloseSwitch);
final SeekBar skRadius = dialogView.findViewById(R.id.seekbar_radius);
final SeekBar skPrice = dialogView.findViewById(R.id.seekbar_price);
dialogView.findViewById(R.id.bt_submit_filter).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
radius = skRadius.getProgress();
maxPrice = skPrice.getProgress();
isOpenOnly = swOpenOnly.isChecked();
bottomSheetDialog.dismiss();
//Get places using filter.
if (previousPlace == null) {
apiService.getPlaceSearch(getString(R.string.default_city), getString(R.string.place_type), radius, maxPrice, isOpenOnly);
} else {
apiService.getPlaceSearch(previousPlace.getName().toString(), getString(R.string.place_type), radius, maxPrice, isOpenOnly);
}
}
});
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
#Override
public void parseResults(Result result) {
mMap.clear();
if (result != null && result.getStatus() != null && result.getStatus().equals("OK")) {
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (Restaurant restaurant : result.getRestaurants()) {
Location pastLocation = restaurant.getGeometry().getLocation();
LatLng latLng = new LatLng(pastLocation.getLatitude(), pastLocation.getLongitude());
MarkerOptions markerOptions = new MarkerOptions()
.position(latLng)
.title(restaurant.getName())
.snippet(restaurant.getFormattedAddress());
Marker m = mMap.addMarker(markerOptions);
m.setTag(restaurant.getResID());
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
builder.include(m.getPosition());
}
try {
LatLngBounds latLngBounds = builder.build();
int padding = 10;
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(latLngBounds, padding);
mMap.animateCamera(cu);
} catch (IllegalStateException | ParseException | NullPointerException e) {
//Don't move
}
} else {
Snackbar.make(findViewById(R.id.main_map), getString(R.string.error_message), Snackbar.LENGTH_SHORT).show();
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (!NetworkChecker.getInstance().isNetworkAvailable(this))
Snackbar.make(findViewById(R.id.main_map), getString(R.string.no_active_connection), Snackbar.LENGTH_SHORT).show();
else
apiService.getPlaceSearch(getString(R.string.default_city), getString(R.string.place_type), radius, maxPrice, isOpenOnly);
mMap.setOnInfoWindowClickListener(marker -> {
Intent i = new Intent(MapsFragment.this, DetailActivity.class);
i.putExtra(getString(R.string.intent_key_id_tag), marker.getTag().toString());
if (NetworkChecker.getInstance().isNetworkAvailable(MapsFragment.this))
startActivity(i);
});
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(broadcastReceiver, connectivityIntentFilter);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
}
}
I don't know does it make sense but ok. How to solve this problem?
Screenshot 2
You might be using android.app.FragmentTransaction. Try using androidx.fragment.app.FragmentTransaction and getSupportFragmentManager().beginTransaction().
Like:
androidx.fragment.app.FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
MapsFragment gMaps = new MapsFragment();
assert getFragmentManager() != null;
transaction.replace(R.id.mainlayout, gMaps).commit();
Related
When I try to open the Navigation Home the App crashes
Navigation Home image
I have tried initializing the mMap but the app still crashes. Please help me out
My error >
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.GoogleMap.clear()' on a null object reference
at com.example.gpshelper.Activity.home$2.onLocationResult(home.java:138)
Here's my Code
public class home extends AppCompatActivity implements OnMapReadyCallback, NavigationView.OnNavigationItemSelectedListener {
DrawerLayout drawerLayout;
Toolbar toolbar;
NavigationView navigationView;
ActionBarDrawerToggle actionBarDrawerToggle;
GoogleMap mMap;
LocationRequest locationRequest;
FusedLocationProviderClient fusedLocationProviderClient;
LatLng latLng;
FirebaseUser firebaseUser;
FirebaseAuth firebaseAuth;
TextView header_name, header_email;
DatabaseReference databaseReference;
String current_uid;
AlertDialog.Builder builder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
drawerLayout = findViewById(R.id.drawerlayout);
toolbar = findViewById(R.id.home_toolbar);
setSupportActionBar(toolbar);
navigationView = findViewById(R.id.nev_view);
//navigationView.setNavigationItemSelectedListener(this);
actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.app_name,R.string.app_name);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
databaseReference = FirebaseDatabase.getInstance().getReference("users");
firebaseAuth = FirebaseAuth.getInstance();
firebaseUser = firebaseAuth.getCurrentUser();
current_uid = firebaseUser.getUid();
callpermissionlistener();
update_location();
dynamicheaderlistener();
}
private void dynamicheaderlistener() {
View header = navigationView.getHeaderView(0);
header_name = header.findViewById(R.id.header_name_text);
header_email = header.findViewById(R.id.header_email_text);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String current_name = dataSnapshot.child(current_uid).child("firstname").getValue(String.class);
String current_email = dataSnapshot.child(current_uid).child("email").getValue(String.class);
String s1 = "Hi "+current_name;
header_name.setText(s1);
header_email.setText(current_email);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void update_location() {
if (ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION)== PermissionChecker.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION)==PermissionChecker.PERMISSION_GRANTED)
{
fusedLocationProviderClient = new FusedLocationProviderClient(this);
locationRequest = new LocationRequest()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(3000) //update interval
.setFastestInterval(5000); //fastest interval
fusedLocationProviderClient.requestLocationUpdates(locationRequest, new LocationCallback(){
#Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult != null)
{
mMap.clear();
final double lat = locationResult.getLastLocation().getLatitude();
final double log = locationResult.getLastLocation().getLongitude();
latLng = new LatLng(lat, log);
mMap.addMarker(new MarkerOptions().position(latLng).title("your current location"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15F));
//update latitude and longitude
Map <String, Object> update = new HashMap<>();
update.put("latitude", lat);
update.put("longitude", log);
databaseReference.child(current_uid).updateChildren(update).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
//Toast.makeText(home.this, "updated", Toast.LENGTH_SHORT).show();
}
});
}else {
Toast.makeText(home.this,"location not found", Toast.LENGTH_SHORT).show();
}
}
},getMainLooper());
}
else
{
callpermissionlistener();
}
}
private void callpermissionlistener() {
String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
String rationale = "Please provide location permission so that you can ...";
Permissions.Options options = new Permissions.Options()
.setRationaleDialogTitle("location permission")
.setSettingsDialogTitle("warrning");
Permissions.check(this, permissions, rationale, options, new PermissionHandler() {
#Override
public void onGranted() {
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.fragment_container);
mapFragment.getMapAsync(home.this);
update_location();
}
#Override
public void onDenied(Context context, ArrayList<String> deniedPermissions) {
callpermissionlistener();
}
});
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)){
drawerLayout.closeDrawer(GravityCompat.START);
}
else {
backpressedwarrning();
}
//super.onBackPressed();
}
public void backpressedwarrning(){
builder = new AlertDialog.Builder(home.this);
builder.setMessage(R.string.dialog_message).setTitle(R.string.dialog_title);
builder.setMessage("Do you want to close this application ?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.setTitle("Exit");
alert.show();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// LatLng sydney = new LatLng(-34, 151);
//mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
//.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()){
case R.id.nev_home:
startActivity(new Intent(home.this, home.class));
finish();
break;
case R.id.nev_profile:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new profilefagment()).commit();
/*getSupportActionBar().setTitle("profile");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);*/
break;
case R.id.nev_joiningc:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new joincirclefragment()).commit();
break;
case R.id.nev_invite:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new invitecodefragment()).commit();
break;
case R.id.nev_mycircle:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new mycirclefragment()).commit();
break;
case R.id.nev_logout:
firebaseUser = firebaseAuth.getCurrentUser();
if (firebaseUser != null)
{
firebaseAuth.signOut();
finish();
startActivity(new Intent(home.this, login_screen.class));
}
break;
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
}
It's because somehow before initializing mMap from the onMapReady(), it called mMap.clear();
To prevent the crash, make sure to null-check the mMap first and then access it.
For e.g.
if (mMap != null) {
...
mMap.clear();
mMap.addMarker(...);
mMap. moveCamera(...);
...
}
I started my first experience in coding a few days ago. Didn't find an answer for my question, so I hope someone could help me.
In my project, I have a MainActivity with a BottomNavigationView using Fragments. I added a map as one of the fragments and it works fine.
But I changed and add some methods in the MapsActivity, things like device location and ask for permission. But when I run the app it doesn't call these methods, so I think it is because the MapFragment needs to get the methods of the MapsActivity but I don't know how to solve the problem and didn't find an answer for my question.
My MapFragment
public class Map_Fragment extends Fragment implements OnMapReadyCallback {
SupportMapFragment mapFragment;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_map_, container, false);
mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
if (mapFragment == null) {
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
mapFragment = SupportMapFragment.newInstance();
ft.replace(R.id.map, mapFragment).commit();
}
mapFragment.getMapAsync(this);
// Inflate the layout for this fragment
return v;
}
#Override
public void onMapReady(GoogleMap googleMap) {
}
}
My MapActivity:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private static final String TAG = "MapActivity";
private GoogleMap mMap;
private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
private static final String COARSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
private static final float DEFAULT_ZOOM = 150f;
// vars
private Boolean mLocationPermissionGranted = false;
private FusedLocationProviderClient mFusedLocationProviderClient;
protected void createLocationRequest() {
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setInterval(10000);
locationRequest.setFastestInterval(5000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
Log.d(TAG, "onMapReady: Map is ready");
if (mLocationPermissionGranted) {
getDeviceLocation();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
Log.d(TAG, "onCreate: Map started");
getLocationPermission();
}
private void getDeviceLocation() {
Log.d(TAG, "getDeviceLocation : get the Devices current location");
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
try {
if (mLocationPermissionGranted) {
Task location = mFusedLocationProviderClient.getLastLocation();
location.addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()) {
Log.d(TAG, "onComplete: found location");
Location currentlocation = (Location) task.getResult();
moveCamera(new LatLng(currentlocation.getLatitude(), currentlocation.getLongitude()), DEFAULT_ZOOM);
} else {
Log.d(TAG, "onComplete: current Location is null");
Toast.makeText(MapsActivity.this, "unable to find location", Toast.LENGTH_SHORT);
}
}
});
}
} catch (SecurityException e) {
Log.e(TAG, "getDeviceLocation: SecurityException: " + e.getMessage());
}
}
private void moveCamera(LatLng latLng, float zoom) {
Log.d(TAG, "moveCamera: move the Camera to lat: " + latLng.latitude + ", lng" + latLng.longitude);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
}
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
private void initMap() {
Log.d(TAG, "Init Map");
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
});
}
private void getLocationPermission() {
Log.d(TAG, "getLocationPermission");
String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
if (ContextCompat.checkSelfPermission(this.getApplicationContext(), FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this.getApplicationContext(), COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
initMap();
} else {
ActivityCompat.requestPermissions(this, permissions, LOCATION_PERMISSION_REQUEST_CODE);
}
} else {
ActivityCompat.requestPermissions(this, permissions, LOCATION_PERMISSION_REQUEST_CODE);
}
}
public void onRequestPermissionResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grandResults) {
Log.d(TAG, " onRequestPermissionResult: called");
mLocationPermissionGranted = false;
switch (requestCode) {
case LOCATION_PERMISSION_REQUEST_CODE: {
if (grandResults.length > 0) {
for (int i = 0; i < grandResults.length; i++) {
if (grandResults[i] == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = false;
Log.d(TAG, "onRequestPermissionResult: failed");
return;
}
}
Log.d(TAG, "onRequestPermissionResult: Permission granted");
mLocationPermissionGranted = true;
//initialize our Map
initMap();
}
}
}
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
}
How I connect these two with each other that the MapFragment uses the methods of MapActivity?
If I understand your problems correctly, you want to run OnMapReadyCallback related methods from activity instead of the fragment. If this is a case, you should fix your fragment like this:
public class Map_Fragment extends Fragment {
SupportMapFragment mapFragment;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_map_,container, false);
mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
if (mapFragment==null){
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
mapFragment=SupportMapFragment.newInstance();
ft.replace(R.id.map, mapFragment).commit();
}
Activity activity = getActivity();
if (activity != null && activity instanceof MainActivity) {
mapFragment.getMapAsync((MainActivity) activity);
}
// Inflate the layout for this fragment
return v;
}
}
i'm from indonesia, i want to refresh a fragment after i insert a data to it.. i have try many times to refresh a fragment. but it can't work.
please help me..
here's my code..
class MainActivity
public class MainActivity extends FragmentActivity {
public MainActivity() {
}
DatabaseReference dataBaseref;
StorageReference strRef;
TextView logout;
TabLayout tabLayout;
ViewPager viewPager;
ViewPagerAdapter viewAdapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dataBaseref = FirebaseDatabase.getInstance().getReference();
strRef = FirebaseStorage.getInstance().getReference();
tabLayout = findViewById(R.id.tab_layout_isi_menu);
viewPager = findViewById(R.id.view_pager_isi_menu);
logout = findViewById(R.id.text_logout);
viewAdapter = new ViewPagerAdapter(getSupportFragmentManager(), MainActivity.this);
viewAdapter.addFragment(new isi_list_beli(), "Beli");
viewAdapter.addFragment(new isi_list_cek(), "Cek Data");
viewPager.setAdapter(viewAdapter);
tabLayout.setupWithViewPager(viewPager);
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
logOut();
}
});
}
private void logOut() {
AuthUI.getInstance()
.signOut(MainActivity.this)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
startActivity(new Intent(MainActivity.this, LoginActivity.class));
finish();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, "" + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
#Override
protected void onResume() {
super.onResume();
}
public void onBackPressed() {
super.finish();
}
}
class isi_list_cek
public class isi_list_cek extends Fragment {
private ListView listView;
public AdapterListCek adapterListCek = null;
private ArrayList<Cek> cekArrayList;
Cursor cursor;
View view;
FloatingActionButton fab;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
adapterListCek = new AdapterListCek(getContext(), R.layout.item_in_list_barang, cekArrayList);
adapterListCek.notifyDataSetChanged();
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #NonNull Bundle savedInstanceState) {
view = inflater.inflate(R.layout.list_barang, container, false);
listView = view.findViewById(R.id.list_item_barang);
fab = view.findViewById(R.id.tambah_barang);
cekArrayList = new ArrayList<>();
adapterListCek = new AdapterListCek(getContext(), R.layout.item_in_list_barang, cekArrayList);
listView.setAdapter(adapterListCek);
cursor = fragment_input_data.sqlHelper.getData("SELECT * FROM CEK");
if(cursor.moveToFirst()){
cekArrayList.clear();
do{
int id = cursor.getInt(0);
String kode = cursor.getString(1);
String nama = cursor.getString(2);
String jumlah = cursor.getString(3);
String harga = cursor.getString(4);
byte[] gambar = cursor.getBlob(5);
cekArrayList.add(new Cek(id, kode, nama, harga, jumlah, gambar));
}while (cursor.moveToNext());
fragment_input_data.sqlHelper.close();
}
adapterListCek.notifyDataSetChanged();
listView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
return false;
}
});
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getContext(), fragment_input_data.class));
}
});
return view;
}
#Override
public void onResume() {
super.onResume();
}
}
class ViewPagerAdapter
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private Map<Integer, String> mFragmentTags;
private FragmentManager mFragmentManager;
private Context mContext;
private final List<Fragment> fragmentList = new ArrayList<>();
private final List<String> fragmentListTitle = new ArrayList<>();
public ViewPagerAdapter(FragmentManager fm, Context mContext) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
return fragmentListTitle.size();
//return 2;
}
#NonNull
#Override
public CharSequence getPageTitle(int position) {
return fragmentListTitle.get(position);
}
public void addFragment (Fragment fragment, String string){
fragmentList.add(fragment);
fragmentListTitle.add(string);
}
}
i expect when i insert some data, fragment will automatically update it's view.
call a function as: just send the new instance of present fragment that you want to recreate
replaceFragment(new YourPresentFragment());
the function can be as below:
private void replaceFragment(Fragment fragment) {
String fragmentTag = fragment.getClass().getName();
FragmentManager manager = getFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
ft.replace(R.id.fragments, fragment, fragmentTag);
ft.addToBackStack("fragments");
ft.commit();
}
this should do the job
I want to send my location information in MapFragment to MyDialog fragment. Because I want to store in database on MyDialog.
I tried bundle but I cant do it.
public class MapFragment extends Fragment implements OnMapReadyCallback {
private static final String TAG = "MapFragment";
public Double lat, lon;
GoogleMap map;
boolean isAdded = true, click;
FloatingActionButton but;
Dialog dialog;
public MapFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_map, container, false);
but = view.findViewById(R.id.showDialog);
but.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (isAdded) {
click = true;
isAdded = false;
} else {
showDialog();
isAdded = true;
}
}
private void showDialog() {
MyDialog dialog = new MyDialog();
dialog.setTargetFragment(MapFragment.this, 1);
dialog.show(getFragmentManager(), "MyDialog");
}
});
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
return view;
}
#Override
public void onMapReady(final GoogleMap googleMap) {
map = googleMap;
map.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
public void onMapClick(LatLng latLng) {
if (click == true) {
lat = latLng.latitude;
lon = latLng.longitude;
// new LatLng(lat, lon)
Log.i("on clicked location", "loc: " + new LatLng(lat, lon));
LatLng loc = new LatLng(lat, lon);
// Marker marker = map.addMarker(new MarkerOptions().position(new LatLng(lat, lon)).title("location"));
sendLocation(googleMap);
but.setImageDrawable(ActivityCompat.getDrawable(getContext(), R.drawable.ic_check));
//sending location mydialog fragment
MyDialog fragment = new MyDialog();
Bundle b = new Bundle();
b.putDouble("Lat", lat);
b.putDouble("Lon", lon);
fragment.setArguments(b);
}
}
});
}
public void sendLocation(final GoogleMap googleMap){
map = googleMap;
LatLng location= new LatLng(lat, lon);
Marker marker = map.addMarker(new MarkerOptions().position(new LatLng(lat, lon)).title("location"));
}
}
MyDialog fragment:
public class MyDialog extends DialogFragment
implements AdapterView.OnItemSelectedListener {
private static final String TAG = "MyDialog";
private Spinner spinner;
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
parent.getItemAtPosition(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
public interface OnInputSelected {
void sendInput(String input);
}
public OnInputSelected mOnInputSelected;
//widgets
private EditText mInput;
private Button mSave, mCancel;
private EditText nameSurname, address;
private Location location;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(final LayoutInflater inflater, #Nullable ViewGroup container, final Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dialog_map, container, false);
spinner = view.findViewById(R.id.addType);
ArrayAdapter<String> aa = new ArrayAdapter<>(getActivity(),
R.layout.support_simple_spinner_dropdown_item,
getResources().getStringArray(R.array.addType));
aa.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
spinner.setAdapter(aa);
spinner.setOnItemSelectedListener(this);
mSave = view.findViewById(R.id.save_action);
mCancel = view.findViewById(R.id.cancel_action);
nameSurname = view.findViewById(R.id.nameSurname);
address = view.findViewById(R.id.address);
mCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: closing dialog");
getDialog().dismiss();
}
});
mSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: capturing input.");
String nameSurname_ = nameSurname.getText().toString();
String address_ = address.getText().toString();
String addType_ = (String) spinner.getSelectedItem();
Dialog dialog = new Dialog();
String input = nameSurname_ + " " + address_ + " " + addType_;
if (!input.equals("")) {
dialog.setName_surname(nameSurname_);
dialog.setAddress(address_);
dialog.setAddress_type(addType_);
// dialog.setLocation(location);
MyDB.getInstance(getContext()).myDAO().addDialog(dialog);
Toast.makeText(getActivity(), "Dialog created. with " + nameSurname_ + " " + address_ + " " + addType_ , Toast.LENGTH_SHORT).show();
}
nameSurname.setText("");
address.setText("");
getDialog().dismiss();
}
});
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
mOnInputSelected = (OnInputSelected) getTargetFragment();
} catch (ClassCastException e) {
Log.e(TAG, "onAttach: ClassCastException : " + e.getMessage());
}
}
}
I would like to show to user the title of the marker added to a map, however none of the solutions that i've found on the web is giving anything. Unfortunately not the showInfoWindow nor selectMarker helps:(
Please see below my code:
public class DetailAnimalPlantMapFragment extends Fragment implements OnMapReadyCallback, PermissionsListener {
private MapView mapView;
private MapboxMap mapboxMapMyLocation;
PermissionsManager permissionsManager;
List<Point> positions;
LatLng[] latLng;
LatLng myLocation;
#Override
public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Mapbox.getInstance(getActivity(), getString(R.string.map_box_api));
View rootView = inflater.inflate(R.layout.fragment_ustka_object_map_mapbox, container,
false);
mapView = rootView.findViewById(R.id.mapViewMapBox);
Bundle bundle = getArguments();
Nature nature = (Nature) bundle.getSerializable("nature");
final double lat = nature.getLat();
final double lng = nature.getLng();
final String name = nature.getName();
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(MapboxMap mapboxMap) {
if(!nature.getWaypoints().isEmpty()){
positions = PolylineUtils.decode(nature.getWaypoints(),5);
latLng = new LatLng[positions.size()];
for (int i = 0; i < positions.size(); i++) {
latLng[i] = new LatLng(
positions.get(i).latitude(),
positions.get(i).longitude());
}
mapboxMap.addMarker(new MarkerOptions()
.setPosition(new LatLng(latLng[0]
.getLatitude(),latLng[0]
.getLongitude()))
.setTitle("PoczÄ…tek"));
mapboxMap.addMarker(new MarkerOptions()
.setPosition(new LatLng(latLng[latLng.length-1]
.getLatitude(),latLng[latLng.length-1]
.getLongitude()))
.setTitle("Koniec"));
mapboxMap.addPolyline(new PolylineOptions()
.add(latLng)
.color(Color.parseColor("#38afea"))
.width(5));
}
mapboxMapMyLocation = mapboxMap;
enableLocationPlugin();
CameraPosition position = new CameraPosition.Builder()
.target(new LatLng(lat,lng))
.zoom(11)
.tilt(30)
.build();
mapboxMapMyLocation.animateCamera(CameraUpdateFactory
.newCameraPosition(position), 4000);
Marker marker = mapboxMapMyLocation.addMarker(new MarkerOptions().setPosition(new LatLng(lat,lng))
.setTitle(name));
mapboxMapMyLocation.selectMarker(marker);
/*marker.showInfoWindow(mapboxMapMyLocation,mapView);*/
}
});
return rootView;
}
#Override
#SuppressWarnings( {"MissingPermission"})
public void onStart() {
super.onStart();
mapView.onStart();
}
#Override
public void onResume() {
super.onResume();
mapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onStop() {
super.onStop();
mapView.onStop();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
public void onDestroyView() {
super.onDestroyView();
mapView.onDestroy();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
#Override
public void onMapReady(MapboxMap mapboxMap) {
DetailAnimalPlantMapFragment.this.mapboxMapMyLocation = mapboxMap;
enableLocationPlugin();
}
#SuppressWarnings( {"MissingPermission"})
private void enableLocationPlugin() {
// Check if permissions are enabled and if not request
if (PermissionsManager.areLocationPermissionsGranted(getActivity())) {
LocationLayerPlugin locationLayerPlugin = new LocationLayerPlugin(mapView, mapboxMapMyLocation);
// Set the plugin's camera mode
Location location = locationLayerPlugin.getLastKnownLocation();
myLocation = new LatLng(location.getLatitude(),location.getLongitude());
locationLayerPlugin.setCameraMode(CameraMode.TRACKING_GPS);
getLifecycle().addObserver(locationLayerPlugin);
} else {
permissionsManager = new PermissionsManager(this);
permissionsManager.requestLocationPermissions(getActivity());
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
}
#Override
public void onExplanationNeeded(List<String> permissionsToExplain) {
}
#Override
public void onPermissionResult(boolean granted) {
}
}
As you can see I'm opening the mapView in a fragment, poiting to both the user's location and the object's location.