Sensor_Service cannont be resolved as a variable - java

I'm getting an error on sensor service. I'm pretty sure that's the right syntax, unless I'm missing something. Just need that part for the accelerometer. Greatly appreciate if you could post thoughts.
public class AskQuestions extends Fragment {
private SensorManager mSensorManager;
private Sensor mAccelerometer;
private ShakeDetector mShakedetector;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_questions, container, false);
//Error
mSensorManager = getSystemService(SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mShakedetector = new ShakeDetector(new OnShakeListener() {
#Override
public void onShake() {
// TODO Auto-generated method stub
handleNewAnswer();
}
});
return rootView;
}
#Override
public void onResume(){
super.onResume();
mSensorManager.registerListener(mShakedetector, mAccelerometer,
SensorManager.SENSOR_DELAY_UI);
}
#Override
public void onPause(){
super.onPause();
mSensorManager.unregisterListener(mShakedetector);
}
private void handleNewAnswer() {
if(makeMethink == true) {
result = answer.makeMeThink();
}else if(WhatsTheAnswer == true){
result = answer.whatsTheAnswer();
} else if (inspireMe){
result = answer.inspireQuotes();
}
displayAnswer.setText(result);
}
}

Use this instead:
mSensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
The problem is the code you used only works in a subclass of Context (e.g. Activity). Fragment is not a subclass of Context, so you have to get an object of that type in order to get the system service. Luckily, in a Fragment, you can easily get the container Activity with getActivity().
SENSOR_SERVICE is a constant that is defined in Context, so you have to write Context.SENSOR_SERVICE whenever you use it from outside a subclass of Context.

Related

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.

OnClick not triggered inside Fragment

Got two empty Activites(A and B), which just hold two fragments inside ViewPager of Activity A.
I do not have code errors, everything seems fine.
When I lunch my app and click on button, nothing happens.I was trying just to log something, but still nothing is happening.
I am using ButterKnife, and so far everything was perfect.I got almost same Fragment and it is performing fine, but OnClick inside Fragment B is not working.I tried to add some more OnClick methods, but none of them worked for me.XML looks good,looks almost same as fragment A.
Fragment B is not complex, it just three TextViews and Button.
Here is code for my fragment B:
public class ForgotPasswordFragmentComplete extends BaseFragment
implements BaseView {
private Realm realm;
private Email model;
#Bind(R.id.btn_resend)
AppCompatButton resendEmail;
#Inject
ForgotPasswordPresenter presenter;
#OnClick(R.id.btn_resend)
public void resendButton() {
Log.d("ResendOnclick", "Checking OnClickMethod ");
Realm realm2 = getRealm();
RealmQuery<Email> queryUserResend = realm2.where(Email.class);
Email resultResend = queryUserResend.findFirst();
ForgotPasswordPayload forgotPayload = new ForgotPasswordPayload(resultResend.getUsername());
this.presenter.subscribe(forgotPayload);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DaggerForgotPasswordCompletedComponent.builder()
.applicationComponent(
((AndroidApplication) getActivity().getApplication()).getApplicationComponent())
.forgotPasswordCompletedModule(new ForgotPasswordCompletedModule())
.build()
.inject(this);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
protected void onCreateViewWidgetInitialization(View view) {
super.onCreateViewWidgetInitialization(view);
}
#Override
public void onStart() {
super.onStart();
getEmail();
}
public void getEmail(){
Realm realm = getRealm();
RealmQuery<Email> queryUser = realm.where(Email.class);
Email result1 = queryUser.findFirst();
resendEmailTxt = (AutoResizeTextView) getView().findViewById(R.id.resend_user_email);
if (resendEmailTxt != null) {
this.resendEmailTxt.setText(result1.getUsername());
}
}
#Override
public void onDestroy() {
super.onDestroy();
realm.close();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_forgot_password_fragment_complete, container, false);
}
#Override
protected int getFragmentLayoutId() {
return R.layout.fragment_forgot_password_fragment_complete;
}
You need to bind the fragment's view object before you can use it. Try putting the following code inside onCreateView() :
View rootView = inflater.inflate(R.layout.fragment_forgot_password_fragment_complete, container, false);
ButterKnife.bind(this, rootView);
return rootView;

How to create separate class with sensor results

I have w problem with simple code: In mainActivity i need check if sensor for example Light sensor is available on phone, and if is available i need to reed and show the results of this senson on screen, but code responsible for read data from sensor must be in separate class. I wrote simple code, but it doesn't work. When i run this code, my phone show me only : "Light level: 0.0". I'm beginner in programming so please help me..
Main class:
public class MainActivity extends Activity {
LightSensor mLightSensor = null;
protected SensorManager mSensorManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView wyswietl = (TextView)findViewById(R.id.res);
mLightSensor = new LightSensor();
mSensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
if (mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT) != null){
LightSensor lS = new LightSensor();
wyswietl.setText("Light level: " + Float.toString(lS.lux));
}
else{
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onResume(){
super.onResume();
mLightSensor.register();
}
#Override
protected void onPause(){
super.onPause();
mLightSensor.unregister();
}
}
and LightSensor class:
public class LightSensor implements SensorEventListener {
SensorManager mSensorManager;
Sensor lightManager;
public float lux;
public Context context;
public void onCreateLight(Context context){
this.context = context;
mSensorManager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE);
lightManager = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
lux = event.values[0];
}
public void register(){
mSensorManager.registerListener(this, lightManager, SensorManager.SENSOR_DELAY_NORMAL);
}
public void unregister(){
mSensorManager.unregisterListener(this);
}
}
I haven't tested it, but you could possibly make a new method in your LightSensor class to return the lux variable to the main class
Something like:
public float getLux(){
return lux;
}
and then in your "MainActivity" class you can call
float newLux = mLightSensor.getLux();
If it doesn't work I might have a slightly more complex solution.
You never call mLightSensor.onCreateLight();
How about changing onCreateLight to be your LightSensor class' constructor. That would solve the problem and not require you to remember to call onCreateLight.
public LightSensor(Context context){
this.context = context;
mSensorManager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE);
lightManager = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
}

