How to reload an activity once when it open - java

I want to go from Activity1 to Activity1 (with newly loaded data), but the problem is that when I use recreate(); in onCreate(); the activity just keeps reloading and reloading till the program crashes.
So is there anyway to make the activity reload one time when its opened (By onCreate and onResume).
Clarification: I need to reload the activity to get the new data from a web service (due to a problem that caused the old data to show instead of the new ones) so the only way this will work is by reloading my activity.

Add a flag variable inside your activity ("Instance Variable")
var mIsInitialLoad = true
, then In whatever lifecycle method or function inside your activity:
if (mIsInitialLoad) {
recreate()
mIsInitialLoad = false;
}

You can check this link
Lifecycle State (Android Developers Site)
Example
#Override
public void onResume() {
super.onResume(); // Always call the superclass method first
// Call Method to check data
}
package com.note.principal
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.webkit.WebChromeClient
import android.webkit.WebView
import android.webkit.WebViewClient
import com.note.R
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Check the data when activity is starting
}
override fun onResume() {
super.onResume()
// Check the data when activity finishes
}
}

Related

Is it possible to invoke a back button click programmatically?

I've seen plenty of answers explaining how to override and add functionality to a back button press via user's interaction, but almost none of the answers explain how to programmatically trigger a back button press without any user input. Answers that do address it give somewhat deprecated code samples that don't really compute.
From your activity just call => onBackPressed(),
or form your fragment => activity?.onBackPressed()
//simply put this code where you want to make back intent
super.onBackPressed();
According to official docs onBackPressed is deprecated in Api level 33.
you can now use onBackPressedDispatcher please follow these steps:
Add android:enableOnBackInvokedCallBack="true” inside application tag
in manifest folder.
Kotlin code :
class YourActivity : AppCompatActivity() {
lateinit var button: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button = findViewById(R.id.txt)
button.setOnClickListener {
onBackPressedCallback.handleOnBackPressed()
}
}
private val onBackPressedCallback = object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
finish() //this finishes the current activity
// Your business logic to handle the back pressed event
}
}
}
And here is old way of implementation:
Java :
buttonBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
YourActivity.super.onBackPressed();
}
});
Kotlin :
buttonBack.setOnClickListener{
super.onBackPressed()
}

get result from activity in adapter

In my fragment I have a recycler view and set adapter to it. With adapter's help I can start start second activity by clicking on items in recycler view. But when I finish second activity I need to call one method again in my fragment.
I can start activityForResult only in adapter, but I write onActivityResult method in it.
How can I get result from the activity or call method in fragment again? Is it possible to get result from activity in adapter?
In general, the Adapter should only care about creating RecyclerView cells. Any other logic is better put elsewhere (Activity/Fragment, or better - ViewModel/Presenter)
In case you don't have a view model per RecyclerView cell, I would use an interface to let the Fragment know that an item was clicked:
public interface ItemClickedListener {
fun itemClicked(String itemName)
}
In your Adapter:
public class YourAdapter(private val listener: ItemClickedListener): RecyclerView.Adapter<ViewHolder> {
}
In your Fragment (where you create your Adapter) pass "this" as the ItemClickedListener:
adapter = YourAdapter(this)
Have your Fragment implement ItemClickedListener & onActivityResult:
public class YourFragment: Fragment, ItemClickedListener {
override fun itemClicked(String itemName) {
startActivityForResult(...)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
// Let your adapter know whatever is needed
}
}
Back in your Adapter, instead of calling startActivityForResult upon item click - call listener.itemClicked
This is a basic example of removing the navigation logic from the Adapter.
Now the Fragment is making decisions about navigation, which might be OK if no business logic is involved.
For cases where more business logic is needed, a better paradigm should be used (MVP, MVVM, MVI, etc..).
As Android recommends using MVVM, I would advice you to read this:
https://developer.android.com/topic/architecture

Pass data by pressing tab in android

