Update main activity values from a different activity - java

I want to update textview in my main activity view.
I have main.xml file that contains the main application ascreen,
in that screen, I have textview that I need to update from time to time from another activity (class).
If I try to update those values from the main activity it work perfect, but when I'm trying to do it from deferent activity the application crashes.
Here is the method of the main activity, I need to know how to call it from the other activity.
Main Activity method:
public void update_counters(){
TextView sms_textview = (TextView) findViewById(R.id.sms_textview);
sms_textview.setText(String.valueOf(sms_missed));
}
Please Help

Indeed it's a bad practice to have any static references to activities (or other contexts). Activity are designed to be rather independed from each other.
You can receive a result from an activity that was started with startActivityForResult() method and than react appropriately.

Like #Roman said, it's a bad practice to touch the UI stuff from other activities, and activities should be independent. What you can do, is a little bit redesign your message passing method. One might be good is to use the broadcast receiver, it also guarantees a better extensibility of your program.
So, whenever your 'other' activity need to call the update_counters, it turns to broadcast such an intent. Your previous MainActivity should register to listen to that broadcast, and update the UI as necessary. What would be the best is you can have several more instance of that activity, or other activity that can register to that broadcast as well.

Is there only one instance of your main activity? If so, store a static reference to it in the main activity class, initialize it in onCreate. Then have a static method that uses that reference to get to the instance:
static MainActivity TheMainActivity;
static public void update_counters()
{
TextView sms_textview = (TextView) TheMainActivity.findViewById(R.id.sms_textview); sms_textview.setText(String.valueOf(sms_missed));
}
The in the other activity:
MainActivity.update_counters();
This is called a singleton. Or, sometimes, a global.

Related

Adding a widget from activity to another activity's in Android Studio

I'm developing a task reminder app and still not familiar with Android Studio. The layout was an Activity Form with a floating action button that opens the second activity for inputting name, date, time, etc., the second activity has a 'create' button that supposes to add a checkbox widget to the main activity form and I was having difficulties to make it work unlike at java where you just have to add it directly on its respective container.
By the way, this is how I created the object for my checkbox...
private class task extends androidx.appcompat.widget.AppCompatCheckBox{
task me;
public task(#NonNull Context context) {
super(context);
me=this;
me.setText(taskName);
}
}
it's not correct to add a widget in another activity in real-time, there are many solutions for this case, the simplest way is to start the second activity with startActivityForResult and in the second activity, return changes to the first activity and on onActivityResult handed if there are any changes or not, if yes create your widgets based on the returned result.

Same asynctask but different result handling in onPostExecute()

Currently I have an AsyncTask declared both in my main activity class and in my widget class. The code is the same except for the result handling in onPostExecute (in activity the result retrieved goes to a textview within activity and in the widget it goes to a textview in my widget).
I'd like to move the AsyncTask to an external java file (to avoid code duplication) and somehow call it from other different classes (like my widget and main activity) with different result handling. I guess I can't just pass a method name as a parameter to call it from onPostExecute, but is there something else I can do?
The short answer to your question is NO, you cannot do anything about this. In general, AsyncTasks are Activity-specific, and are defined as inner classes inside different Activitys so that they have access to methods defined in that Activity.
You can go ahead and define the same AsyncTask inside the Activity and the widget.

Update TextView from another Activity

