Android how get Context from specific class being in Service - android

I created Service class.
I can run it anywhere where I want, but I always need Context from MainMenuActivity.class.
I tried use getApplicationContext and getBaseContext but they show another class.
Thanks for answer
public class MainActivity extends ActionBarActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startService(new Intent(this, MyService.class));
}
}
public class MyService extends Service {
private Handler handler = new Handler();
private MyLocationListener mylistener;
public void onCreate() {
handler.postDelayed(new runnable(), 10000);
}
private class runnable implements Runnable {
#Override
public void run() {
mylistener = new MyLocationListener();
}
}
}
public class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
}
}
[EDIT]
When I used getApplicationContext() or getBaseContext or MainActivity.this to getDefaultSharedPreferences, always it will be the same?

Solution: 1
In that case you have to use, defaultSharedPreferences. You can access the default shared preferences instance by:
PreferenceManager.getDefaultSharedPreferences(Context context):
Example:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
This preference is shared across all your Activity and Service classes.
Solution: 2
You can create sharedPreference instance in your application class like:
public class MyApplication extends Application {
public static SharedPreferences preferences;
#Override
public void onCreate() {
super.onCreate();
preferences = getSharedPreferences("Preferences", MODE_PRIVATE);
}
}
And then you can manage your preferences as:
MyApplication.preferences.getString("key", "default");

add context parameter to your service class methods
public void myMethodInsideServiceClass(Context context){
//bluh bluh
}
so that you can call from Activity Class like this
myMethodInsideServiceClass(this);
you can also try
public class MyActivity extends Activity {
public static myActivity;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myActivity=this;
}
}
so that you can use myActivity across the application
(i was not using editor to type code, sorry for syntax error)

Related

Appcompatactivity onCreate() not getting triggered when instantiating a class

I am still learning Android development and I am stuck at a point where I assume I am doing something wrong. Would appreciate your help.
I have my main class that extends AppCompatActivity like this, and inside it, I have a function that instantiates another class where I want to do some calculations based on the store sharedpreferences:
public class Level1_0 extends AppCompatActivity {
.....
public void isTwoUnlocked(){
CalculateAvg calc = new CalculateAvg();
boolean L = calc.level2();
if(L == true){
showPopup();
calc.finish();
}
}
.....
}
CalculateAvg is the class I am instantiating. That class has a method called level2(), this is where I do some checks and return True or False as boolean. When I run the code, init() never gets called by onCreate(). I also tried writing the entire code of init inside onCreate itself, still same problem, onCreate never gets triggered.
CalculateAvg class
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;
public class CalculateAvg extends AppCompatActivity{
public static final String SHARED_PREFS = "sharedPrefs";
private static final String TAG = "Level1_0";
level10 = sharedPreferences.getBoolean(LEVEL10, false);
........
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
init();
}
public void init(){
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
........
// do my calculations here but init() never gets called by onCreate().
// I even tried writing entire code inside onCreate but it also didn't work
}
public boolean level2(){
boolean L = false;
if(level10 == null){
L = false;
}
else{
L = true;
}
return L;
}
}
Any idea why onCreate is not getting triggered when I instantiate it in my main class?
According your requirements there is no need to use AppCompatActivity. You can simply use like class and pass context to access SharedPreferences.
public class CalculateAvg {
private Context mContext;
....
public CalculateAvg(Context context) {
mContext = context;
init();
}
public void init(){
SharedPreferences sharedPreferences = mContext.getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE);
....
}
public boolean level2(){
boolean L = false;
if(level10 == null){
L = false;
}
else{
L = true;
}
return L;
}
}
And instantiate CalculateAvg with your activity's context like below:
CalculateAvg calc = new CalculateAvg(Level1_0.this);
This Android not a java you can not call activity with creating new instance to call CalculateAvg from Level1_0 do below code in Level1_0 onCreate().
public class Level1_0 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent =new Intent(this,CalculateAvg.class);
startActivity(intent);
}
}

Android make callback to an Activity from java class

