Call public void function from different activity android - android

How can I call public void function from FirstActivity in SecondActivity?
// FirstActivity
public void thisFunction(){
// do something
// do something
}
in Second Activity
if(x){
FirstActivity.thisFunction();
}
but returns error:
Non-static method 'thisFunction()' cannot be reference from a static context

Static functions are functions of class and don't depend on any objects of that class
Class.staticFunction() (no need to instantiate), you can call it everywhere
public static void thisFunction(){
// do something
// do something
}
Then in SecondActivity:
FirstActivity.thisFunctions();

Related

How do we cast context to fragment reference?

I have a class 'Common' and a fragment 'FragmentTest'. The 'Common.java' is a general class that have some common functions for other activities..Those functions are accessed by context of each activities.. And here I am passing the fragment's context to a function in that class. I am doing like this
In Fragment :-
Common commonObj = new Common();
commonObj.myfunction(this.getActivity(),"Do you want to Update ?");
And in Class after some operation i'm trying to return back to fragment class.Like this
:-
public void myfunction(Context context , String str){
//....//
if(context.getClass().isInstance(FragmentTest.class)){
**FragmentTest mContext = (FragmentTest)context;**
mContext.FunctionInFragment();
}
}
But i have error in this..Because i cannot cast the context to fragment reference.
Somebody please help..
Firstly you can't cast a Context to a Fragment as Fragment doesn't extend Context. Activity does extend Context which is why when you do this from an Activity what you are trying works.
I'd suggest ideally that the methods in your Common class should be totally unaware of the existence of your Fragment. This way they are not 'coupled' together. To achieve this you can use a callback interface.
Create an interface as follows:
public interface Callback<T> {
onNext(T result);
}
Then you can change your method in Common to the following:
public void myfunction(Callback<Void> callback , String str){
//....//
callback.onNext(null);
}
Then when you call the method in Common from the Fragment you would do it like this:
Common commonObj = new Common();
commonObj.myfunction(
new Callback<Void>() {
#Override
public void onNext(Void result) {
functionInFragment();
}
},
"Do you want to Update ?"
);
If you needed to send data back to the function then you can change the return type of the callback. For instance if you wanted to pass back a string you would use Callback<String> and then the method in the original call would look like this:
new Callback<String>() {
#Override
public void onNext(String result) {
}
}
And in your Common class you would call it like this:
public void myfunction(Callback<String> callback , String str){
//....//
String result = "Hello from common";
callback.onNext(result);
}
You can do something like this:
public void myfunction(BaseFragment fragment, String str){
//....//
if(fragment.getClass().isInstance(FragmentTest.class)){
FragmentTest fr = (FragmentTest) fragment;
fr.FunctionInFragment();
}
}
i.e. using some base fragment(BaseFragment) and inherit from it.

android passing data from class to activity

I have been looking for a long time for a simple way to pass data (string type) from class to activity.
I found some tutorials about passing data from activity to class but is it possible to do the opposite, passing data from class to activity ?
if you import the class in your activity (which is also a class by the way) you can easily access the classes attributes.
example: MyClass.java
package edu.user.yourappname;
public class MyClass {
public string infoToPass = "whatever";
}
MyActivity.java
package edu.user.yourappname;
import edu.user.yourappname.MyClass
public class MyActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
String myString = MyClass.infoToPass;
}
}
i have no IDE to type this in atm it might contain some errors :S but i hope you get the idea.
if you need more specific help you have to provide a code sample.
also, what do you want to achieve exactly? maybie there's a different approach.
cheers!
Create Interface and implement that in your activity. Pass the activity instance in your class and and call that instance with interface method whenever you like.
To be more clear, create an interface and use it as following:
public interface SomeInterface{
public void passValue(String value);
}
public SomeActivity extends Activity implements SomeInterface{
// place any code you want in your activity, onCreate, onResume, etc.
private void someMethod(){
// Wherever in your activity, initialize your class with your activity.
SomeClass someClass = new SomeClass(this);
someClass.someMethod();
}
public void passValue(String value){
// do whatever you want with your value
}
}
public class SomeClass{
private SomeInterface someInterfaceInstance;
public SomeClass(SomeInterface someInterfaceInstance){
this.someInterfaceInstance = someInterfaceInstance;
}
public void someMethod(){
// Some code...
someInterfaceInstance.passValue("Hello World!");
// Some more code...
}
}
Here is a easy way of doing it -
By defining static variables
In your class, make the String whose value you want to pass public static like this -
public static String pass;
And then in you activity, you can directly access it since it's a public variable like this -
String receive = className.pass;

Using delegates for AsyncTask

I'm having trouble implementing a delegate in my android app.
In my GetData class I have nested asynctask, and I need to notify my main activity when all the work has actually finished.
I came up with this answer from Mohd Mufiz
What is the best way for AsyncTask to notify parent Activity about completion?
But I always get stuck at the same point:
in my GetData class I call a constructor with the delegate as only argument:
public class GetData {
private TaskDelegate delegate;
public GetData(TaskDelegate delegate) {
this.delegate = delegate;
}
...
}
In my main activity I don't know what I have to pass to get it working:
GetData getData = new GetData(**???**);
Going from the question you linked to, that defined TaskDelegate as :
public interface TaskDelegate {
public void taskCompletionResult(String result);
}
You can pass GetData any instance of a class that implements TaskDelegate - but typically, that would be the object that creates it - ie. your main activity (and so, therefore, it would also implement "void taskCompletionResult(String result);"). That then means you can pass "this" to GetData's constructor, so :
public class MyMainActivity implements TaskDelegate {
public void someMethod() {
GetData getData = new GetData(this);
}
public void taskCompletionResult(String result) {
// do stuff
}
}

