How to get Object of calling Activity in an Intent? - android

I have two Activities.
I got my FirstActivity and SecondActivity and I start an Intent from the first activity which brings me from the first to the second one like this:
startActivity(new Intent(FirstActivity.this, SecondActivity.class));
Now I need an Instance of my FirstActivity in the second activity. My working approach was a static instance in my FirstActivity:
private static FirstActivity firstActivity;
onCreate(...) { firstActivity = this; }
public static FirstActivity get() { return firstActivity; }
This although is breaking InstantRun and is considered as a memory leak. I know that I can send Parcelable's through intents, but I need my FirstActivity object.

A typical solution for this is inheritance:
Step #1: Create a BaseActivity class that extends from whatever you are using right now (Activity, AppCompatActivity, etc.)
Step #2: Have FirstActivity extend BaseActivity
Step #3: Move the onCreateOptionsMenu() and onPrepareOptionsMenu() methods from FirstActivity to BaseActivity
Step #4: Have SecondActivity also extend BaseActivity
Another option would be to use static utility methods for the common code bits, where those static methods are called by the onCreateOptionsMenu() and onPrepareOptionsMenu() of FirstActivity and SecondActivity.

//first activity
Bundle bundle = new Bundle();
bundle.putSerializable("TAG", object);
Intent intent = new Intent(getApplicationContext(), ActivityB.class).putExtras(bundle);}
startActivity(intent);
//second activity
onCreate().....
Bundle bundle = getIntent().getExtras();
if(bundle!=null){
Object object = (Object) bundle.get("TAG");
//and implements serializable in your class object

Related

pass data from activity one to activity three directly while going through activity two but data should not be passed to activity two

I have three activities A,B and C. I need to pass some data from activity A to activity C. But the navigation is from A to B to C i.e. I can't go to activity C from activity A directly. I don't want to pass my data to activity B from A and I don't want to use any external storage like sqlite or shared preferences. Can it be done through intent ? If yes , how ? If no, is there any other way ?
use Interface to communicate with other Activity.
or you can make your variable public static on Activity1
The problem is that your third activity has no way of knowing which activity sent the bundle. You need to add a field that identifies what type of bundle this is so you can process accordingly. For instance, in activity 1:
Intent i = new Intent(ActivityOne.this, ActivityTwo.class);
i.putExtra("activity", (int)1);
i.putExtra("key", value);
startActivity(i);
Then in 3rd activity:
Bundle extras = getIntent().getExtras();
if(extras !=null) {
int typeAct = extras.getInt("activity");
if (typeAct == 1) {
//do something with data
}
There are various ways to send the data from one activity to other activity,
Now as you can not use intent so I would suggest you to go with either Application class or create a Global singleton class to hold your data.
Please refer following link
https://androidresearch.wordpress.com/2012/03/22/defining-global-variables-in-android/
Following are the steps to create an application class:
Step 1: Create any class and extend it with the Application class:
public class Globals extends Application{
private int data=200;
public int getData(){
return this.data;
}
public void setData(int d){
this.data=d;
}
}
Step 2: Defining the application class in the manifest file:
<application
android:name=".Globals"
.... />
Step 3:Now by calling getApplication() in any of the activity you get your application class. Just typecast it and call the methods required.
Globals g = (Globals)getApplication();
int data=g.getData();
I hope this will help.
make one interface :
public interface PassData {
public void data(String data);
}
if you want to pass the data from activity A to activity C then :
from Activity A you need to pass the data like this:then on Activity A.
PassData passData;// make it global variable
passData.data("Your DATA WHICH YOU WANT TO SEND TO ACTIVITY C");
In Activity C :
ActivityC extends AppCompatActivity implements PassData{
//onCreate Stuff
#Override
public void data(String data) {
// print this data and see it's coming or not
}
yes sure.
for example in your Activity
class ActivityA extend Activity{
public static String abc = "hello";
}
in ActivityC
ActivityC extend Activity{
onCreate(){
String a = ActivityA.abc;
Log.d("test",a);
}
}

Finish the activity using component name in android

I am trying to finish one activity from another.
For that purpose I am having only the component name of that activity.
How can i finish that ?
1.Make your activity A in manifest file: launchMode = "singleInstance"
2.When the user clicks new, do FirstActivity.fa.finish(); and call the new Intent.
3.When the user clicks modify, call the new Intent or simply finish activity B.
FIRST WAY
In your first activity, declare one Activity object like this,
public static Activity fa;
onCreate()
{
fa = this;
}
now use that object in another Activity to finish first-activity like this,
onCreate()
{
FirstActivity.fa.finish();
}
SECOND WAY
While calling your activity FirstActivity which you want to finish as soon as you move on, You can add flag while calling FirstActivity
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
But using this flag the activity will get finished evenif you want it not to. and sometime onBack if you want to show the FirstActivity you will have to call it using intent.
You can do it in very simple way.
First create a static instance of your activity e.g. MainActivity, whom you want to finish like,
public static MainActivity act=MainActivity.this;
and now in another actvity e.g. MainActivity2 just call this line,
MainActivity.act.finish();
Try extending that activity and override the finish method
public class ma extends MainActivity{
#Override
public void finish()
{
super.finish();
}
}
You want to exit application after log out.
that time to user this
i.addCategory(Intent.CATEGORY_HOME);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
or try to another way like
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
moveTaskToBack(true);
finish();
}

How to pass data from fragment to ActionBarActivity?

I have PatientList class that extends fragment and other AddPatient class that extends ActionBarActivity. Now i want to pass static string from PatientList to AddPatient then its getting null.Where is the problem?? Why it is getting null???
not sure if I'm understanding but you can add a method in AddPatient and within PatientList call ((AddPatient) getActivity()).yourmethod(string)
in AddPatient:
public receiveString(String mystring)
{
// do whatever with mystring
}
in PatientList where needed e.g. onClick or something
((AddPatient) getActivity()).receiveString("hello")
if you want to pass data to an Activity you are starting with startActivity() instead you should do something like (if you are inside a fragment)
Intent intent = new Intent(getActivity(), AddPatient.class);
intent.putExtra("param_string", mystring)
getActivity().startActivity(intent);
in AddPatient
private String mMyString;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.yourlayout);
mMyString = getIntent().getStringExtra("param_string");
}
you can add Integer, Strings and Serializable stuff, multiple times
Instead of some dark magic proposed by #sherpya you should check how it is done by google at http://developer.android.com/training/basics/fragments/communicating.html
You should create an interface that is for that instead of creating dependency upon concrete Activity. What if you decide later to reuse this fragment in another Activity ?
In same cases you can use some event bus http://square.github.io/otto/

