Cannot assign local value to global value - java

I am just a beginner in java/android. I was trying to pass location latitude and longitude to firebase. So I toast the message to see the value it was showing 0.0. I passed lat and long value from client.getlastlocation to the global value of lat and lon, but it is showing default value 0.0, why is this happening?
public class shopaction extends Fragment implements CompoundButton.OnCheckedChangeListener{
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
Location location;
GoogleApiClient googleApiClient;
FusedLocationProviderClient client;
private String mParam1;
private String mParam2;
String s;
Switch action;
public double lat,lon;
private OnFragmentInteractionListener mListener;
public shopaction() {
}
public static shopaction newInstance(String param1, String param2) {
shopaction fragment = new shopaction();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_shopaction, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
action = (Switch) view.findViewById(R.id.action);
action.setOnCheckedChangeListener(this);
client = LocationServices.getFusedLocationProviderClient(getActivity());
Button button=(Button)view.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(),new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
}
client.getLastLocation().addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
lat=location.getLatitude();
lon=location.getLongitude();
}
});
}
});
client.getLastLocation().addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
lat=location.getLatitude();
lon=location.getLongitude();
}
});
Toast.makeText(getActivity(),lat+"",Toast.LENGTH_LONG).show();
FirebaseDatabase firebaseDatabase=FirebaseDatabase.getInstance();
DatabaseReference databaseReference=firebaseDatabase.getReference();
databaseReference.child("shop").child("location").setValue(lat);
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(action.isChecked())
{
Toast.makeText(getActivity(),"Your shop is open",Toast.LENGTH_LONG).show();
action.setText("open");
s="open";
}
else
{
Toast.makeText(getActivity(),"Your shop is closed",Toast.LENGTH_LONG).show();
action.setText("close");
s="close";
}
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}

The problem is that getLastLocation() returns a Task which then operates asynchronously. The location data are not available until the success listener call-back has actually been called. Meanwhile, your code proceeds to display a Toast using the current (default) values of 0 for lat and lon.
One way to fix this is to have your success listener callback display the toast, rather than your main code. So instead of this:
client.getLastLocation().addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
lat=location.getLatitude();
lon=location.getLongitude();
}
});
Toast.makeText(getActivity(),lat+"",Toast.LENGTH_LONG).show();
// Firebase update code that depends on location data
use this:
client.getLastLocation().addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
lat=location.getLatitude();
lon=location.getLongitude();
Toast.makeText(getActivity(),lat+"",Toast.LENGTH_LONG).show();
// Firebase update code that depends on location data
}
});

Related

How to retrieve data from firebase for if else condition in java