How can i make a callback to an Activity form a Java Class?
Example:
public class TestClass{
String text = "Test";
public TestClass(Context context){
startActivity(new Intent(context, SomeActivity.class));
}
private void sendToSomeActivity(){
//Call some method of SomeActivity and pas text as string
}
}
When sendToSomeActivity() is called, i want to make a callback to the already started SomeActivity and pass some text to the Activity. In SomeActivity i want to use the text.
Note: The TestClass object that i want to use is already created in another class.
How can this be done?
The solution I chose is as follows:
Use BroadcastReceivers to communicate between Java classes and Activities.
Example:
public class SomeActivity extends Activity{
private MyBroadcastReceiver receiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
receiver = new MyBroadcastReceiver();
this.registerReceiver(receiver, new IntentFilter(MyBroadcastReceiver.ACTION));
}
#Override
public void onDestroy() {
super.onDestroy();
this.unregisterReceiver(receiver);
}
private class MyBroadcastReceiver extends BroadcastReceiver{
public static final String ACTION = "com.example.ACTION_SOMETHING"
#Override
public void onReceive(Context context, Intent intent) {
String test = intent.getStringExtra("dataToPass");
}
}
}
public class TestClass{
private String test = "TEST";
private Context context;
public TestClass(Context context){
this.context = context;
}
private void sendToSomeActivity(){
Intent intent = new Intent();
intent.setAction(SomeActivity.MyBroadcastReceiver.ACTION);
intent.putExtra("dataToPass", test);
context.sendBroadcast(intent);
}
}
Try this..
public class TestClass{
interface Implementable{
public void passData(String text);
}
Implementable imple;
String text = "Test";
public TestClass(Context context){
startActivity(new Intent(context, SomeActivity.class));
}
private void sendToSomeActivity(){
if(imple != null){
imple.passData(text);
}
}
public void setListener(Implementable im){
imple = im;
}
}
class SomeActivity implements Implementable{
new TestClass().setListener(this);
#override
public void passData(String text){
//here is your text
}
}
In your java class create an interface like this
public class TestClass{
private MyInterface myInterface;
public interface OnSendSomething {
public void onSending(String sendWhateverYouWant);
}
public void setOnSendListener(MyInterface myInterface) {
this.myInterface = myInterface;
}
}
private void sendToSomeActivity(){
//Call some method of SomeActivity and pas text as string
myInterface.onSending(sendWhateverYouWant);
}
And in your activity do something like this:
TestClass tclass = new TestClass(context);
tclass.setOnSendListener(new OnSendSomething () {
#Override
public void onSending(String sendWhateverYouWant) {
//sendWhateverYouWant is here in activity
}
});
You can also visit these links for better understanding.
How to create our own Listener interface in android?
Observer Design Pattern in Java

how to call method in activity form non activity class

I have an Activity and non Activity class. How to call a method in Activity class from non Activity class
public class MainActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
DataClass dc = new DataClass();
dc.show();
}
public void call(ArrayList<String> arr) {
// Some code...
}
}
public class DataClass {
public void show(ArrayList<String> array) {
// Here I want to send this ArrayList values into the call
// method in activity class.
MainActivity act = new MainActivity();
act.call(array);
}
}
Just create a callback interface inside the DateClass.
public DateClass {
public interface IDateCallback {
void call(ArrayList<String> arr);
}
private IDateCallback callerActivity;
public DateClass(Activity activity) {
callerActivity = (IDateCallback)activity;
}
...
}
public void show(ArrayList<String> array) {
callerActivity.Call(array);
...
}
//And implements it inside your activity.
public class MainActivity extends Activity
implements IDateCallback {
public void call(ArrayList<String> arr) {
}
}
Well there are several things you could do. I think the easiest for you would be to send the Context into DataClass like so:
DataClass dc =new DataClass();
dc.show(this);
And in your DataClass save the context into a global var Context context. Then use it like so:
((MainActivity)context).call(array);
((MainActivity)getContext).array();
Just make a singleton like:
TeacherDashboardSingleton:
public class TeacherDashboardSingleton {
public Teacher_Dashboard aa;
private static final TeacherDashboardSingleton ourInstance = new TeacherDashboardSingleton();
public static TeacherDashboardSingleton getInstance() {
return ourInstance;
}
}
myActivity class:
onCreate(....){
....
TeacherDashboardSingleton.getInstance().aa = this;
....
}
this will create an object of same instance as in activity
now you can use it from anywhere

SharedPreference in non-activity class

I have a class PreferenceClass which extends PreferenceActivity. The code for this class is as follows:
public class Preferenceclass extends PreferenceActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.main2);
addPreferencesFromResource(R.layout.preferences);
}}
I also have a non activity class Shakelistener which implements SensorListener. The code for this class is as follows:
public class Shakelistener implements SensorListener {
public void onSensorChanged(int sensor, float[] values) {
// Some code
}}
I need to be able to access the preferences from in this non-activity class, but I'm not sure how to do this.
EDIT
This is the code I use to access the shared preferences:
String PREF_FILE_NAME = "preferences";
SharedPreferences pref = mContext.getSharedPreferences(PREF_FILE_NAME , Context.MODE_PRIVATE);
String myListPreference = pref.getString("listpref", "default choice");
boolean cb = pref.getBoolean("checkBox", false);
Toast.makeText(mContext, myListPreference+"-"+cb, Toast.LENGTH_LONG).show();
This code is giving no errors, but it always evaluates the toast to "default choice-false".
Which PREF_FILE_NAME should I be using in this case?
Take an instance of Context in the constructor of your non-activity class and use that to call all such methods.
Something like this:
public class NonActivityClass implements SensorListener{
Context mContext;
public NonActivtiyClass(Context context) {
this.mContext = context;
}
//Rest of your code
}
Then do this to create an object of that class in your Activtiy's onCreate():
NonActivityClass nac = new NonActivityClass(this);

