I am a novice, just making my first app, so please excuse my poor phrasing and understanding.
I have made a Class MyAlarms() to help manage my alarm and notification code. I require context for a few functions, namely Toast, SharedPreferences, and PendingIntent. GetContext() does not work, nor does getApplicationContext(), so I decided to go with passing the context to MyAlarms(Context context) from the code using it. This works just fine.
But I have now read that I should not be doing this, as to may lead to memory leak issues. Is there another way to get context in a class?
Thanks in advance!
I'm assuming you need the context because you are creating some views? If so, then you need to use .getContext() from whatever layout you are placing that view in.
If you have a static function, you have to pass in the Context from the Activity in the parameters.
For example:
private static void sendMessageToActivity(String msg) {
Intent intent = new Intent("intentKey");
intent.putExtra("key", msg);
LocalBroadcastManager.getInstance(getContext()).sendBroadcast(intent);
}
Change to:
#Override
protected void onCreate(Bundle savedInstanceState) {
...
sendMessageToActivity(this,"test");
}
private static void sendMessageToActivity(Context context, String msg) {
Intent intent = new Intent("intentKey");
intent.putExtra("key", msg);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
Related
I would like know how to send a command to an activity which has started from inside another function. More precisely I want to send a pause intent to com.google.vr:sdk... the view is started like this:
class VRPlayer {
private void playVideo(int sourceType, Context context) {
Intent intent = new Intent(context, VrVideoActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
private void pauseVideo(Context context, JSONArray args) {
VrVideoActivity.class.toggleVideoPlay(); <------------- NOT WORKING ¯\_(-_- )_/‾
}
}
once the activity has started there should be a way to execute other function, ex: toggleVideoPlay() which are inside the VrVideoAcitivity from the but I can't get the right way to do it... If you want to try it you can find the Android project here: https://github.com/StarStep/android-help-vr
VrVideoActivity vrVideoActivity = new VrVideoActivity();
vrVideoActivity.toggleVideoPlay();
a simple way -> (new VrVideoActivity).toggleVideoPlay();
another way -> set the toggleVideoPlay(); to static as following
public static void toggleVideoPlay()
{
//Your Code
}
and call it VrVideoActivity.toggleVideoPlay();
I am starting other activity using intent from MainActivity.
Here is my code:
Intent intent = new Intent(this, ProgramClass.class);
startActivity(intent);
Now I want to access string.xml file in ProgramClass but getResources(), getApplicationContext(),getContext() are not able to get me that stringArray defined string.xml file.
As it generating an error, the possible solution I have is to create a constructor & pass context to ProgramClass from MainActivity().
but for doing that I need to create an object of ProgramClass in MainActivity while using an explicit Intent which takes .class parameter. How can I start an intent or another activity by passing context of MainActivity?
....
NewActivity.setParams(context);
Intent i = ..........
in NewActivity:
private static Context c;
public static void setParams(Context c){
this.c = c;
}
This is a slight workaround because it uses static methods. This is however accessable from anywhere so any activity can change the context.
ABOUT INTENT
Intent is Android's native way to change from one activity to another. These do not change anything in the target/starting point class. They do however trigger the next step in the Activity Lifecycle:
There is no way to pass the context to the target activity using Intent. However, you can pass context, integers, booleans, strings, instances and so on using a static method as shown above. It works as long as you do not alter the context from the NewActivity class.
Also, I would like to add that all classes that extend Activity, Application, AppCompatActivity and so on are contexts. If you need to use context somewhere, you should pass it to a class without native context. If you are to use activities for main logic computing, try doing something that requires context and just write this.
I am starting other activity using intent from MainActivity. Here is my code:
Intent intent = new Intent(this, ProgramClass.class);
startActivity(intent);
Alright, that's great, but this won't work if ProgramClass doesn't extend some variant of Activity. And if it did, then you should have access to each of those methods you mentioned.
A hack would be that you define a static variable in your activity class and initialize it in onCreate method and later use that in your other class.
public static Context context = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
}
and then in your other class use:
MainActivity.context.getResources().getString();
I have successfully used androidannotations #Extra to decode an intent and get the sent message as this snippet demonstrates:
#Extra(MyActivity.MESSAGE)
String intentMessage;
#ViewById(displayMessage)
TextView textView;
#AfterViews
protected void init() {
textView.setText(intentMessage);
}
I'm missing how, if possible, to create the intent in the first place using annotations. e.g replace the following
Intent intent = new Intent(this,DisplayMessageActivity_.class);
intent.putExtra(MESSAGE, s);
startActivity(intent);
with something. Is this possible? (I'm totally new to all this so probably am missing something terribly obvious)
SOLUTION:
DisplayMessageActivity_.intent(this).intentMessage(s).start();
Where intentMessage is the name of the extra field.
Yes, you can use the following:
// Starting the activity
MyListActivity_.intent(context).start();
// Building an intent from the activity
Intent intent = MyListActivity_.intent(context).get();
// You can provide flags
MyListActivity_.intent(context).flags(FLAG_ACTIVITY_CLEAR_TOP).start();
// You can even provide extras defined with #Extra in the activity
MyListActivity_.intent(context).myDateExtra(someDate).start();
// startActivityForResult() equivalent:
MyListActivity_.intent(context).startForResult();
Source: https://github.com/excilys/androidannotations/wiki/HowItWorks
Solution. Finally saw the pattern on how it works. Thanks.
DisplayMessageActivity_.intent(this).intentMessage(s).start();
where intentMessage is the #Extra defined in the activity to be started e.g
#EActivity(R.layout.activity_display)
public class DisplayMessageActivity extends Activity {
public static final String MESSAGE = "net.richardriley.MyFirst.MESSAGE";
#Extra(MESSAGE)
String intentMessage;
#ViewById(displayMessage)
TextView textView;
#AfterViews
protected void init() {
textView.setText(intentMessage);
}
}
I know this is a late answer but I have developed a library that does exactly this. It uses annotations to generate the intent code.
Check it out in here: https://github.com/kostasdrakonakis/android_navigator
I got list of checked contacts.However, i need to pass these selected contacts to another activity and display in edit Text.Please help.Thanks
You have a few solutions...
You can use static fields in your Java classes
You can pack the data into Intents via Intent.putExtra
Option (1) is probably going to be the easiest and quickest if you are trying to send data between your own activities. Option (2) is what you must do if you wish to send data to Activities of another applications.
I suggest you read these Q&A first though as some cover this question in more depth...
Passing data of a non-primitive type between activities in android
Passing data between activities in Android
Switching activities/passing data between activities
You have to use an Intent to do so.
Example, to pass the data to an activity already running:
public void sendToActivity(Object data){
Intent i = new Intent("SEND_DATA");
i.putExtra("data", this.catchReports.get(data));
sendBroadcast(i);
}
Then, you have to setup a listener in your receiving activity to catch the Broadcasted signal:
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
// Sets the View of the Activity
setContentView(R.layout.activity_layout);
registerReceiver(new CustomReceiver(this), new IntentFilter("SEND_DATA"));
}
With the following customreceiver:
public class CustomReceiver extends BroadcastReceiver {
private MyActivity activity;
public ReceiverEvent(MyActivity activity) {
this.activity = activity;
}
public void onReceive(Context context, Intent i) {
this.activity.doWhateverWithYourData(i.getParcelableExtra("newEvent"));
}
}
Note that if you want to transport Objects other than integers, floats and strings, you have to make them Parcelable.
I have a beginners problem. Here is my situation:
I want to start a new activity from the main activity. The code to launch the new activity is found in a separate class file. I seem to be passing the wrong arguments and I am ending up in a nullpointerexception when trying to launch the new activity. The new activity launches fine when I place the code in the main activity class file, therefore the second activity and the manifest are fine. Here is a sample of my code:
In my main activity class where I instanciate the second class (THIS IS MY MAIN ACTIVITY. I OMITTED THE REST BECAUSE I DO NOT THINK IT IS RELATED TO THE PROBLEM):
Tester mytest = new Tester();
mytest.test(this);
In my second class file (THIS IS NOT AN ACTIVITY; IT IS A CLASS THAT IS INSTANTIATED IN THE ACTIVITY):
public class Tester extends Activity {
Intent myIntent;
public void test (Context context) {
myIntent = new Intent (Intent.ACTION_VIEW);
myIntent.setClass(context, newActivity.class);
thebutton.setOnClickListener(
new OnClickListener() {
public void onClick(View v) {
startActivity(myIntent);
}
}
):}
When I perform the click I receive a nullpointerexception at startactivity. Can anyone enlighten me on this please?I am sure that I am wrongly using the context.
Activities are started with Intents. Please read the Android Application Fundamentals first and try the Hello World app :)
I understood that you will use your separate Tester class at all cost ;) so I'm trying to adapt and help you out there.
First of all, don't let your class inherit from Activity. This won't help you, cause this calls will probably not have any valid context. Activity somehow implements the template pattern, providing you key method like onCreate(...), onPause(...) etc and is instantiated by the Android OS.
If you still want to use the class, you have to pass in the context. Probably you're aiming for some MVC/MVP pattern structure, anyway.
public class Tester {
private Context context;
public Tester(Context context){
this.context = context;
}
public void test () {
final Intent myIntent = new Intent(context, NewActivity.class);
//guess this comes from somewhere, hope through a findViewById method
thebutton.setOnClickListener(
new OnClickListener() {
public void onClick(View v) {
context.startActivity(myIntent);
}
}
)};
}
}
This would be a proposed solution from my side. A problem I still see here is on how you retrieve the button in that test() method. In order to have that work properly you have to retrieve it from some View class (with view.findViewByid(R.id.myButton)) or to create it dynamically and associate it with the view during the onCreate(...) of your Activity (probably using an Inflater).