I wonder how to pass data by pressing tab. I have two tab in activity, named Info and Details. When Details tab is clicked, I want to pass the title editText to next activity.
P/S : Without button clicked
MainActivity
tabs.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
override fun onTabReselected(p0: TabLayout.Tab?) {
}
override fun onTabSelected(p0: TabLayout.Tab?) {
val position = p0?.position
when (position) {
0 ->
supportFragmentManager.beginTransaction().replace(
R.id.frame_container,
CreateWOInfoFragment()
).addToBackStack(null).commit()
else -> supportFragmentManager.beginTransaction().replace(
R.id.frame_container,
CreateWODetailsFragment()
).addToBackStack(null).commit()
}
}
override fun onTabUnselected(p0: TabLayout.Tab?) {
}
})
FragmentOne would be sending the data entered in EditText to FragmentTwo.
So add an interface in fragment one and let the activity implement this interface,
in Fragment one call the method to send data and in main fragment will handle it to send it to fragment two.
Please check this example Android Passing Data between Fragments

How to finish the main activity from other Activity

Hello how do you finish Main activity
Assume that there are 3 Activities and 1 Fragment
LoginActivity , MainActivity, infoFrgMent, ChangePwdActivity.
The scenario is when I loggedin in LoginActivitythen MainActivity will show up LoginActivity will finish() then i will go to my info which is 'infoFrgMent' then i want to change my password after i changed my password.
LoginActivity will shows up Again to relogin but whenever i try to press back MainActivity shows up and didn't finished.
You need to remove previous activities form stack
setFlags to intent from MainActivity to LoginActivity
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
refer : https://developer.android.com/guide/components/activities/tasks-and-back-stack.html
What you need is to add the Intent.FLAG_CLEAR_TOP. This flag makes sure that all activities above the targeted activity in the stack are finished and that one is shown.
Another thing that you need is the SINGLE_TOP flag. With this one you prevent Android from creating a new activity if there is one already created in the stack.
Just be wary that if the activity was already created, the intent with these flags will be delivered in the method called onNewIntent(intent) (you need to overload it to handle it) in the target activity.
Then in onNewIntent you have a method called restart or something that will call finish() and launch a new intent toward itself, or have a repopulate() method that will set the new data. I prefer the second approach, it is less expensive and you can always extract the onCreate logic into a separate method that you can call for populate.
To finish another Activity you have to create a static method to finish this Like here:
MainActivity.java
private static MainActivity activity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
activity = this;
}
public static void finishThis()
{
try
{
if (activity != null)
{
activity.finish();
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
And call it like this:
AnotherActivity.java
MainActivity.finishThis();
That's it

Activity returning null and producing NullPointerException even though I implemented it

I have a class extending ParseQUeryAdapter so I can use the notifyDataSetChanged feature. The adapter class is called mainAdapter.
Here's my notifyDataSetCHanged method in the mainAdapter:
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
MainActivity mainActivity = new MainActivity();
mainActivity.getItems();
}
Here's my getItems() method in MainActivity:
public void getItems(){
if(adapter == null){
Toast.makeText(MainActivity.this, "null", Toast.LENGTH_SHORT).show();
}
}
The app crashes on loading. As you can see, I planted an if so that I can see if adapter was null. But it still crashes.
According to the debugger, it says in green after getting to the if line, "adapter:null". However, I have this in onCreate():
adapter = new mainAdapter(this);
And I declared it:
mainAdapter adapter
Is there a method I can put in that will solve my issue? Although I am implementing the class, why is it still null? I clearly stated that adapter = new mainAdapter()
You should never instantiate your activity classes with new; they should be interacted with using startActivity() and related APIs.
An activity created with new won't be registered with the ActivityManager, won't show up on the screen, and won't have any of it's lifecycle callbacks called.
Since your MainActivity instance's onCreate() method has not been run, adapter has not been created.
In your case, it seems like you would want your ParseQueryAdaptor subclass to have a reference to your activity in some way, so that it can access the right one.
If you want to reference an existing activity then you have to pass the activity object to where you want to use it (or use getContext or getActivity when your in a class that has that available).
One of the things you can do is create a method that passes the MainActivity object into your ParseQUeryAdapter. Then when you are calling stuff in your adapter do: activityObject.whatevermethodyouwantocallontheactiviy() be shure to error check the activity object first though.
IE:
private MainActivity activity;
public void setup(MainActivity activity){ this.activity = activity;}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
if(activity != null){
activity.getItems();
}
}

Categories

Resources