2

I have a reference to an anonymous class object that I want to pass to an activity. It is a kind of reference to a callback fn which gets called based on an action on activity i.e. click of button. But, I dont know a way to do so as activities can not be instantiated directly (done only through startActivity) and using intents will pass my object by value not by reference. So, I need tips on a good solution. I want to avoid statics.

takesavy
  • 135
  • 2
  • 16
  • use parcelable. – Shivang Trivedi Dec 06 '16 at 11:25
  • I don't think pass by reference is possible in Java/Android.. See this link http://stackoverflow.com/a/40523/3111083. In your case you can use Parceble or Serilizable.. – Sunil Sunny Dec 06 '16 at 11:49
  • 1
    Well, yes according to Java language, Java passes references ( they decided to call pointers references) by values. In C++ paradigm, it passes by references. – takesavy Dec 06 '16 at 13:04
  • @takesavy Can you give any source which say's pass by reference is possible in Java..( they decided to call pointers references thus confusing newbies .Because those references are passed by value.) – Sunil Sunny Dec 06 '16 at 13:34

3 Answers3

0

Short Answer: No You cannot pass objects as references to activities.

Shridutt Kothari
  • 7,326
  • 3
  • 41
  • 61
0

Try this

CustomListing currentListing = new CustomListing();
Intent i = new Intent();
Bundle b = new Bundle();
b.putParcelable(Constants.CUSTOM_LISTING, currentListing);
i.putExtras(b);
i.setClass(this, SearchDetailsActivity.class);
startActivity(i);

Afterwards to call

Bundle b = this.getIntent().getExtras();
if (b != null)
 mCurrentListing = b.getParcelable(Constants.CUSTOM_LISTING);
Ali Asheer
  • 117
  • 13
0

Here is the answer :
Create a public static method in the Activity to which you want to pass the reference of an object.

public static void openActivity(Activity activity, Class object){
        YourNextActivity.object = object;
        Intent intent = new Intent(activity, YourNextActivity.class);
        activity.startActivity(intent);
}

Call this method from current Activity :

YourNextActivity.openActivity(this, classObject);
Sahil Munjal
  • 463
  • 2
  • 15