Accessing R from a BroadcastReceiver

I want to change a TextView in the onReceive method of my BroadcastReceiver, but I can't access it with findViewById because it's not an activity.
I don't want to create a private class for the BroadcastReceiver in my activity.
How can I get access?
Define an interface and use a callback to let the activity know that a broadcast event has been received.
public Interface BroadcastReceiverListener {
void onReceive(int arg1, String arg2); ..<----add arguments you want to pass back
}
In your BroadcastReceiver class
ArrayList<BroadcastReceiveListener > listeners = new ArrayList<BroadcastReceiveListener >();
...
public void addBroadcastReceiveListener (BroadcastReceiveListener listener){
if(!listeners.contains(listener)){
listeners.add(listener);
}
}
public void removeBroadcastReceiveListener (BroadcastReceiveListener listener){
if(listeners.contains(listener)){
listeners.remove(listener);
}
}
In your OnReceive
for (BroadcastReceiveListener listener:listeners){
listener.onReceive(arg1, arg2);
}
In your Activity:
public class MyActivity extends Activity implements BroadcastReceiveListener {
...
broadcastReceiver.addBroadcastReceiveListener(this); <---- the instance of your receiver
...
}
public void onReceive(int arg1, String arg2){
// do whatever you need to do
}
Note. Because you use an interface, any class (not just an Activity) can implement it so you can update anywhere in your app. The BroadcastReceiver class doesn't know or care. It just calls the listeners, if any are registered.
Now, you don't need to access R, or anything to do with the UI since your Activity is the only class that knows about, and can change, your UI - which is the Android way!
[EDIT]
The arguments are whatever you need them to be.
Think of the Interface as a contract. It says that anyone who implements it, must implement the onReceive() method and that the method will be called with an integer and a String. It's up to you what arguments you need, if any.
BroadcastReceiver.onReceive() calls the onReceive callback of the interface and passes in the int and String as arguments.
You could change the Interface definition to pass a bool for example.
public Interface BroadcastReceiverListener {
void onReceive(boolean arg1); ..<----add arguments you want to pass back
}
Then your caller looks like this:
for (BroadcastReceiveListener listener:listeners){
listener.onReceive(someBooleanValue);
}
And your callback looks like this:
public void onReceive(boolean theCallerIsReady){
if(theCallerIsReady){
// do interesting stuff
}
}

How can I call a function in my main Activity class from a custom Gallery view in Android?

I have a custom gallery view in which I am overriding some methods. I would like to be able to call a function in my main activity from this class. How do I make a reference back to my main class?
I thought I'd just push the class reference into CustomGallery by creating a setter function ---> g.setBaseClass(this);
CustomGallery g = (CustomGallery) findViewById(R.id.playSelectionGallery);
g.setSpacing(10);
g.setCallbackDuringFling(false);
g.setAdapter(new ImageAdapter(this));
g.setSelection(1);
registerForContextMenu(g);
g.setBaseClass(this);
Problem is this is of type Context and someFunctionToCall() will result in a not a member of this class error. In my custom class I have:
public void setBaseClass(Context baseClass)
{
_baseClass = baseClass;
}
private void callSomeFuntionOnMyMainActivityClass()
{
_baseClass.someFunctionToCall();
}
All I want to do is call back to my main class, called ViewFlipperDemo. This would be easy in As3. Any thoughts? Hopefully I'm missing something really simple.
That's actually not a good idea... but you can do it this way:
private void callSomeFuntionOnMyMainActivityClass()
{
((ViewFlipperDemo)_baseClass).someFunctionToCall();
}
What you should do instead is implementing a simple observer which allows you to notify the Activity that something happened. That's one of the main OO principles, your custom class shouldn't know anything about your activity class.
Observer pattern example
The Observer interface:
// TheObserver.java
public interface TheObserver{
void callback();
}
Your custom view:
public class CustomGallery{
private TheObserver mObserver;
// the rest of your class
// this is to set the observer
public void setObserver(TheObserver observer){
mObserver = observer;
}
// here be the magic
private void callSomeFuntionOnMyMainActivityClass(){
if( mObserver != null ){
mObserver.callback();
}
}
// actually, callSomeFuntionOnMyMainActivityClass
// is not a good name... but it will work for the example
}
This is the activity that will benefit of the observer (notice that now you can use your custom view on different activities not just one, that's one of the key reasons to implement it this way):
public class YourActivity extends Activity{
// your normal stuff bla blah
public void someMethod(){
CustomGallery g=(CustomGallery)findViewById(R.id.playSelectionGallery);
g.setObserver(new TheObserver(){
public void callback(){
// here you call something inside your activity, for instance
methodOnYourActivity();
}
});
}
}
You will notice that this design pattern (observer) is widely used in Java and Android... almost any kind of UI event is implemented using observers (OnClickListener, OnKeyListener, etc.). By the way, I didn't test the code, but it should work.

Categories

Resources