Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use startActivityForResult from non-activity

Tags:

java

android

I have MainActivity which is an Activity and other class(which is a simple java class), we`ll call it "SimpleClass". now i want to run from that class the command startActivityForResult.

now i though that i could pass that class(SimpleClass), only MainActivity's context, problem is that, u cant run context.startActivityForResult(...);

so the only way making SimpleClass to use 'startActivityForResult; is to pass the reference of MainActivity as an Activity variable to the SimpleClass something like that:

inside the MainActivity class i create the instance of SimpleClass this way:

SimpleClass simpleClass=new SimpleClass(MainActivity.this); 

now this is how SimpleClass looks like:

public Class SimpleClass {  Activity myMainActivity;     public SimpleClass(Activity mainActivity) {        super();        this.myMainActivity=mainActivity;        } ....       public void someMethod(...) {         myMainActivity.startActivityForResult(...);     }  } 

now its working, but isnt a proper way of doing this? I`am afraid i could have some memory leaks in the future.

thanks. ray.

like image 634
rayman Avatar asked May 17 '10 11:05

rayman


People also ask

Can startActivityForResult still be used?

onActivityResult , startActivityForResult , requestPermissions , and onRequestPermissionsResult are deprecated on androidx.

How can we call method in activity from non activity class?

onCreate(savedInstanceState); setContentView(R. layout. main2); DataClass dc = new DataClass(); dc. show(); } public void call(ArrayList<String> arr) { // Some code... } }

How do I get data from startActivityForResult?

From your FirstActivity , call the SecondActivity using the startActivityForResult() method. Intent returnIntent = new Intent(); setResult(Activity. RESULT_CANCELED, returnIntent); finish(); Show activity on this post.

Can we call startActivityForResult from adapter?

Yes. You can call startactivityforresult() from adapter.


1 Answers

I don't know if this is good practice or not, but casting a Context object to an Activity object compiles fine.

Try this:

if (mContext instanceof Activity) {         ((Activity) mContext).startActivityForResult(...); } else {         Log.e("mContext should be an instanceof Activity."); }  

This should compile, and the results should be delivered to the actual activity holding the context.

like image 55
Some Noob Student Avatar answered Oct 12 '22 22:10

Some Noob Student