I tried to make a different condition based on firebase database data. for example if the "Status" field data has value "Aktif" then the marker color will change to blue and when the "Status" value change into "Nonaktif" then the marker color will change into red. I already to use this code, but when tried to run it have the problem "error: incompatible types: cannot be converted to Context".
So how can i fix this problem? i will put the database structure here Firebase structure
private NavigationView navigationView;
private TextView namapengguna, emailpengguna;
private ImageView imageView2;
private View headerView;
DrawerLayout drawerLayout;
MapView mapView;
public MapboxMap mapboxMap;
private LocationManager manager;
private PermissionsManager permissionsManager;
private LocationComponent locationComponent;
Marker myMarker;
private final int MIN_TIME = 1000;
private final int MIN_DISTANCE = 1;
private FirebaseUser user;
private DatabaseReference root;
private StorageReference reference;
private String userID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Mapbox.getInstance(this,"pk.eyJ1IjoiaGFuZGlrYW1lZGlhbWFydGEiLCJhIjoiY2ttb2o1MWQ2MHp5cDJ3bHcyM3RkN2VvdiJ9.VOmbzomxo3nMMWLcmF2l0g");
setContentView(R.layout.activity_dashboard);
manager = (LocationManager) getSystemService(LOCATION_SERVICE);
mapView = (MapView)findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
drawerLayout = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
headerView = navigationView.getHeaderView(0);
namapengguna = (TextView) headerView.findViewById(R.id.namalengkap);
emailpengguna = (TextView) headerView.findViewById(R.id.emailpengguna);
imageView2 = findViewById(R.id.imageview2);
imageView2 = (ImageView) headerView.findViewById(R.id.imageview2);
user = FirebaseAuth.getInstance().getCurrentUser();
root = FirebaseDatabase.getInstance().getReference();
reference = FirebaseStorage.getInstance().getReference();
userID = user.getUid();
root.child("Users").child(userID).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
User userProfile = snapshot.getValue(User.class);
if (userProfile != null) {
String fullName = userProfile.fullname;
String email = userProfile.email;
namapengguna.setText(fullName);
emailpengguna.setText(email);
if (snapshot.hasChild("image")){
String image2 =snapshot.child("image").getValue().toString();
Picasso.get().load(image2).into(imageView2);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(Dashboard.this, "Terjadi Kesalahan Pada Database", Toast.LENGTH_LONG).show();
}
});
}
public void ClickMenu(View view) {
openDrawer(drawerLayout);
}
public static void openDrawer(DrawerLayout drawerLayout) {
drawerLayout.openDrawer(GravityCompat.START);
}
public void ClickLogo(View view) {
closeDrawer(drawerLayout);
}
public static void closeDrawer(DrawerLayout drawerLayout) {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
}
}
public void ClickHome(View view) {
recreate();
}
public void ClickUtama(View view) {
redirectActivity(this, Utama.class);
}
public void ClickAboutUs(View view) {
redirectActivity(this, AboutUs.class);
}
public void ClickLogout(View view) {
logout(this);
}
public static void logout(Activity activity) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle("Logout");
builder.setMessage("Are you sure want to logout?");
builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
activity.finishAffinity();
System.exit(0);
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
}
public static void redirectActivity(Activity activity, Class aClass) {
Intent intent = new Intent(activity, aClass);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(intent);
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
return false;
}
#Override
public void onMapReady(#NonNull final MapboxMap mapboxMap) {
this.mapboxMap = mapboxMap;
root.child("otoped").addValueEventListener(new ValueEventListener() {
Query q = FirebaseDatabase.getInstance().getReference("otoped").orderByChild("Status").equalTo("0");
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
MyLocation location = dataSnapshot.getValue(MyLocation.class);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng loc = new LatLng(latitude,longitude);
if (q != null){
myMarker = mapboxMap.addMarker(new MarkerOptions().icon(IconFactory.getInstance(this).fromResource(R.drawable.ic_markerbiru)));
myMarker.setPosition(loc);
}else{
myMarker = mapboxMap.addMarker(new MarkerOptions().icon(IconFactory.getInstance(this).fromResource(R.drawable.markerblue)).position(loc).title("Otoped1"));
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
mapboxMap.setStyle(Style.MAPBOX_STREETS, new Style.OnStyleLoaded() {
#Override
public void onStyleLoaded(#NonNull Style style) {
enableLocationComponent(style);
Drawable drawable = ResourcesCompat.getDrawable(getResources(),R.drawable.ic_baseline_location_on_24,null);
Bitmap mBitmap = BitmapUtils.getBitmapFromDrawable(drawable);
}
});
}
private void enableLocationComponent(#NonNull Style loadedMapStyle) {
if (PermissionsManager.areLocationPermissionsGranted(Dashboard.this)){
LocationComponent locationComponent = mapboxMap.getLocationComponent();
locationComponent.activateLocationComponent(
LocationComponentActivationOptions.builder(Dashboard.this, loadedMapStyle).build());
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED){
return;
}
locationComponent.setLocationComponentEnabled(true);
locationComponent.setCameraMode(CameraMode.TRACKING);
locationComponent.setRenderMode(RenderMode.COMPASS);
} else {
permissionsManager = new PermissionsManager((PermissionsListener) this);
permissionsManager.requestLocationPermissions(this);
}
}
#Override
public void onResume() {
super.onResume();
mapView.onResume();
}
#Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
#Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
#Override
public void onPause() {
super.onPause();
closeDrawer(drawerLayout);
mapView.onPause();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
#Override
public void onLocationChanged(#NonNull Location location) {
if (location != null){
saveLocation(location);
}else {
Toast.makeText(this, "No Location", Toast.LENGTH_SHORT).show();
}
}
private void saveLocation(Location location) {
root.child("otoped").setValue(location);
}
}
I Got problem when tried to edit this code
#Override
public void onMapReady(#NonNull final MapboxMap mapboxMap) {
this.mapboxMap = mapboxMap;
root.child("otoped").addValueEventListener(new ValueEventListener() {
Query q = FirebaseDatabase.getInstance().getReference("otoped").orderByChild("Status").equalTo("0");
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
MyLocation location = dataSnapshot.getValue(MyLocation.class);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng loc = new LatLng(latitude,longitude);
if (q != null){
myMarker = mapboxMap.addMarker(new MarkerOptions().icon(IconFactory.getInstance(this).fromResource(R.drawable.ic_markerbiru)));
myMarker.setPosition(loc);
}else{
myMarker = mapboxMap.addMarker(new MarkerOptions().icon(IconFactory.getInstance(this).fromResource(R.drawable.markerblue)).position(loc).title("Otoped1"));
}
}

RecyclerView disappearing after switching between fragments on a particular Activity

The problem I have been facing with the development is that there is a recyclerview inside my fragment which gets disappeared after I switch between two fragments on a particular activity. On the first time when the fragment loads everything works fine but afterwards I don't understand what goes wrong. I had tried to refer to various ways that people had posted over github like notifyDatasetChanged, etc. But nothing seems to work. I would appreciate if someone could help me out with this issue.
So here are my classes.
The ProfileFragment.java :
public class ProfileFragment extends Fragment {
FirebaseAuth firebaseAuth;
FirebaseUser user;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
StorageReference storageReference;
RecyclerView itemRecycler;
List<ModelProfile> modelProfiles;
AdapterProfile adapterProfile;
String storagePath= "Users_Profile_Cover_Image/-";
ImageView avatarIv,dp;
CardView card,cardArrow;
TextView nameTv, emailTv, phoneTv;
Button logout,update;
ExtendedFloatingActionButton fab;
ProgressDialog pd;
//..
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View view= inflater.inflate(R.layout.fragment_profile, container, false);
firebaseAuth = FirebaseAuth.getInstance();
user= firebaseAuth.getCurrentUser();
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference("Users");
storageReference= getInstance().getReference();
loadItems();
return view;
}
private void loadItems() {
//Problem could be here
GridLayoutManager layoutManager= new GridLayoutManager(getContext(),3);
itemRecycler.setHasFixedSize(true);
itemRecycler.setLayoutManager(layoutManager);
itemRecycler.setVisibility(View.VISIBLE);
CollectionReference ref =FirebaseFirestore.getInstance().collection("All_Posts");
com.google.firebase.firestore.Query query = ref.whereEqualTo("uid",uid);
FirestoreRecyclerOptions<ModelProfile> options = new FirestoreRecyclerOptions.Builder<ModelProfile>()
.setQuery(query,ModelProfile.class).build();
adapterProfile = new AdapterProfile(options,getActivity());
itemRecycler.setAdapter(adapterProfile);
adapterProfile.startListening();
query.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot value,
#Nullable FirebaseFirestoreException e) {
if (e != null) {
return;
}
assert value != null;
Log.i("Size",String.valueOf(value.getDocuments().size()));
if (value.getDocuments().size() > 0) { // List is populated
card.setVisibility(View.GONE);
cardArrow.setVisibility(View.GONE);
} else { // List is empty
card.setVisibility(View.VISIBLE);
cardArrow.setVisibility(View.VISIBLE);
}
}
});
}
//
// #Override
// public void onStart() {
// super.onStart();
// adapterProfile.startListening();
// }
//
//
//
// #Override
// public void onStop() {
// super.onStop();
// adapterProfile.stopListening();
// }
#Override
public void onResume() {
super.onResume();
adapterProfile.startListening();
}
}
Adapter:-
public class AdapterProfile extends FirestoreRecyclerAdapter<ModelProfile,AdapterProfile.MyHolder> {
Context context;
public String im;
public AdapterProfile(#NonNull FirestoreRecyclerOptions<ModelProfile> options, Activity Context) {
super(options);
context = Context;
}
#Override
protected void onBindViewHolder(#NonNull MyHolder holder, int position, #NonNull ModelProfile model) {
String uid = model.getUid();
String uEmail =model.getuEmail();
}
#NonNull
#Override
public MyHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
//..
}
class MyHolder extends RecyclerView.ViewHolder{
//..
}
Activity on which Fragment switching takes place
public class LandingActivity extends AppCompatActivity {
FirebaseAuth firebaseAuth;
DatabaseReference userDbRef;
FirebaseUser user;
String uid,dp;
ChipNavigationBar chipNavigationBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_landing);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,new InventoryFragment()).commit();
bottomMenu();
}
private void bottomMenu() {
chipNavigationBar.setOnItemSelectedListener(new ChipNavigationBar.OnItemSelectedListener() {
//problem could be here as well.........
#Override
public void onItemSelected(int i) {
Fragment fragment=null;
switch(i) {
case R.id.bottom_nav_2:
fragment = new CltFragment();
break;
case R.id.bottom_nav_3:
fragment = new MaceFragment();
break;
case R.id.bottom_nav_profile:
fragment = new ProfileFragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,fragment).commit();
}
});
}
private void checkUserStatus()
{
FirebaseUser user= firebaseAuth.getCurrentUser();
if(user !=null)
{
uid=user.getUid();
}
else
{
startActivity(new Intent(LandingActivity.this,MainActivity.class));
finish();
}
}
#Override
public void onResume() {
//Problem could be here
super.onResume();
Intent intent = getIntent();
String frag = "";
if(intent.hasExtra("frag")) {
frag = intent.getExtras().getString("frag");
}
else
{
//..
}
switch(frag)
{
//..
case "ProfileFragment":
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new ProfileFragment()).commit();
chipNavigationBar.setItemSelected(R.id.bottom_nav_profile,true);
break;
}
}
}
Thanks for having looked at my Problem!
Try using this
getSupportFragmentManager().beginTransaction().add(R.id.fragment_container,new InventoryFragment()).commit();
Instead of this
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,new InventoryFragment()).commit();