Call a public method in the Activity class from another class?

MAIN ACTIVITY
public class MyActivity() extends Activity
{
onCreate()
{
MyClass myobj=new MyClass();
}
public void Mymethod()
{}
}
//HELPER CLASS IN A SEPARATE FILE
public class MyClass()
{
MyClass(Context context)
{
}
}
I tried to call Mymethod() from an instance of MyClass.
I would really appreciate any help. Thanks.
Why not just pass the activity to the constructor like
public class MyActivity extends Activity {
onCreate(){
MyClass myobj=new MyClass(MyActivity.this);
}
public void myMethod(){
}
}
//HELPER CLASS IN A SEPARATE FILE
public class MyClass{
public MyClass(MyActivity act) {
act.myMethod();
}
}
Make that method as static so you can call without creating the class object
public static void Mymethod()
{}
and call like this way
MainActivity.Mymethod();
This is probably the best way to do it. This is how I'm doing it. It's called a Singleton Design Pattern:
public class MyActivity extends Activity {
private static MainActivity instance;
public static MainActivity getInstance() {
if(instance==null){
setInstance(this);
}
return instance;
}
public static void setInstance(MainActivity instance) {
MainActivity.instance = instance;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setInstance(this);
}
}
If I'm understanding you correctly I believe you can solve your problems using an interface as a callback.
////ACTIVITY/////////////////////////////////
public class MyActivity() extends Activity {
onCreate()
{
MyClass myObj=new MyClass();
//Set the listener on the object. Created as anonymous
myObj.setListener(new MyClass.Listener() {
myMethod();
});
}
}
public void myMethod(){
}
//////Custom Class//////////////////
public class MyClass {
Listener mListener;
public interface Listener {
public void onInterestingEvent();
}
public void setListener(Listener listener) {
mListener = listener;
}
public void someUsefulThingTheClassDoes() {
//Do your code here and when you're ready to call the activity's method do this
mListener.onInterestingEvent();
}
}
I had an inner class that I wanted to pull out into a more general library "Helper" class. I had the same issue you do. I got around it by making the helper class abstract, with a single abstract method. Then in my project package I extended the helper class with a constructor call in the specific class.
public class MyActivity extends Activity {
onCreate() {
MyHelperClass = new MyHelperClass(this, "foobar");
}
public void myMethod() {
// Code...
}
}
// In a different file
public class MyHelperClass extends HelperClass {
private MyActivity mInstance;
public MyHelperClass(MyActivity act, String data) {
super();
this.mInstance = act;
this.mActivity = act; // Useful for calling generic Activity methods in the HelperClass
this.mData = data;
}
protected void callMyActivityMethod() {
mInstance.myMethod();
}
}
// In a different file
public abstract class HelperClass {
protected Activity mActivity;
protected String mData;
public HelperClass() {
// Subclass will set variables
}
protected abstract void callMyActivityMethod();
// More code for all the other stuff the class does
}
In this way, I have a helper class that contains the vast majority of the "work", and all I have to do is make a subclass with the constructor and one method in order to get access to the calling activity's method of interest.
You have to pass instance of MainActivity into another class, then you can call everything public (in MainActivity) from everywhere.
MainActivity.java
public class MainActivity extends AppCompatActivity {
// Instance of AnotherClass for future use
private AnotherClass anotherClass;
#Override
protected void onCreate(Bundle savedInstanceState) {
// Create new instance of AnotherClass and
// pass instance of MainActivity by "this"
anotherClass = new AnotherClass(this);
}
// Method you want to call from another class
public void myMethod(){
...
}
}
AnotherClass.java
public class AnotherClass {
// Main class instance
private MainActivity mainActivity;
// Constructor
public AnotherClass(MainActivity activity) {
// Save instance of main class for future use
mainActivity = activity;
// Call method in MainActivity
mainActivity.myMethod();
}
}
In MainActivity.class file
You have to pass MainActivity context from MainActivity Class. Then in MyClass you have to Get MainActivity context. Remember Context and MyActivity are two different reference.
public class MyActivity extends Activity
{
onCreate(){
MyClass myobj=new MyClass(MyActivity context);
}
public void Mymethod(){}
}
//HELPER CLASS IN A SEPARATE FILE
public class MyClass()
{
MyActivity context;
MyClass(MyActivity context)
{
this.context = context;
this.context.Mymethod();
//Or you can directly use activity context
context.Mymethod();
}
}
I decided to write the HelperClass MyClass as an inner class of MyActivity class. This allows it full access to parent class but the bad thing is now MyClass is restricted to MyActivity class only.
public class MyActivity() extends Activity
{
onCreate()
{
MyClass myobj=new MyClass();
}
public void myMethod()
{
}
}
//INNER CLASS
public class MyClass
{
public MyClass()
{
}
//I can directly access the MyMethod
myMethod();
}

Categories

Resources