NEWBIE ALERT!
Here's the situation. I've got an Android ListActivity class (AppWindow) that contains all the methods that create and update the UI for my application. It includes a method (refreshWindow) that calls setListAdapter, and therefore must be non-static. So far, I've been using a separate class (FileHandler) to perform manipulations on files that are referenced by the AppWindow class. I've reached a point where I want to call the refreshWindow method when a certain file manipulation has been performed. However, since the refreshWindow method is non-static, it seems that I would need to instantiate AppWindow and call the method through that instance. However, I'm not sure how to do this or if it's even a good idea. Perhaps I just need to move all of the FileHandler logic into AppWindow, although I'd prefer to keep them separate.
Here's a description of the situation in code form:
AppWindow.java
...
public class AppWindow extends ListActivity {
...
void refreshWindow() {
...
setListAdapter(new ListAdapter());
...
}
...
}
FileHandler.java
...
class FileHandler extends Activity {
...
static void doStuffToFiles() {
...
AppWindow appWindow = new AppWindow();
appWindow.refreshWindow();
...
}
...
}
Should I be doing this? If so, how do I properly instantiate AppWindow?
Create a static member variable; say act; in FileHandler
On creation of ListActivity set the variable act using 'this' variable of activity
Now you can access activity instance from FileHandler.
Update the UI must be in the UI thread. You can use handler to handle the message. The handler's constructor can contain the activity, so you can use it.
Related
I've been working on Xamarin for the past couple of years along with Android studio and I decided to create an application for a friend (full source code here https://github.com/nekrull/waiter don't be too harsh please :) )
The idea is that there is a base activity which exchanges fragments when a new screen should appear.
Fragments have everything that has to do with user interaction and the activity they are attached to handles the business logic.
To do this I have a base class CoreActivity/DataActivity which has some methods most Fragments use (like blocking the back button) and some helper methods (like calling a method on an attached fragment of a specific class) , a CoreInteraction that responds to this activity and
CoreFragment/AttachedFragment which is used as the base of all view fragments
so for example the view fragment would look like this:
public class GroupsFragment extends AttachedFragment<GroupsFragment.GroupsInteraction> {
//this is what we expect to be able to call in the parent
public interface GroupsInteraction extends CoreInteraction {
Group get_shown_group();
void new_group();
void select_parent();
}
}
which is basically a fragment that expects its attached activity to be able to respond to the interaction methods.
the activity fragment would look like this:
public class MainActivity extends DataActivity<MainData> implements
GroupsFragment.GroupsInteraction, (other interactions here) {
}
The problem is that since the application I'm working on has only one Activity with many small screens, the code inside the base activity will get big, that does not cause a problem with the application or compiling or anything else. But it makes it really hard to find what I'm looking for easily.
What I used to do in Xamarin is something like this:
public partial class MainActivity : DataActivity<MainData> {
}
for the initialization activity and then each interaction would get its own file like this:
public partial class MainActivity : GroupsInteraction {
}
It had the same effect (since the class is compiled as a single class) but the code would be tidy and easy to read.
Obviously there are no partial classes in Java, but is there a way to delegate the implementation of an interface to another class?
Something along the lines of saying "when you're invoking a method from interface a, invoke it from that class" without actually writing stuff like :
public Group get_shown_group() {
return new GroupHandler(this).get_shown_group();
}
public void new_group() {
new GroupHandler(this).new_group();
}
public void select_parent() {
new GroupHandler(this).select_parent();
}
Thanks in advance for any help you can provide
Something along the lines of saying "when you're invoking a method from interface a, invoke it from that class"
Taking you literally what you describe is plain delegation, a class does not implement some or any functionality itself, instead it wraps a class implementing the desired functionality, calling the methods of said wrapped class. You could even switch implementation at runtime, just changing the wrapped class as you go (assuming the classes share a common interface, of course). Of course that does not "spare" you from writing the delegations yourself.
class Wrapper implements GroupsInteraction {
private final GroupInteraction gi;
public Wrapper(GroupsInteraction gi) {
this.gi = gi;
}
Group get_shown_group() {
return this.gi.get_shown_group();
}
// ... other interface impls
}
Additionally, you should keep the GroupHandler as a member instead of creating a new Object each time, so
public Group get_shown_group() {
return new GroupHandler(this).get_shown_group();
}
becomes
public Group get_shown_group() {
return this.groupHandler.get_shown_group();
}
You can try Delegation Pattern
BaseActivity {
MyDelegateClass delegate;
void example() {
delegate.example();
}
}
P.S. both activity and delegate implements same interface
Details here
Giving the following class of my android Project :
Preview extends SurfaceView implements SurfaceHolder.Callback
and
A extends Doc
I don't really know how to ask and I know that this is not really good but I want that from Preview, I call an abstract method of Doc. In this Doc's method, I have to call a method of the previous Object of Preview.
This is an example :
From Preview.java :
Doc _doc = new A();
private void myMethod() {
this._doc.process(this)
}
From A.java :
#Override
public void process(Preview p) {
p.processA();
}
The problem is that I got an error :
The method process(Preview) in the type Doc is not applicable for the arguments (new Camera.PreviewCallback(){})
However, I can't change this judging by the fact that I want to call the method from Preview. I tried many thing such as cast etc. None of them works.
Thanks for your help !
PS : I am on Eclipse under Windows.
Assuming you are calling A.process(this) from an anonymous inner class (of type Camera.PreviewCallback I presume, hence the error message), you have to write A.process(Preview.this), since a standalone this refers to the inner class and not to the Preview instance.
The method process(Preview) in the type Doc is not applicable for the arguments (new Camera.PreviewCallback(){})
It simply means you are passing the object of Camera.PreviewCallback but in your method public void process(Preview p) You want an object of Preview.
If you have written this code in side an anonymous class, then this won't point to the Preview class. It will point to the object of inner anonymous class.
Thus you need to write A.process(Preview.this)
I'm somewhat new to Java and I was wondering if there was a way to change the function of a class somehow.
Class pager = new Pager();// everything is initialized
pager.dostuff() = function(){};
Is there a specific name for this and is it possible to do in Java? If not, is there a language that does allow it?
Thank you for your time.
Edit:
To clarify the question because originally it seemed like I wanted to initialize the new class with different functions. That is not the case. I want to change it after it's already been created. The reason for this is that I'm working with android and the class I'm getting is from the xml. Is it possible to change the class' function when I get the class like so?
Pager pager = (ViewPager) findViewById(R.id.pager)
I feel like I'm going to have to create a new class, which is ok but I wanted to see if I could do it this way.
In java you can override method at runtime like -
Pager pager = new Pager(){
#Override
public void dostuff(){
....
}
};
Runtime it will create subclass of Pager and override the doStuff method.
Of course ..It is possible through overriding of a class through an annonymous inner class while inheriting all the properties of the class being overriden.
Pager pager = new Pager(){
public void dostuff(){
....
}
}
PS:- Beware,Outside the anonymous inner class ,you may invoke only those methods present in your parent class through the instance of your annonymous inner class
Java does not offer a functionallity like this.
Maybe it is possible for you to override the function in a sub-class.
What you Showed above can be done in Ruby (i think).
Override
Pager pager = new Pager() {
#Override
public void doStuff() {
doSomethingElseFunct();
}
};
I have found one answer that appears to say I should create a separate class and make a static MyApplication object and make a get method. Then any class can call MyApplication.get() to retrieve the context.
Is there any other cleaner way? This is my situation:
I have a class A and a class B. Class A contains an object from class B (let's call the object b). In class A I call, "b.play()". However, I get a null pointer exception because class B needs to pass a context to the MediaPlayer.create() method.
Until now I threw together a hack and from class A I called.... "b.play(this)" and simply passed the context to B. However that is pretty ugly and looks like a bad use of OOP.
Any thoughts?
This problem seem to arise a lot in Android development. One solution to obtaining a reference to a specific Context is subclassing the Application and grab a reference to the Context which you want.
public class MyApplication extends Application {
private Context context;
#Override
public onCreate() {
super.onCreate();
this.context = getApplicationContext() // Grab the Context you want.
}
public static Context getApplicationContext() { return this.context; }
}
This solution however requires that you specify the name of your subclass in your manifest.
<application
android:name=".MyApplication"
</application>
You can then use this anywhere in your application like this in non-activity classes.
MyApplication.getContext(); // Do something with the context! :)
If class B requires a Context to operate, then I don't see any problem having class A provide that to it (through a parameter on the play method, a parameter in a constructor, etc).
I don't think you are doing any poor OOP by providing class B the dependencies that it needs to do it's job.
Passing this around is a viable way of doing things, especially if this is the activity that creates the object in need of a Context. Sometimes, I'll put the Context into the constructor (like public MyObject(Context context){this.context = context;}), so that you don't need to send it every time. However, if your object is shared across multiple Activities, you should probably update the context it is looking at with the new Activity, though I haven't tested what happens if you use the old activity.
I've answered also here.
You can do that using ContextWrapper, as described here.
For example:
public class MyContextWrapper extends ContextWrapper {
public MyContextWrapper(Context base) {
super(base);
}
public void someMethod() {
// MediaPlayer.create(this, ...)
}
}
I have created an application using the texttospeech api and I have all the functionality within one class. I would like to split this into several classes but when I do so I have a null exception error.
The texttospeech api has onclick buttons. Within these buttons I try to call a method from another class for the functionality.
I extend the class 1 with the current class I am using.
I then add the method image() within the class 1:
public void image() {
if(currentHelloIndex==0){
alertDialog.show();
}
else if (currentHelloIndex == 2) {
Image.setImageResource(R.drawable.books);
} else if (currentHelloIndex == 3) {
Image.setImageResource(R.drawable.mic);
}
Currently no variables are declared in class 1 as it is using the variables in the main class.
I then call this method in the main class. This doesn't seem to be working the class 1 has no onCreate method it is just a standard class which extends the main class.
I would appreciate any help on this as I need to separate the functionality into separate classes.
Edit:
currentHelloIndex is an int which is set to 0 in the main class
if the button is clicked an currentHelloIndex is 0 an alertdialog in the main class will appear
if the button is clicked and currentHelloIndex is 2 this will set the Image which is an ImageView in the main class with the image set.
I have put into the main class: static SoundGameScore sound;
Within the main class I have called sound.Image(); in an onclick. Please can someone let me know what I have done wrong, thanks.
You should use some of the refactoring functionality in your Java IDE (you ARE using a Java IDE, right?)