0

Ok straight to the point I'm a beginner in this android programming, I have question about How to pass context from my activity due to "cant resolve method getapplicationcontext"

this is MyLocationListener.java :

 public class MyLocationListener implements LocationListener {
        // Dipanggil saat ada perubahan lokasi geografis pengguna

private Context mContext;

    public MyLocationListener(Context context) {
        mContext = context;
    }

        @Override
        public void onLocationChanged(Location location) {
    // Mendapatkan nilai latitude dari lokasi terbaru
            double latitude = location.getLatitude();

    // Mendapatkan nilai longitude dari lokasi terbaru
            double longitude = location.getLongitude();

    // Menampilkan lokasi terbaru menggunakan Toast
            String message = "Lokasi saat ini :\n" +
                    "Latitude  = " + latitude + "\n" +
                    "Longitude = " + longitude;
            Toast.makeText(getApplicationContext(),
                    message, Toast.LENGTH_LONG).show();
        }

        // Dipanggil saat provider dinon-aktifkan oleh pengguna
        @Override
        public void onProviderDisabled(String provider) {
            String message = "GPS disabled";
            Toast.makeText(getApplicationContext(),
                    message, Toast.LENGTH_LONG).show();
        }

        // dipanggil saat provider diaktifkan oleh pengguna
        @Override
        public void onProviderEnabled(String provider) {
            String message = "GPS enabled";
            Toast.makeText(getApplicationContext(),
                    message, Toast.LENGTH_LONG).show();
        }

        // dipanggil saat ada perubahan status pada provider
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub
        }
    }

This is my activity (GPSSample.java) :

public class GPSSample extends Activity {
        /** Called when the activity is first created. */
        @Override

LocationListener myLocationListener = new MyLocationListener(this);

        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

    // Inisiasi LocationManager dan LocationListener
            LocationManager myLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
            LocationListener myLocationListener = new MyLocationListener();
            myLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, myLocationListener);
        }

It said that I should use constructor to pass it, but how? I have Some constructor sample but I have no idea where to put it, and rename it based on my script

MyClass myClass = new MyClass(this);

Then create a constructor in that class that accepts Context as a param and use that

public class MyClass  
{ 
    Context c;
    public MyClass(Context context)
    { 
         c= context;
     } 
}} 

Thanks for the help...

Rikudo Pain
  • 441
  • 9
  • 22

2 Answers2

2

1

You need to pass context as incoming parameter.

public class MyLocationListener implements LocationListener {

    // Dipanggil saat ada perubahan lokasi geografis pengguna
    private Context mContext;

    public MyLocationListener(Context context) {
        mContext = context;
    }

    @Override
    public void onLocationChanged(Location location) {
// Mendapatkan nilai latitude dari lokasi terbaru
        double latitude = location.getLatitude();

// Mendapatkan nilai longitude dari lokasi terbaru
        double longitude = location.getLongitude();

// Menampilkan lokasi terbaru menggunakan Toast
        String message = "Lokasi saat ini :\n" +
                "Latitude  = " + latitude + "\n" +
                "Longitude = " + longitude;
        // change getApplicationContext() to mContext(inner context reference)
        Toast.makeText(mContext,
                message, Toast.LENGTH_LONG).show();
    }

    // Dipanggil saat provider dinon-aktifkan oleh pengguna
    @Override
    public void onProviderDisabled(String provider) {
        String message = "GPS disabled";
        // change getApplicationContext() to mContext(inner context reference)
        Toast.makeText(mContext,
                message, Toast.LENGTH_LONG).show();
    }

    // dipanggil saat provider diaktifkan oleh pengguna
    @Override
    public void onProviderEnabled(String provider) {
        String message = "GPS enabled";
        // change getApplicationContext() to mContext(inner context reference)
        Toast.makeText(mContext,
                message, Toast.LENGTH_LONG).show();
    }

    // dipanggil saat ada perubahan status pada provider
    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
    }
}

And set it in Activity :

LocationListener myLocationListener = new MyLocationListener(this);

2

Also you can use self-reference using .this construction. .this - in Java - is a reference for himself. But if class is static - you getting compile error.

Sergey Shustikov
  • 15,377
  • 12
  • 67
  • 119
  • I Got new error : Error:(28, 47) error: constructor MyLocationListener in class MyLocationListener cannot be applied to given types; required: Context found: no arguments reason: actual and formal argument lists differ in length Error:Execution failed for task ':app:compileDebugJavaWithJavac'. > Compilation failed; see the compiler error output for details. – Rikudo Pain Aug 26 '15 at 13:14
  • @RikudoPain you add a constructor? – Sergey Shustikov Aug 26 '15 at 14:17
  • yes, I add it as your suggestion, Already update the question (now with your suggestion) – Rikudo Pain Aug 26 '15 at 14:21
  • @RikudoPain but you don't replace `getApplicationContext()` with `mContext` – Sergey Shustikov Aug 26 '15 at 14:23
  • @RikudoPain and read again my answer. You do not change class declaration to `LocationListener myLocationListener = new MyLocationListener(this);` – Sergey Shustikov Aug 26 '15 at 14:24
  • for getApplicationContext() I already replaced it with mContext (I'm sorry forgot to change it in question. Oh... I See, I put new declaration of LocationListener instead of changing it. Thank You. By the way can you explained in simple word why should I pass this context? is it works like my class should "get" it from "post" in another page like html? Thank you for your answer, Vote it. – Rikudo Pain Aug 26 '15 at 14:33
  • 1
    @RikudoPain i think you jump to Android from web development. Do not look for parallel of the **context** for good understanding. Actually context is the entity which allow to you get resources or similar environment data. You do not need to pass context everywhere, but in this case - you should, because if you look a code, you can find a `Toast` class that needs a context for use. More about context : http://stackoverflow.com/a/18327529/2956344 – Sergey Shustikov Aug 26 '15 at 14:38
  • Yes, previously I used to use PHP, MySQL and other stuff for web development, It's quite bit confusing enough just to try to understand it. Oh I got it.., so it's more like a bridge where in this case I need that bridge to access needed resources using toast. Thank You Very Much!!! – Rikudo Pain Aug 26 '15 at 17:22
0

Just use GPSSample.this instead of getApplicationContext(). This is the "outer this" i.e. the this of the parent class that, in this case, is the activity (and an activity is a subclass of a context).

If you will need to move the listener (I don't think so), use the constructor. Usually you will even use anonymous classes instead of concrete one for listeners. It's more direct and clear to read.

Filnik
  • 352
  • 1
  • 12
  • 33
  • actually yes, I'll move the listener (for learning purpose). I just curious how to pass context to another activity, that's why I ask this question. I saw so much explanation about using constructor but I have problem in implementing it, since I really new to this programming. Anyway thanks for answer. (Updated question) – Rikudo Pain Aug 26 '15 at 13:11
  • yes but usually you don't define a constructor in a listener. It's overkilling. You just pass the reference with the other this usually or directly using some sort of variable (or directly with getContext() in the anonymous class). Obviously you can create an external class and sometimes may be useful for listeners, but most of the cases it's not.. :) – Filnik Aug 26 '15 at 13:17
  • 1
    yes that's the point, as my explanation before my question are about pass context and it's for learning purpose and as you said sometimes may be useful, in that case I really curious about how it works. – Rikudo Pain Aug 26 '15 at 13:26