I have two Activities in one application.
First one updates its TextViews every 3 seconds. It works fine.
When the keyguard (lock screen) is activated the first activity launches the second activity which appears over the lock screen (in order to show data even if the screen is locked). It also works fine.
I would like the TextViews of the second activity to be updated periodically by the first activity. I have played hours with this and tried a lot of suggestions I found with Google but none of them worked for me. The second activity always crashes with NullPointerException at the moment when the TextView.setText() is called.
What is the best practice for doing this?
Thanks in advance for any help.
I don't think there is a good way to do this, as your first activity could get collected by the system, and you generally don't want to do work after onPause has been called.
I would move that logic that updates the views into a service that runs in the background. Since it sounds like you only need this service while the application is running I would create a bound one.
http://developer.android.com/guide/components/services.html
You can pass the data on calling another activity as :
Intent intent =new Intent(FirstActivity.this, SecondActivity.class);
intent.putStringExtra("TextName","Value");
startActivity(intent);
As Ashish said you could use EventBus.
Add the library to your app and in your Second Activity register your activity in the EventBus in onCreate method:
EventBus.getDefault().register(this);
Create a new class in your project to define an event type:
public class TestEvent {
public TestEvent() {}
}
So in your second activity create a method to receive the event:
public void onEvent(TestEvent event) {
//stuff to do
}
Now, in your first activity you just have to "fire" the event in the method executed each 2 seconds:
EventBus.getDefault().post(new TestEvent());
Each time you execute post method, the onEvent of your second activity will be run.
A way to do it is by defining a Singleton object that holds the value to be displayed on the TextView, for instance, a Integer or a String.
Both activities have access to read/write into this object. So when you come back to the second activity, maybe on the onResume() method..you can the following:
public void onResume() {
super.onResume();
textview.setText(""+ MySingleton.getInstance().getValue());
}
On the other activity:
public void updateMethod() {
int newValue = .....;
MySingleton.getInstance().setValue(newValue);
}
This will make sure that whenever you come back to this activity (as onResume() is called), the value will be updated into the TextView. Of course, assuming that you are updating the value from the other activity accordingly.
Note this is the simplest solution you can do, professionally, I would do an event driven solution, where the observer gets notified when the value is changed. For that you can play with http://square.github.io/otto/ library.

Activity Lifecycle and the stack of activities

I have an activity with the following screen scheme:
|------> Activity1
MainActivity |------> Activity2
The application navigation only use startActivity() calls and the standard "back button" function.
Considering an Activity as created when its in between the onCreate and the onDestroy methods.
May I assume that when the activity1 or 2 is created then the MainActivity is created too?
There is no guarantee that the MainActivity will still be alive when you have Activity1/2 in the foreground. Definitely it will be created when the app starts since it is the only way to reach to Activity1/2.
Once the MainActivity is covered by another activity it will be in Stop state and can be killed by the system when resources is needed.
You can have some control over this behavior by specifying android:noHistory="true/false" in your activity definition, which by default set to false
Yes, when Activity1 or Activity2 is created, then by your definition MainActivity has also been created. So, if you are trying to access variables or methods from within MainActivity, then will be there.

Fragments onClick method in fragment element

I read quite some articles about fragments, but I am still confused about how to do what.
I have a MainActivity, which displays two fragments side by side. In one of the fragments I have a button and defined in the fragments layout XML for the button
android:onClick="buttonClicked"
Now I want to implement that method
public void buttonClicked(View view)
I would have assumed that this has to be implemented in FragmentA.java and not in MainActivity.java. But it only works if that method is implemented in MainActivity.java. Why is that? To me that doesn't make sense. Pre Honeycomb a method belonging to one activity stayed in that activity, now on a tablet I am merging many activities to one MainActivity and all the different methods are merged? Whatever do you put for example in FragmentA.java then? What if you have to start you an own activity because this app runs on a handheld, then the onClick method has not to be in the MainActivity but in the Activity which needs to be called then. I am pretty confused at the moment...
I'm not sure what the specific problem is, but maybe this will help.
From the Android documentation on Fragments:
You should design each fragment as a modular and reusable activity component. That is, because each fragment defines its own layout and its own behavior with its own lifecycle callbacks, you can include one fragment in multiple activities, so you should design for reuse and avoid directly manipulating one fragment from another fragment.
That is, you should never manipulate a fragment from another fragment; rather, this should be done through the underlying Activity. Read the "Creating event callbacks to the activity" section in this article for more information (it's important stuff!!).
On the other hand, if you want the button to perform an action within the Fragment itself (i.e. if you wanted a Button click to change the text of a TextView within the Fragment), you should implement this in the Fragment, not the Activity (this is because the resulting behavior is contained within the Fragment and has nothing to do with the parent Activity).
Leave a comment and I can clarify if my post is confusing... I only recently began to understand Fragment's myself :).
Well,
I guess it is related to hierarchy of android context structure.
Activity is host of all child views and hence you can say fragment is actually using its host's context.And that's why when you use onClick with fragment system always searches it in Host activity of fragment.
Check it on.
Android developer onClick attribute description
I haven't checked one thing but you could put a test.
By providing implementation in host activity rather than in fragment,but use onClick on layout file of fragment.It should call parent's method.

Categories