Get Activity after startActivity(Intent i) - android

In one method i start a new activity
public void start(){
Intent i = new Intent(mContext, Screen.class);
mContext.startActivity(i);
//Here i want to get the new activity
Activity a = ...
//Do something with new activity
}
After calling starActivity() i need to get that new Activity and doing something with it.
Is it possible??
EDIT:
Well i have these methods on my Screen class:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
loadedScreen = false;
}
public void loadScreen(String folderResources, String nameXml, String nameScren){
//Do something
}
loadScreen read an XML file and create by code all user interface, instead of doing in onCreate
In another class I call foo():
public void goToScreen(String nameScreen){
Class screen = Screen.class;
Intent i = new Intent(mContext, screen);
mContext.startActivity(i);
//Here in screen.getMethod... i need use a instance of Screen, which i think it have to be created in `startActivity()`
Method loadUrl = screen.getMethod("loadScreen", String.class, String.class, String.class);
loadUrl.invoke(screen, "folder-s","screen1","screen1.xml");
}
I need call to loadScreen after startActivitybecause this method load all views. I use reflection for doing this. So i need get that new Activity

After calling starActivity() i need to get that new Activity and doing something with it.
Once you call startActivity(), the other activity does not yet exist -- it will not exist for some time.
I need call to loadScreen after startActivitybecause this method load all views.
Call loadScreen() from onCreate() of the Screen activity.
If you wish to pass the values of folderResources, nameXml, and nameScren to Screen, do so by calling putExtra() on the Intent you use with startActivity(). Then, Screen can call getIntent().getStringExtra() in onCreate() to retrieve those values, in order to pass them to loadScreen().

Related

How do I recreate the activity only once after opening the application?