Android: How can I add Google map to a ViewPager?

I want to make an app that has on the main screen a ViewPager with a map and a profile section. Therefore, for position = 0 in the ViewPager, there is the map and for position = 1, there is the profile.
For each one of those two "sections" on the main screen, I have two activities: the map.xml with the MapActivity.java and the profile.xml with Profile.java. Both of those are inflated in the EnumFrag java class, depending on the position ( you see there an if ).
I have two issues:
The first one is that when I try to slide left or right, the map moves, not the ViewPager to the next slide. I tried to put a shape on the edge, but it is not working like the slide gesture is passing through the shape. Any help here, please?
The second is related to the first one, the MapActivity.java class is not even running because onCreate is not running (I put a Toast there so display something and nothing happened). Any help, please? (I create the map class object).
map.xml contains a simple fragment with an id of map.
MapActivity.java:
public class MapActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap map;
private Location me;
private FusedLocationProviderClient fusedLocationProviderClient;
private static final int REQUEST_CODE = 101;
#Override
protected void onCreate(Bundle savedInstanceState) {
Toast.makeText(this, "hey din onCreate", Toast.LENGTH_SHORT).show();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
getLastLocation();
}
private void getLastLocation() {
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_CODE);
return;
}
Toast.makeText(getApplicationContext(), "hey...", Toast.LENGTH_SHORT).show();
Task<Location> task = fusedLocationProviderClient.getLastLocation();
task.addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if(location != null){
me = location;
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(MapActivity.this);
}
else
Toast.makeText(getApplicationContext(), "Deschide-ti locatia", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
MapStyleOptions mapStyleOptions= MapStyleOptions.loadRawResourceStyle(this,R.raw.map_style);
googleMap.setMapStyle(mapStyleOptions);
LatLng point = new LatLng(me.getLatitude(),me.getLongitude());
MarkerOptions markerOptions = new MarkerOptions().position(point).title("Me");
googleMap.animateCamera(CameraUpdateFactory.newLatLng(point));
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(point,16));
googleMap.addMarker(markerOptions);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getLastLocation();
}
}
}
}
Profile.java
public class Profile extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
EditText username = findViewById(R.id.usernameProfile);
username.setText(MainScreen.getUsername());
}
}
EnumFragment.java
public class EnumFragments extends PagerAdapter {
private Context context;
public EnumFragments(Context context) {
this.context = context;
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view;
MapActivity mapActivity = new MapActivity();
switch (position){
case 0:
view = layoutInflater.inflate(R.layout.activity_profile,null);
break;
default:
view = layoutInflater.inflate(R.layout.activity_map,null);
break;
}
ViewPager viewPager = (ViewPager)container;
viewPager.addView(view);
return view;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
ViewPager viewPager = (ViewPager)container;
View view = (View) object;
viewPager.removeView(view);
}
#Override
public int getCount() {
return 2;
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == object;
}
}
MainScreen.java
public class MainScreen extends AppCompatActivity {
private static String username;
private ViewPager viewPager;
private EnumFragments enumFragments;
private static int userID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
Bundle extras = getIntent().getExtras();
userID = extras.getInt("userID");
username = extras.getString("username");
viewPager = findViewById(R.id.mainSlider);
EnumFragments enumFragments = new EnumFragments(this);
viewPager.setAdapter(enumFragments);
}
public static int getUserID() {
return userID;
}
public static String getUsername() {
return username;
}
#Override
public void onBackPressed() {
//Nothing
}
}
Why you don't add the MapActivity into the MainScreen Activity. You even don't use the MapActivity in your PagerAdapter class. I would make an other attribute in the constructor of your PagerAdapter, after this :
private MapActivity current;
public EnumFragments(MapActivity map_activity)
{
this.current = map_activity;
}
then I would put a getter method in the map_activity, wich returns a view, where you can see the current GoogleMap or other features.
Your problem is that you don't use the new MapActivity...
I hope that may helps you

