I have a one notification service which fires at every 5 seconds and get the data and parse it and then display it..
But this mechanism works only for the home screen of the app.
I want this to be done in every screen of the app.For that should i write the same code in every activity of the project ? It is very tedious job . I want to make it generalize ..
How to do that ?? any ideas??
you can make BasicActivity and have method in that Activity and call that method inside onCreate();
now extend every Activity in your project from your BasicActivity
If you are talking push notification service, this idea seems to problematic. tell us more what are you exactly trying to do.
you do something like this in some utility class
public static void showNotifction(Activity a)
{
//notify
}
and over this if you have any call back methods.. Then create an interface with those methods and implement them in all those Activities and you can do this..
public static void showNotifction(CommoInterface a)
{
if(a insatncof Activity){
//notify
a.callBack(); // callBack is a method in the interface..
}
}
Related
I'm extending the Application class for my additional custom need. And I'm calling a method inside that. As the expected behaviour, it is getting invoked for type of Android components(Activity, Service, Broadcast receiver, etc.,) But I want that too be invoked only on Activity. Is that any other way to overcome this problem ?
public class MyApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
// the below method needs to invoked only for service
// but now called for all application components
myCustomMethod();
}
....
}
But I want that too be invoked only on Activity.
Can't be done. The Application instance will run if one component of your Application is open.
You need to do the customized stuff in another class and open it just when the instance of your desire component is open.
just add your code to onCreate method of your entry-point activity. If you want it to be called once per session - add two int keys to your shared preferences - app_launch_count and method_invoke_count. Increment first on App's onCreate and check the second in your Activity's onCreate if first greater then invoke the method :)
Move myCustomMethod() into the activity. An Application has no way of knowing what triggered the creation of its process.
Or, use registerActivityLifecycleCallbacks() on Application to register an ActivityLifecycleCallbacks object, and put your myCustomMethod() logic in onActivityCreated(). This requires a minSdkVersion of 14 or higher. That will tell you when each activity is created after your process is instantiated — if you only care about the first one, you would have to unregister the callbacks in your onActivityCreated() implementation.
I have two classes One is MainActivity.java and other is simple Java class ConnectMe.java. I have Single Button and Single EditText on MainActivity. I am using a button to Login So it is named also as btnLogin. On its clickListener, I am taking the Ip from the EditText(in string format) and calling the Login function from the ConnectMe.java class which takes string as a parameter.
Now in ConnectMe class I check if the application is connected to the server it should show the Connected Message in EditText and Also it should show the Toast on MainActivity. And I have no Idea How to do this as I am new to android.
here is my sample code
public class MainActivity extends Activity {
Button btngLogin;
EditText etIp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
ConnectMe connectMe = new ConnectMe();
connectme.LogMeIn(etIp.getText().toString);
}
});
}
here is my java class for connection
public class ConnectMe {
MainActivity mainActivity = new MainActivity();
void LogMeIn(String ip){
MyConnectedmethod.Connectednew (new Runnable() {
public void run() {
mainActivity.setText("connected");
}
}
I know the code is not proper, But I just want to give you an idea. I am getting the null point exception on the line in which I am setting text of EditText.
With some research, I have find out that I can not touch the views from the Thread and Runnable directly . and I was told to use runOnUiThread. like mainActivity.runOnUiThread but it is also not helping giving error of nullpointexception.
So Please help me as I am new to android programming
A lot going on here.
There's basically no instance in which you should instantiate an activity.
The Activity doesn't have a .setText() method. So that's the null pointer.
There's a much easier way to do a simple worker task than creating your own thread and managing it yourself. Use AsyncTask
http://developer.android.com/reference/android/os/AsyncTask.html
EDIT:
You can run as many AsncTasks as you like. Without more context, it's hard to say exactly what your best approach is. But, it sounds like you probably want to run some kind of service. (http://developer.android.com/reference/android/app/Service.html). There's a couple different flavors available, depending on what you want to do. If it needs to run all the time, rather your app is running or not, then use a start service. If it needs to run only so long as the UI is going, then a bound service is the option. If it needs to do something every so often than some combination of intent service/broadcast receiver/alarm manager is the route.
You may not even need a service. If you're just loading several things use the loader manager. For downloading content a SyncAdapter may be the way to go. The point is that after 24APIs most common tasks already have a ready made solution. So, in most cases, you don't need to fiddle with threads yourself.
The NullPointerException happens because you`re missing to declare what object Button btngLogin refers to.
btngLogin = findViewById(R.id.yourbuttonnameinxml);
Do the same with your EditText.
i think you better read this first, starting another activity with intents and sharing a message between two activities (classes): http://developer.android.com/training/basics/firstapp/starting-activity.html
Inside my Application class, I have a long-running function (e.g. downloading new data). Once the operation finishes, I want to inform several related activities to refresh their UI. What is the best way to achieve this in Android (the equivalent of postNotification in iOS)?
public class MyApplication extends Application{
public void onCreate() {
downloadDataInBackground(); // call operationDone when finished
}
private void operationDone(){
sendMessageToAllRelatedActivities();
}
}
You can use: Broadcast Receivers for this. Please see following link:
http://www.vogella.com/articles/AndroidBroadcastReceiver/article.html
I think you should use the Observer design pattern in order to notify that a certain status is changed
Observer
I have a set of commands that I want my app to run when it's restarted, regardless of what activity it's on. I know I need to put an onRestart() into every one.
Since it's the same set of commands regardless of what activity it's on, is there a way I could have them all refer to a single function for that? It seems like that would be better then having to copy paste the commands into each onRestart() handler. It will be a lot less work if I need to change the set of commands too.
You have a couple of options, depending on the code.
You can put it in a helper class as a static function: public static void doWork() { .. } This should work, unless whatever you are doing depends on being in the activity. You can generally just pass it what it needs though, like the Context.
Or, you could extend Activity with your own class, MyActivity and place the work in that onResume. Then extend MyActivity for each of your real activities. They will now automatically do that work when you call super.onResume(). This works well as long as you really want to do the same thing in every activity, and don't use a lot of specialized activities like ListActivity.
Edit:
public class MyHelper {
public static void doWork() {
// do your work here
}
}
public class MyActivity extends Activity {
public void onResume() {
super.onResume();
MyHelper.doWork();
}
}
A search for "static method" will provide more details.
Derive all your activities from a single class (something like ActivityBase) that, in turn derives from system-provided Activity. Then implement onRestart() in ActivityBase.
Is it your application that is restarting from scratch? Or just your activities that are restarting/resuming?
The Application class has an onCreate() method, and you can extend Application in your app to override its behavior. Just remember to change the name of the application in AndroidManifest.xml so it picks up your custom Application class when starting. This code would run before any activities start up. But it won't run every time an activity is stopped and restarted. If that's what you need, this won't do it.
You could also implement a singleton class that contains an initialize() method, or restart() method. You simply call it from onRestart() in each activity you want it in. It sounds like this special code ought to be localized away from your activities so I don't think I'd recommend extending Activity to put the code there.
I am working on an Application that require some interaction between two activities, and I am not sure of what is the best way to achieve it:
One of the Activities is a "Logbook" (Just a ListView that displays a bunch of events).
The other Activity allows the user to create the events, that will be sent (and displayed in the Logbook).
How do I notify my Logbook Activity when a new Event is ready to be added?
Also, where should I add the event to the database? From the Logbook Activity, when I add it to the ListView, or from the NewEvents Activity, as soon as it's ready?
Thanks!
Ok, I found how to do it, using a BroadcastReceiver:
In my Logbook activity, I just set up a new custom receiver onCreate():
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_logbook);
registerReceiver(new EventReceiver(this), new IntentFilter("SEND_NEW_EVENT"));
Now, I can make the calls in my newEventActivity:
public void sendToLogbook(int eventId){
Intent i = new Intent("SEND_NEW_EVENT");
i.putExtra("newEvent", this.newEvents[eventId]);
sendBroadcast(i);
}
Of course, I had to create my CustomReceiver Class, and override the onReceive() method to do what I want:
public class EventReceiver extends BroadcastReceiver {
private ActivityLogbook activity;
public EventReceiver(ActivityLogbook activity) {
this.activity = activity;
}
public void onReceive(Context context, Intent i) {
this.activity.addToReport((Event)i.getParcelableExtra("newEvent"));
}
}
It works great so far, but if you do have comments/concerns about this, please tell me!
Thank you!
If I recall cporrectly the Notepad project which is included in the android sdk and is also part of the tutorials online is a good examaple which should satisfy your needs.
To borrow from MV-* (Model-View-something or other) patterns, separate your idea of the Model (in this case, your Event objects) and what is displaying them (the View, or in your case an Activity) and it'll become more clear.
If you have your events somewhere global where all activities can interact with them, then you can work with the model and display the model from wherever and however you choose.
One simple suggestion is have a class (EventController or something like that) that allows you to interact with the Events collection, and make it available through a derived Application class. I can explain further if that doesn't make sense. I have a pattern I use in my Android apps whereby all Activity classes have access to a custom global Application instance, so my model is a model and can be accessed by whatever Activities I want to have access.
This is merely one approach, and as always, there are many that may suit your needs.
One possibility would be:
The ListActivity gets all the data each time it is resumed and updates the ListView accordingly
The NewEventActivity does all the job of storing the Event and simply finishes
You can improve it a bit more:
The ListActivity gets all the data when it starts
The ListActivity starts the NewEventActivity expecting a OK/CANCELLED result
The NewEventActivity does all the job of storing the Event and returns a result saying OK or CANCELLED
Depending on the result it gets from the NewEventActivity, ListActivity reloads its data or not