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();
Related
I have a Main Activity and Child Activity.
MainActivity will intent the ChildActivity and call moveTaskToBack(true) at last to hide itself, but not finish().
On ChildActivity, i want to access the getContext(),getApplicationContext() method from MainActivity, so how can i do that?
Thanks you.
One way you can access using static variable, like this
In parent class declare
Public static String parentContext;
assign context in onCreate(...) method
parentContext = parentActivity.this;
or
parentContext = getApplicationContext();
Now in your ChildActivity
Context childContext = parentActivity.parentContext;
Usually, in order to launch a new Activity and get its result, from an Activity class, I will use
public void startActivityForResult (Intent intent, int requestCode)
However, what if I try to launch a new Activity and get its result, from a non-Activity class? How I can achieve this?
The reason I ask so as I am currently having LoginManager class (A non-Activity class). It is having the following code.
accountManager.getAccountManager().getAuthToken(account, AUTH_TOKEN_TYPE, true, new AccountManagerCallback<Bundle>() {
public void run(AccountManagerFuture<Bundle> future) {
try {
Bundle bundle = future.getResult();
if (bundle.containsKey(AccountManager.KEY_INTENT)) {
Intent intent = bundle.getParcelable(AccountManager.KEY_INTENT);
intent.setFlags(intent.getFlags() & ~Intent.FLAG_ACTIVITY_NEW_TASK);
// Compilation error, as LoginManager doesn't have startActivityForResult method.
startActivityForResult(intent, REQUEST_AUTHENTICATE);
((Activity) mContext).startActivityForResult(.....) will do the trick.
But results will be delivered to the actual activity holding the context.
You can apply following Approach
Create single argument constructor in LoginManager class like follows.
class LoginManager
{
private Context mContext;
LoginManager(Context mContext)
{
this.mContext=mContext;
}
.............................
//Then whenever you want to call method call like this.
((Activity) mContext).startActivityForResult(.....)
}
Now in Activity class whenever you will create Object of LoginManager class create as follows.
LoginManager loginManager=new LoginManager(ActivityName.this);
I would have the Activities within your project extend some kind of a "BaseActivity". Within that base activity, I would override onActivityResult() and pass the result into the LoginManager from there.
This will have the consequence of making all of your Activities pass their results to your LoginManager, so you won't have to keep overriding onActivityResult manually everywhere.
Perhaps you could just send a reference to your Context into the LoginManager class and use it to start the Activity?
I want call an activity class from a normal java class(without extends anything) for every some time interval to refresh the Ui, Is it possible to call an activity from normal java class. We can call the activity from another activity using intent and startactivity. But am not sure about calling the activity from class.
For example
class example extends Activity
{
}
class example2 extends Activity
{
// we can call like
Intent intent = new Intent(this.example2,example.class);
startActivity(intent);
}
class test
{
// How can i call example or example2 from here.
}
Thanks,
Lakshmanan
You could provide a parameter consisting of the context of your Activity that has been creating the Object. Then you can use the Context's methods just like within an Activity.
i.g.
public class Foo {
private Context context;
public Foo(Context context) {
this.context = context;
}
public void startActivity() {
context.startActivity(/*your intent here*/);
}
}
Intent intent12 = new Intent(context.getApplicationContext(), ImageClick.class);
context.startActivity(intent12);
It works. I've tried.
I use this to view you tube videos from a non activity class -
Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse(url));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // important step
context.startActivity(intent);
Hope this helps you.
Salil.
Suppose I have a class first.java (activity class) and I start another activity in this class (second.java - activity class).
How can I access the instance of first.java from second.java?
Can someone give me a good explanation on this... An example would be great...
If you need your second activity to return some data to your first activity I recommend you use startActivityForResult() to start your second activity. Then in onResult() in your first activity you can do the work needed.
In First.java where you start Second.java:
Intent intent = new Intent(this, Second.class);
int requestCode = 1; // Or some number you choose
startActivityForResult(intent, requestCode);
The result method:
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
// Collect data from the intent and use it
String value = data.getString("someValue");
}
In Second.java:
Intent intent = new Intent();
intent.putExtra("someValue", "data");
setResult(RESULT_OK, intent);
finish();
If you do not wish to wait for the Second activity to end before you do some work in the First activity, you could instead send a broadcast which the First activity reacts to.
You can simply call getParent() from the child activity.
I have no clue why other answers are so complicated.
Only this should work
class first
{
public static first instance;
oncreate()
{
instance = this;
}
}
first.instance is the required thing that is accessible from the second class
try this if this work 4 u.........
something like this.....
class first
{
public static first instance;
oncreate()
{
instance=this;
}
public static getInstance()
{
return instance;
}
}
now from second class call first.getInstance();
you can also directly acess instance in static way like this first.instance.......
Thanks...
You can't create an activity directly.
In the first activity take a static activity variable like this,
public static Activity activity;
In the onCreate do this.
activity = this;
Then in the second activity do this,
Activity activity = (your activity name).activity;
Edit:
For passing data from one activity to other activity this is not the way.
Above answer was to get activity instance from other activity which was initially asked.
To pass data from one activity to other activty generally use bundle. But if the data is not primitive data type, then use object class which should implement parcelable or serializable interface. Then through bundle only parcelable list of objects we can pass.
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).