Getter returning 0 when called from other class

I'm beginner to Android and Java, and i just saw some videos of using getter and setter method in java which worked well when i used the getter and setter method in same class. But when i set the position of an image from main class using setter method and try to retrieve it from my fragment class using getter method its returning 0. there was a similar question asked in stackoverflow which i didn't understand. Please help me out..
My main class:
public class Login_Register extends Activity implements OnClickListener {
Login login = new Login();
Register register = new Register();
ImageButton LoginB;
ImageButton RegisterB;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login_register);
FragmentManager fmanager = getFragmentManager();
LoginB = (ImageButton) findViewById(R.id.login_button);
RegisterB = (ImageButton) findViewById(R.id.Reg_button);
LoginB.setOnClickListener(this);
RegisterB.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Positions pos = new Positions();
pos.setLIpos(LoginB.getY());
pos.setRIpos(RegisterB.getY());
FragmentTransaction transaction = fmanager.beginTransaction();
switch (v.getId()) {
case R.id.login_button:
transaction.add(R.id.Parent, login, "Loginf");
transaction.addToBackStack("Login");
break;
case R.id.Reg_button:
transaction.add(R.id.Parent, register, "registerf");
transaction.addToBackStack("registerf");
break;
default:
break;
}
transaction.commit();
// TODO Auto-generated method stub
}
}
My fragment class:
public class Login extends Fragment implements OnGlobalLayoutListener {
EditText UN, Pass;
View loginimage, loginusing, loginlayout;
// Login_Register Lg=new Login_Register();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View login = inflater.inflate(R.layout.login, container, false);
// TODO Auto-generated method stub
UN = (EditText) login.findViewById(R.id.UsernameL);
Pass = (EditText) login.findViewById(R.id.PassswordL);
loginimage = login.findViewById(R.id.LoginImage);
loginusing = login.findViewById(R.id.loginusing);
loginlayout = login.findViewById(R.id.LoginLayout);
loginimage.getViewTreeObserver().addOnGlobalLayoutListener(this);
UN.getBackground().setAlpha(50);
Pass.getBackground().setAlpha(50);
Positions poss=new Positions();
float f=poss.getLIpos();
ObjectAnimator.ofFloat(loginusing, View.ALPHA, 0,1).setDuration(1000).start();
return login;
}
}
Class with setter and getter methods:
public class Positions {
private float LIpos=0;
private float RIpos=0;
public Positions() {
// TODO Auto-generated constructor stub
}
public float getLIpos() {
Log.i("allalalla", ""+LIpos);
return LIpos;
}
public void setLIpos(float lIpos) {
LIpos = lIpos;
}
public float getRIpos() {
return RIpos;
}
public void setRIpos(float rIpos) {
RIpos = rIpos;
}
}
Before getting the float you instantiate your class. That creates a default class with floats initialized to 0.
Positions poss=new Positions();
float f=poss.getLIpos();
If you want to save the floats between different instances of this class then make the floats static:
private static float LIpos;
private static float RIpos;
Alternatively you can preserve a reference to the instance where you save the floats and pass it your fragment, or your fragment could fetch that instance from your activity directly:
public Position pos;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
#Override
public void onClick(View v) {
pos = new Positions();
...
}
Then in your fragment fetch the position element and get the floats:
#Override
public void onActivityCreated(Bundle savedInstanceState) {
...
float LIpos = ((Login_Register)getActivity()).pos.getLIpos();
...
}
I think there is a confusion between the notion of a class and an instance. A class is a simple contract or definition if you will, of a designed object in terms of attributes and functionality. An instance is the real active object, the one that you apply operations on during runtime. Now when you write:
Position pos = new Position();
In the heap memory it is allocated the memory for the particular instance you point to by the pos reference. If in another place you type:
Position poss = new Position();
It crates one more instance of the class Position which is referenced by poss. The poss and pos have nothing to do with each other and their internal attributes may have totally unrelated values. I believe this explains why you cannot see the same attribute value for different instances.
As for how to deal with this, #user3249477 gave some options from which i recommend the second.
You are doing in wrong way. You are creating an instance of Position class in both Activity and Fragment.
Try to create an method inside Fragment which will receive position object which you have been set inside activity like below:
Your activity onClick
#Override
public void onClick(View v) {
Positions pos = new Positions();
pos.setLIpos(LoginB.getY());
pos.setRIpos(RegisterB.getY());
FragmentTransaction transaction = fmanager.beginTransaction();
switch (v.getId()) {
case R.id.login_button:
transaction.add(R.id.Parent, login, "Loginf");
transaction.addToBackStack("Login");
login.setImagePosition(pos);
break;
case R.id.Reg_button:
transaction.add(R.id.Parent, register, "registerf");
transaction.addToBackStack("registerf");
register.setImagePosition(pos);
break;
default:
break;
}
transaction.commit();
// TODO Auto-generated method stub
}
Your Fragment
class Login extends Fragment implements OnGlobalLayoutListener {
EditText UN, Pass;
View loginimage, loginusing, loginlayout;
// Login_Register Lg=new Login_Register();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View login = inflater.inflate(R.layout.login, container, false);
// TODO Auto-generated method stub
UN = (EditText) login.findViewById(R.id.UsernameL);
Pass = (EditText) login.findViewById(R.id.PassswordL);
loginimage = login.findViewById(R.id.LoginImage);
loginusing = login.findViewById(R.id.loginusing);
loginlayout = login.findViewById(R.id.LoginLayout);
loginimage.getViewTreeObserver().addOnGlobalLayoutListener(this);
UN.getBackground().setAlpha(50);
Pass.getBackground().setAlpha(50);
ObjectAnimator.ofFloat(loginusing, View.ALPHA, 0,1).setDuration(1000).start();
return login;
}
public void setImagePosition(Positions pos){
Positions poss=pos;
float f=poss.getLIpos();
}
}

Categories

Resources