How do I recreate the activity only once after opening the application?
I tried to do this, but it didn't work. Endlessly recreate()
refreshLang() in onCreate
private fun refreshLang() {
PreferenceManager.getDefaultSharedPreferences(this).apply {
val checkRun = getString("FIRSTRUN", "DEFAULT")
if (checkRun == "YES") {
PreferenceManager.getDefaultSharedPreferences(this#MainActivity).edit().putString("FIRSTRUN", "NO").apply()
recreate()
}
}
}
and SharPref.putString("FIRSTRUN", "YES").apply() in onDestroy to make it work again the next time you run it.
Please refer: Activity class
recreate()
It create new instance and initiates fresh activity lifecycle.
So when you call recreate() it will call onCreate() and will go in endless loop.
You have add some condition to avoid this overflow.
Edit:
Use .equals instead of ==
if ("YES".equals(checkRun)) {
PreferenceManager.getDefaultSharedPreferences(this#MainActivity).edit().putString("FIRSTRUN", "NO").apply()
recreate()
}
I suggest you not to use recreate(). It will call onCreate and onDestory().
Refer below code.
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
boolean recreateRequested = true;
Intent currentIntent = getIntent();
if (currentIntent.hasExtra("recreateRequested")){
recreateRequested = currentIntent.getBooleanExtra("recreateRequested", true);
}
if (recreateRequested) {
Intent intent = new Intent(this, MyActivity.class);
intent.putExtra("recreateRequested", false);
startActivity(intent);
finish();
}
}
you can't compare two Strings like this in your if condition
checkRun == "YES"
these are two separated instances of String, so they never be equal in the this meaning (== - same object)
use this instead
"YES".equals(checkRun)
equals will compare "content" of compared objects, in String case it will compare text
use onResume Method
#Override
public void onResume() {
super.onResume(); // Always call the superclass method first
}

how to link a new activity in android studio using a clickable text

Please how do I link a new activity from my main activity using a clickable text. I have set the text to clickable from my main.xml but I don't know how to call the new activity from my MainActivity.java class. I know I have to use this code "textView.setOnClickListener(new View.OnClickListener());" I found in a similar question, but I don't know how and where to place it on my MainActivity.java class so that it calls a the next activity I named display
Check out Intent. You use these to start new activities or services within your application.
You're correct in that you have to assign an OnClickListener interface to your text, after you made it clickable. In the interface's onClick() method you would need to do something like this.
For example:
#Override
public void onClick(View v) {
// Create the intent which will start your new activity.
Intent newActivityIntent = new Intent(MainActivity.this, NewActivity.class);
// Pass any info you need in the next activity in your
// intent object.
newActivityIntent.putExtra("aString", "some_string_value");
newActivityIntent.putExtra("anInteger", some_integer_value);
// Start the new activity.
startActivity(newActivityIntent);
}
In the next activity, you can retrieve the intent used to start it, so that you'll have access to the data you passed from the first activity, like so:
#Override
public void onCreate(Bundle savedInstanceState) {
// Get the intent that started this activity.
Intent startingIntent = getIntent();
// Retrieve the values.
String aString = startingIntent.getStringExtra("aString");
Integer anInteger = startingIntent.getIntExtra("anInteger", 0); // 2nd param is the default value, should "anInteger" not exist in the bundle.
// Use the values to your hearts content.
}
Hope that helps.

How to refresh fragment UI when come back to it

I am new to android and learning things with fragments and have made a demo for it,in that i am having a fragment from which we can go to another activity at there some calculation is performing and after that we come back to frgament at that time i want to dislay that calculation value to my fragment's textview,So which life cycle method should i use to do so?i already used onresume which is not working...
public void onResume () {
super.onResume();
//tvFollowings.setText((sharedConnect.getCurrentUser().userFollowingCount)
// + " Following");
System.out.print("------user count is-------" + String.valueOf(sharedConnect.getCurrentUser().userFollowingCount));
Toast.makeText(getActivity(), "------user count is-------" + String.valueOf(sharedConnect.getCurrentUser().userFollowingCount), Toast.LENGTH_SHORT).show();
}
Yout have to use startActivityForResult(...) when calling your activity, then you can get any information you need in your fragments onActivityResult().
The best approach which works, toggle between onPause and onResume. No need to even bother the parent activity
private boolean allowRefresh = false;
#Override
public void onResume() {
super.onResume();
//Initialize();
if(allowRefresh){
allowRefresh=false;
//call your initialization code here
}
}
#Override
public void onPause() {
super.onPause();
if (!allowRefresh)
allowRefresh = true;
}
onResume will always be called when your fragment gets loaded, so initial state of allowRefresh should be false so the fragment does not get loaded twice
Once you open new activity whilst the fragment is active, onPause is called, here set allowRefresh to true only if allowRefresh is false.
When the fragment regains focus, check if allowRefresh is true and redo your initialization. A good code practice is put all your initialization code in one function.
You can use Bundle to do the same in Android
Create the intent:
Intent i = new Intent(this, ActivityTwo.class);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocomplete);
String getrec=textView.getText().toString();
//Create the bundle
Bundle bundle = new Bundle();
//Add your data to bundle
bundle.putString(“stuff”, getrec);
//Add the bundle to the intent
i.putExtras(bundle);
//Fire that second activity
startActivity(i);
Now in your second activity retrieve your data from the bundle:
//Get the bundle
Bundle bundle = getIntent().getExtras();
//Extract the data…
String stuff = bundle.getString(“stuff”);
You can refer here for more.POST
You can use the onResume() method of the Fragment
public class Fragment_ABC extends Fragment {
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_abc, container, false);
return view;
}
#Override
public void onResume() {
super.onResume();
// PERFORM YOUR OPERATION OVER HERE
}
}
Let me know if this works for you ! :)
In your fragment write below code and overide onActivityResult(int requestCode, int resultCode, Intent data) method
Intent intent = new Intent(getApplicationContext(),TrendingQuestions.class);
intent.putExtra("categoryId", Integer.parseInt(categoryId));
startActivityForResult(intent, 101);
In your next activity after you got the result just set result
Intent result = new Intent();
setResult(Activity.RESULT_OK, result);
finish();
If onActivityResult is not getting called please check this link
Then do one thing .. use the Activities onResume Method in which you are showing the Fragment and then from within this Activity's OnResume call the Fragment' Function where you want to refresh the Fragment.
For example.
You have a Activity_A in which you have defined the fragment, let it be Fragemtn_A. Now you are navigating to Activity_B from within this Fragment_A.
Now when you are leaving Activity_B, then the onResume() method of the Activity_A will be called for sure, and from the onResume() of Activity_A you can call the function of Fragment_A and perform your operations that you want.
For calling any fragment's function from withing the Activity you can follow this link :
Calling a Fragment method from a parent Activity
Let me know if this works for you! :)

Android: execute method after returning to main activity from intent activity

I have seen many examples with
startActivityForResult(Intent, int)
and then using
onActivityResult(int, int, Intent)
but for me I dont need to pass anything, I simply want to startActivity(intent), and when intent activity returns, a method get called in main activity..
Any tutorial on doing this?
EDIT:
Here a sample code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_options);
createEvent = (Button) findViewById(R.id.createEvent);
createEvent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(optionsInterface.this, MainActivity.class);
startActivity(intent);
}
});
}
here, after I return from MainActivity (press back, or just close it), I want the activity to perform a task ( with no data being passed from MainActivity)
you can use startactivityforResult().. it doesn't matter if you send any data back or not... when you use startactivityonResult() the method onActivityResult will get called...just check for the request code there and do whatever you want...sending back something is not necessary.
Instead of startActivity() you might want to use startActivityForResult(), so that you get a call back on result.

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