I have GPS listener class AppLocationListener that has a parent activity GPSSensorActivity (not shown below).
I'm trying to access AppLocationListener from another class QuestionSearch by using AppLocationListener searchLL = new AppLocationListener(); searchLL.parentActivity = this; but using this gives a type mismatch between QuestionSearch and GPSSensorActivity. .
Is this because it's not possible to access classes that have parent activities? How can I access AppLocationListener. QuestionSearch is something I've added on to existing code that isn't my original code, I'm trying to I am new to java and don't fully understand passing data and linking classes/methods yet.
// AppLocationListener class
import java.util.ArrayList;
...
public class AppLocationListener implements LocationListener {
public GPSSensorActivity parentActivity;
public ArrayList<GeoPoint> pointList;
public void onLocationChanged(Location location) {
}
public void onProviderDisabled(String s) {
}
public void onProviderEnabled(String s) {
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
}
// QuestionSearch class
import java.util.ArrayList;
...
public class QuestionSearch extends Activity {
private static final long MINIMUM_DISTANCECHANGE_FOR_UPDATE = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATE = 5000; // in Milliseconds
private LocationManager locationManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quizmap);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
AppLocationListener searchLL = new AppLocationListener();
searchLL.parentActivity = this;
ArrayList<GeoPoint> pointList = new ArrayList<GeoPoint>();
...
// add these points to the list
pointList.add(gMapPoint);
pointList.add(gMapPoint2);
pointList.add(gMapPoint3);
// now set up the location manager and listener
searchLL.pointList = pointList;
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATE,
MINIMUM_DISTANCECHANGE_FOR_UPDATE,
searchLL
);
}
}
To be able to pass this in searchLL.parentActivity = this; your QuestionSearch should be GPSSensorActivity or should extend it.
Is this because it's not possible to access classes that have parent activities?
No, it has nothing to do with it, it's a pure Java matter - just pass right classes where they are expected.
Related
I am new user of android studio. I am using priority in manifest file and all required permissions but I do not know how can I use result in main activity, help me out.
public abstract class SmsBroadcastReceiver extends BroadcastReceiver {
protected abstract void onSmsReceived(SmsMessage smsMessage);```
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pduObjectList = (Object[]) bundle.get("pdus");
if (pduObjectList != null) {
for (Object pduObject : pduObjectList) {
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pduObject);
onSmsReceived(smsMessage);
}
}
}
}
}
The abstract keyword is a non-access modifier, used for classes and methods:
Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class).
Abstract method: can only be used in an abstract class, and it does not have a body. The body is provided by the subclass (inherited from).
In your activity:
public class MyActivity extends Activity {
private smsReceiver SmsBroadcastReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_one_position);
smsReceiver = new SmsBroadcastReceiver() {
// this code is call asyncrously from the receiver
#Override
protected void onSmsReceived() {
// Add your activty logic here
}
};
}
#Override
protected void onPause() {
super.onPause();
this.unregisterReceiver(this.smsReceiver);
}
}
One easy way is by using static variables.
On the MainActivity add the following:
public class MainActivity extends AppCompatActivity{
public static SmsMessage result;
//...
}
Then, add the following line MainActivity.result = smsMessage to the code you provided just after you get the message.
Then you can use the variable result in any part of the MainActivity (also by calling MainActivity.result you have the value of the variable in any part of your code).
Just be careful, static variables are defined as null before any assignment.
Automatic SMS Verification with the SMS Retriever API used so this is easily getting in SMS,So there was no problem and No permission is needed
https://developers.google.com/identity/sms-retriever/overview
This is a part of my activity class,
public class StatusActivity extends AppCompatActivity {
private boolean cFlag = false;
public boolean getFlag() { return cFlag; }
public void setFlag(boolean cFlag) {
this.cFlag = cFlag;
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,
android.R.id.text1, messages);
ListView listView = findViewById(android.R.id.list);
listView.setAdapter(adapter);
adapters.add(adapter);
Button btn = findViewById(R.id.btnCustomerCheckIn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setFlag(true);
cFlag = getFlag();
Intent intent = new Intent(StatusActivity.this, MainActivity.class);
Toast.makeText(StatusActivity.this, "customer checked in",
Toast.LENGTH_LONG).show();
startActivity(intent);
}
});
}
this is a part of another class named as position
public class Position {
StatusActivity statusactivity = new StatusActivity();
public boolean ccflag = statusactivity.getFlag();
statusactivity.setFlag(false);
}
when i am calling
statusactivity.setFlag(false);
it is showing an error. couldn't recognize that what is the error that i am getting. but
statusactivity.getFlag();
is working properly. any help is appreciated
StatusActivity statusactivity = new StatusActivity();
This is totally wrong because you are trying to create a new Instance of activity.
If you want to use "setFlag" method from other activity then you must create a static method inside StatusActivity so you can access using directly StatusActivity.
And If you want to call from any fragment of this activity then please get an instance of this activity by the cast from "getActivity()" to StatusActivity and use that instance for call "setFlag" or "getFlag" method.
You can implement like below in Activity.
private static boolean cFlag = false;
public static boolean getFlag() {
return cFlag;
}
public static void setFlag(boolean cFlag) {
StatusActivity.cFlag = cFlag;
}
and call from position class like below
public class Position {
public boolean ccflag = StatusActivity.getFlag();
StatusActivity.setFlag(false);
}
you can not instantiate Activity class. if you want to call a method from activity, fist you should check that activity already running and not destroyed then by having the context of your class you just cast it like below then use its method
StatusActivity statusactivity= (StatusActivity )context;
statusactivity.setFlag(false);
This question already has answers here:
What is the meaning of "this" in Java?
(22 answers)
Closed 4 years ago.
I'm trying to write a function where I have to pass an Activity object to a method that requires such an argument. Usually in such case I'm supposed to just type "this" and it automatically recognizes which type of object it's supposed to create. But sometimes this doesn't work and it for whatever reason reassings a different type of object than the one that is required. For example, I actually use the exact same method in both of these cases:
if (checkLocationPermission(this)){
In this first one, the program automatically recognizes "this" as an Activity object. Here's the second one:
#Override
public void onSuccess(Location location) {
if (location == null || !checkLocationPermission(this)){
In this case the exact same method recognizes "this" as an OnSuccessListener instead of an Activity.
Another example I have in the same program is one where "this" object is supposed to be a Looper but instead it again gets recognized as an OnSuccessListener:
fusedLocationClient.requestLocationUpdates(locationRequest,new LocationCallback(),this);
I don't know how to actually select the proper type of object for "this" argument since I can only type the same damn word.
EDIT:
Here's the full code. I used Looper.this just so you can find it easier. I also tried with MapsActivity.this and it doesn't work:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private GoogleMap mMap;
private GoogleApiClient googleApiClient;
public static final String TAG = MapsActivity.class.getSimpleName();
private FusedLocationProviderClient fusedLocationClient;
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000; //Request code to send to Google Play Services
private LocationRequest locationRequest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
googleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
locationRequest = LocationRequest.create().setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY).setInterval(10*1000).setFastestInterval(1*1000);
}
private void setUpMapIfNeeded(){
if (mMap==null){
SupportMapFragment mapFragment = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map));
mapFragment.getMapAsync(this);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//setUpMap();
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
#Override
public void onConnected(Bundle bundle) {
Log.i(TAG,"Location Services Connected");
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
if (checkLocationPermission(this)){
fusedLocationClient.getLastLocation().addOnSuccessListener(this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location == null || !checkLocationPermission(MapsActivity.this)){
fusedLocationClient.requestLocationUpdates(locationRequest,new LocationCallback(),Looper.this);
}
else{
handleNewLocation(location);
}
}
});
}
}
public static boolean checkLocationPermission(Activity activity){
if(ActivityCompat.checkSelfPermission(activity, android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED
|| ActivityCompat.checkSelfPermission(activity, android.Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(activity, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION,
android.Manifest.permission.ACCESS_COARSE_LOCATION},0);
return false;
}
return true;
}
private void handleNewLocation(Location location){
Log.d(TAG,location.toString());
}
#Override
public void onConnectionSuspended(int i) {
Log.i(TAG,"Location Services suspended. Please reconnect.");
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (connectionResult.hasResolution()){
//Starts an Activity that tries to resolve the error
try {
connectionResult.startResolutionForResult(this,CONNECTION_FAILURE_RESOLUTION_REQUEST);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
}
else{
Log.i(TAG,"Location services connection failed code: " + connectionResult.getErrorCode());
}
}
#Override
protected void onResume(){
super.onResume();
setUpMapIfNeeded();
googleApiClient.connect();
}
#Override
protected void onPause(){
super.onPause();
if (googleApiClient.isConnected()){
googleApiClient.disconnect();
}
}
#Override
public void onLocationChanged(Location location) {
handleNewLocation(location);
}
}
this corresponds to the object in which it is used. onSuccess is a method of OnSuccessListener class and hence this refers to OnSuccessListener. You need to use ActivityName.this. For example if you activity name is MainActivity, then
#Override
public void onSuccess(Location location) {
if (location == null || !checkLocationPermission(MainActivity.this)){
When you use an anonymous inner class, such as a listener, and use this, it refers to the anonymous inner class, because that's your current location.
For instance, with an OnClickListener:
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//"this" here will refer to the OnClickListener instance you create
}
}
Nothing is being "created" with a this argument. It's a direct reference to the current enclosing class. If you need to reference the Activity, you can use:
ActivityClassName.this
as long as you're in an inner class and not a static class.
If you use a lambda (only available for API 24+):
view.setOnClickListener((v) -> {
//"this" will reference your Activity because there's no inner class anymore
}
the this refers to the object of the immediate enclosing class. So, if you have some interface or class as an argument to a function, we usually do like this :
functionThatTakesInterfaceOrClassAsArgument( new TheInterfaceOrClass {
#Override
public void someMethod () {
// if you use `this` here, it refers to the object of `TheInterfaceOrClass`
}
});
If you want to use the object corresponding to an enclosing class (yet not the immediate enclosing class) using <className>.this
So, if the name of the enclosing Activity is MyActivity, one would need to use MyActivity.this.
I have a (seemingly) simple problem: I'm trying to set an onTouchListener on a child linear layout but I can't get my code to compile. I get the error "Cannot Resolve Symbol setOnTouchListener" when I try to use setOnTouchListener() on my chosen view.
How can I record touches on my LinearLayout? What am I doing wrong?
MainActivity.java
public class MainActivity extends FragmentActivity {
public static LinearLayout glView;
public static OpenGL_GLSurface foo;
public TouchController touchSurface;
void configView(){ // used to configure an opengl view
foo = new OpenGL_GLSurface(this);
setContentView(R.layout.activity_main);
glView = (LinearLayout)findViewById(R.id.openglsurface);
RelativeLayout.LayoutParams glParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
glView.addView(foo, glParams);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
...
touchSurface = new TouchController(this); //initialize touchable surface
}}
TouchController.java
public class TouchController {
private Context mContext;
public TouchController(Context c) { //constructor
mContext = c;
}
View.OnTouchListener touch = new View.OnTouchListener() { //set OnTouchListener to OpenGL View
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (maskedAction) {
//do stuff
}
return true;
}
};
MainActivity.glView.setOnTouchListener(touch); //Compilation Error here # setOnTouchListener
}
The issue is in your TouchController, when you are setting the touch listener, this line:
MainActivity.glView.setOnTouchListener(touch);
That line of code is invalid java code because is just hanging around in the class. It must be inside a method like the constructor. Like this:
Edit:
public class TouchController {
private Context mContext;
public TouchController(Context c) { //constructor
mContext = c;
View.OnTouchListener touch = new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (maskedAction) {
//do stuff
}
return true;
}
};
//Register touch listener here in constructor or in another method
CourseListActivity.glView.setOnTouchListener(touch);
}
}
You should consider moving the assignment of your member variable "touch" inside the constructor too, just before you set the touch listener. It will be more organized.
I want to give the user some offers based on his current location.
Which means the ui should wait (not be blocked, but wait with animation)- so i have thought to use location listener and an asyncTask.
but the listener signature returns void
public class MyLocationListener implements LocationListener {
public void onLocationChanged(final Location loc) {
and an asynTask won't help here (as it's a saperated class from my activity)
how would you suggest doing this?
Hope this helps you
public class MyLocationListener extends LocationListener{
public interface MyLocCallbacks{
onLocFound(double lat, double lng);
}
private MyLocCallbacks mCallbacks;
public MyLocationListener(MyLocCallbacks callback){
this.mCallbacks = callback;
//Make sure to start the LocationSerivce here
}
public void onLocationChanged(final Location loc) {
this.mCallbacks.onLocFound(log.getLatitude(), loc.getLongitude())
}
}
MainActivity
public class MainActivity implements MyLocCallbacks{
private MyLocationListener mLocListener;
onCreate(S...){
mLocListener = new MyLocationListener(this); //this for the interface
}
//This one is called by your Location Listener
#Override
onLocFound(double lat, double lng){
startAnimation();
}
private void startAnimation(){
//do here your startAnimation,
//before you could show a simple loading screen
}
}