Work with BroadcastReceiver in many fragments

I working with a PDA that has a laser scanner. For that I'm working with BroadcastReceiver in many fragment. I have one activity that has a BottomNavigationView to switch between three fragments. I'm using BroadcastReceiver like this :
package com.example.package.fragments;
public class MyFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
private final static String SCAN_ACTION = "scan.rcv.message";
ScanDevice sm;
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//Doing my work
}
};
public MyFragment () {
// Required empty public constructor
}
public static MyFragment newInstance(String param1, String param2) {
CarteGriseFragment fragment = new CarteGriseFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
sm = new ScanDevice();
IntentFilter filter = new IntentFilter();
filter.addAction(SCAN_ACTION);
getContext().registerReceiver(mReceiver, filter);
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_carte_grise, container, false);
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onResume() {
super.onResume();
sm = null;
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mReceiver);
}
#Override
public void onPause() {
super.onPause();
sm = null;
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mReceiver);
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
sm = null;
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mReceiver);
}
#Override
public void onDestroy() {
super.onDestroy();
sm = null;
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mReceiver);
}
#Override
public void onDestroyView() {
super.onDestroyView();
sm = null;
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mReceiver);
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
The problem is that, when I move to another fragment, BroadcastReceiver of the first fragment keep working in the second. In fact, when I scan something while being in the second fragment the BroadcastReceiver of the first fragment is called. I searched for many solutions, as you can see in the code above, I tried to unregister the BroadcastReceiver, but not working.
The code of the other fragment is similar to the code above.
I guess the problem is in navigation view all fragments stays in a visible state, hence onPause is not called. you can try to unsubscribe in this method setUserVisibleHint when isVisibleToUser = false
Maybe you can use RxJava.
You say "I have one activity".
Use RxJava like this.
You need to just one BroadcastReceiver in your activity.Listen it when triggered "onReceive" function then you send event with RxJava and listen this event in your fragments.