how to know the calling activity in android

I have an activity which is called by few other activities. For example: I have Activity1,Activity2,Activity3.
Activity1 calls Activity2 and pass parameter.
Activity3 also calls Activity2 and pass parameter.
Now based on the calling activity, Activity2 performs some task.
But how do I know which activity is calling Activity2??
can anybody plz help me??
If you start the activity with startActivityForResult(Intent, int), then you can get calling activity by getCallingActivity().getClassName().
A. If you can use startActivityForResult
As per Zain Ali's answer below: If you can start Activity with startActivityForResult() then you can get name of calling Activity class by this.getCallingActivity().getClassName();
B. If you can not use startActivityForResult
If you can not use startActivityForResult(), then you can use following method:
You can pass additional parameter in intent, check the value in activity and act accordingly.
1) Define an interface or constants class to define integer constants to indicate calling activity
public interface ActivityConstants {
public static final int ACTIVITY_1 = 1001;
public static final int ACTIVITY_2 = 1002;
public static final int ACTIVITY_3 = 1003;
}
2) Add extra parameter in intent while calling Activity2.
Intent act2 = new Intent(context, Activity2.class);
act2.putExtra("calling-activity", ActivityConstants.ACTIVITY_1);
// or ActivityConstants.ACTIVITY_3 if called form Activity3
startActivity(act2);
3) Check the value of this extra parameter in Activity2 and act accordingly..
int callingActivity = getIntent().getIntExtra("calling-activity", 0);
switch (callingActivity) {
case ActivityConstants.ACTIVITY_1:
// Activity2 is started from Activity1
break;
case ActivityConstants.ACTIVITY_3:
// Activity2 is started from Activity3
break;
}
In your calling activity (FirstActivity):
Intent i = new Intent(FirstActivity.this, SecondActivity.class);
i.putExtra("classFrom", FirstActivity.class.toString());
startActivity(i);
And add the following code in the onCreate of the called activity (SecondActivity):
Bundle bundle = getIntent().getExtras();
if (bundle.getString("classFrom").equals(FirstActivity.class.toString())) {
//Do some task
}
Notice that you should be carefully because the bundle object can't be null when you perform "b.getString("classFrom")".
You could pass an additional parameter that specifies the calling Activity.
I successfully use: (Activity).getLocalClassName()
Pass anything(String/ int etc.) to putExtra and base on that do the your work like
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("PARENT_ACTIVITY_REF", "ParentActivityIsA");
startActivity(intent);
And then receive in child like
String parentActivityRef = intent.getStringExtra("PARENT_ACTIVITY_REF");
then
if (parentActivityRef.equals("ParentActivityIsA"){
// do your work here
}else if ...{
// ...
}else{
//...
}
I'm Using This line
if (((((ActivityManager) getSystemService(Context.ACTIVITY_SERVICE)).getRunningTasks(1).get(0).baseActivity)).compareTo(new ComponentName(getPackageName()
, AnyActivityWantToCheck.class.getName())) == 0){
// do somthing .....
}
i hope it work with you
Another solution, using companion object as in the following example:
class MainActivity: BaseActivity {
...
LoginActivity.callerActivity = this
it.context.startActivity(Intent(getActivity(), LoginActivity::class.java))
...
}
class LoginActivity : BaseActivity() {
companion object {
var callerActivity: AppCompatActivity? = null
}
...
callerActivity?.let {
it.callSomething()
}
}

Accessing instance of the parent activity?

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.

Categories

Resources