How to download attached file from https web sites with using Android Studio?

I want to integrate my app with Microsoft Office 365 Outlook to be able to manage user's account. The user may access his account and may see email without a problem but when the user wants to download attached files program closes immediately.
I tried almost every suggestion on Stack Overflow which exists in other posts and couldn't manage to find the true solution. I also researched about outlook account management for Android and couldn't find helpful information. So I need some suggestion and solutions to handle this.
public class hiddenNetwork extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
private WebView mWebview;
ProgressDialog prDialog;
public hiddenNetwork() {
// Required empty public constructor
}
private Handler handler = new Handler(){
#Override
public void handleMessage(Message message) {
switch (message.what) {
case 1:{
webViewGoBack();
}break;
}
}
};
public static hiddenNetwork newInstance(String param1, String param2) {
hiddenNetwork fragment = new hiddenNetwork();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
int count=0;
private void webViewGoBack(){
count++;
mWebview.goBack();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_announcement, container, false);
mWebview = (WebView)view.findViewById(R.id.webView);
CookieManager cookieManager = CookieManager.getInstance();
WebSettings webSettings = mWebview.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebview.setDownloadListener(new DownloadListener() {
#Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(url));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed!
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "Name of your downloadble file goes here, example: Mathematics II ");
DownloadManager dm = (DownloadManager)getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
dm.enqueue(request);
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); //This is important!
intent.addCategory(Intent.CATEGORY_OPENABLE); //CATEGORY.OPENABLE
intent.setType("*/*");//any application,any extension
}
});
mWebview.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading (WebView view, String url) {
if (url.endsWith(".pdf")) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
// if want to download pdf manually create AsyncTask here
// and download file
return true;
}
return false;
}
#Override public void onReceivedError(WebView view, WebResourceRequest request,
WebResourceError error) {
super.onReceivedError(view, request, error);
}
});
mWebview.loadUrl("https://login.microsoftonline.com");
return view;
}
public void myOnKeyDown(int key_code){
//do whatever you want here
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
}

Categories

Resources