I've been working on android for few months, during my spare time, so probably i'm going to ask stupid questions.
In a class, I create an object, for example a button, and I'd like to 'reach' it from others classes.
Of course i could do it this way:
public class CreateButton{
public void createButton(){
Button myButton = new Button(context);
//I can "pass" my object to another class this way
ManageButton manageButton = new ManageButton(myButton);
// or this way
manageButton.writeButtonTextMethod(myButton);
}
}
or this way
public class CreateButton{
public Button createButton(){
Button myButton = new Button(context);
return myButton;
}
}
public class ManageButton{
public void writeButtonTextMethod(){
CreateButton createButton = new CreateButton()
Button myButton = createButton.createButton();
myButton.setText("W");
}
}
I'm wondering if there's a way to 'reach' myButton, created in createButton.class directly from ManageButton.class (and other classes).
With the code above, I have to 'call' createButton.class from ManageButton.class or vice versa to be allowed to manage myButton.
I can do it making myButton static, but it's not correct make view static.
For example, i can easily reach variables created in a class that extends Application. Is there something similar for views?
Much people/guides/articles claim is possible and correct sharing objects (and fields) between activities by using Application, this way:
Such people are idiots, as myButton will introduce a memory leak unless this is done very carefully.
So, I'm still not sure how i should share objects (TextView, Button, ImgaeView etc.) among different activities.
You don't share widgets between activities. At most, you share model data between activities (or, better yet, pointers to centrally-stored model data).
In a Web app, you do not share DOM nodes between Web pages, as that is not possible. At most, you share data passed as GET parameters and the like between Web pages, or you store data in local central storage (cookies, local storage, IndexedDB, etc.). Android activities are like Web pages -- they are loosely coupled.
If you have pieces of your UI that are so tightly coupled that they absolutely need to share widgets, they should not be separate activities.
Views are not meant to be shared across Activities. Even if you do disregard this and share them, you're more than likely to run into a WindowManager$BadTokenException, which essentially means you can't alter Views outside of its parent Activity.
However, to answer your question in a more general way about sharing non-view objects, the Application class is the right way to go. However, making the objects static is not the right way to do. Instead, make them instance variables, and access them in in your various activities by using:
Application application:
//Below line is in onCreate()
application = this.getApplication();
After that, simple access it using
application.myObject; //Or you could use getters and setters. Your choice.
Not quite sure why would u like to share one button between two activities?!
It is either button in ActivityA or ActivityB? No need, or use to do it..You shouldn't do it.
EDIT: This is more Java Basics topic then Android.. And from what I understood, u call "class" something that IMHO is method (because u can't CALL the class and because what did you described).
Best advices I can give u here:
Study Java basics (methods, classes, objects, constructors, inheritance..),
Study Android basics (simple examples with 1 activity til u understand it good),
Make MyButton Class which will extend standard button,
Create button(s) and change their properties
This few tasks will make u busy for some time. Take it easy because it will be easier later with complicated apps. Hope I helped you. Cheers
EDIT2: In last example u wrote (in comments to this answer), nothing make sense because as we wrote u before u don't share button between two activities. Pause! Read it again: You should't share button between two Activies. Questions u asked are not clear because for A and Z u can't say just class and "share" button between them. Which class? no line of code written so it is really difficult to figure out what u want.. :s
LAST LAST EDIT: Man.. Please understand that u r missing basics of Java. No bad intentions here, just try to guide u and tell u exactly what u should study. Why? Because it doesn't surprise me that you are confused to explain what u mean when classes are with one method named exactly the same.. They are just objects "doing something", u want to "manage" them by adding variable in constructor which doesn't exist etc.. Learn, next time write immediately code to save time for all of us. Cheers and enjoy learning
Related
I'm writing an android application which will have two types of users.One is admin that s gonna make adding and removing needed stuff and user that is gonna just read only.And I dont know a word about how can i make authentication between them.I need some source and advice.So if I can hear some advice.I really become so happy :)
Thanks in advance.
There would be several approaches to this. One rather quick that gives some flexibility would be to:
1) Create an:
interface ApplicationRights {
boolean writeX()
boolean canSeeButtonY()
}
Then you have a static variable of ApplicationRights interface somewhere accessible from anywhere in the application. (there would be many options for this, this is just a simple way)
To complement this you have two classes:
class AdminRights implements ApplicationRights {
...
}
and
class UserRights implements ApplicationRights {
...
}
Then in that static variable, as soon as you know if it's a User or Admin you
create and put either the UserRights or AdminRights in there. Doing so will allow you to customise this behaviour on a more finegrained level.
And whenever you add a new piece of code that will differ from a User and Admin you can easily add another boolean method in the interface to decide upon the rights. (This would also easily allow you to create more roles than users and admins)
Then to decide and save this to repeat it you can use for example SharedPreferences for knowing which user to create.
I am working on my second Android Application, first being, hello world. The application code is quite crazy looking because I love to test new libraries and ideas in it. I have been working on this application for well over 3 months and one of my activities is getting way to large and difficult to work with. I find myself getting lost in the code and it is taking longer to do simple things. There might be simple solutions to solving this issue. I really want to split my activity into two and reference each other if possible. Is there are any suggestions to simplifying and organizing code that would be greatly helpful. Even example will help me very much.
Part of my activity is adding a ton of data into a database and the other part is a long equation with multiple values. Another part is implementing the HoloGraphLibrary (Which I love). It is also implementing a listView with custom adapter. It also has a custom dialog............ I can go on and on. I hope you get my point.
EDIT
Going to work with this.
HoloGraphHelper holoGraph = new HoloGraphHelper();
holoGraph.initialize();
Try creating classes for each responsibility.
A Database Helper that has functions to insert data too:
DatabaseHelper database = new DatabaseHelper();
database .insertData(whatever);
A HoloGraphHelper that initializes the HoloGraph
HoloGraphHelper holoGraph = new HoloGraphHelper();
holoGraph.initialize();
And so on.
Break into multiple files. First classes defined in the Activity like the adapter. Change anonymous classes to classes defined in their own file. Look for ways to break out other related code into a class.
Right click on src folder of your Project and select new - class to create a new class. You can use a class for storing methods but you won't be able to display anything on screen.
To display contents to user, you can create a new Activity bu pressing Ctrl + N and selecting Android - Android Activity.
The best way is modularise your code.
I.e split your code into various related modules, for example a separate class for each part that your testing. So you could have a database entry class, a class for Gui testing, i.e. for your custom dialog. That class does all the work for that test, into various functions, I always try to keep functions as small as possible as they are easy to read.
As an example for your database entry, you could have a function which checks the database if the record already exists and then insert it. But a better way would be your insert function only performs the insert code and instead within this function it calls CheckIfDatAlreadyExists function which can return a bool so you know whether you should go ahead and insert the record. This would keep the code tidy and clean to manage.
Then from your main activity all would need to do is instantiate the relative class and call the relevant method.
This question is more like a discussion about how you guys would do it.
I'm developing an application that has an Avatar Creation, but this creating occurs across two different Activities.
In the first one the user selects whether is man or a woman and a name, in the next Activity the user has to select his face, hair, clothes and etc.
Since the views for hair and etc changes if the user is a man or a woman how would you implement a way to pass the gender value to all the Views?
I was thinking about using a static member to hold the value so I could access inside my views, or maybe I should use SharedPreferences to do it.
I think using the SharedPreferences is a more elegant way to do it but I'm wondering if there isn't any other better and more elegant way of doing it.
Has anyone thought about other implementations?
If its only a small information like "gender" i don't see much harm using "Static" variable(Ofcourse the static variable will become null if your app crashes when its in the background).
SharedPreference will come good if you want the information to be persistent(But i don't see you need this).
One more choice is you do can extend the application class to store the static data across activities.
You could pass the gender to the next Activity with start activity Intent. Example:
Intent intent = new Intent(this, NEXT_ACTIVITY.class)
intent.putExtra("gender", genderVariable)
startActivity(intent);
And retrieve the value in NEXT_ACTIVITY class on onCreate() like this:
String genderVariable = ""
Bundle parms = getIntent().getExtras()
if (parms != null) genderVariable = parms.getString("gender")
Then, pass gender to all your views and persist the genderVariable on SharedPreferences or onSavedInstanceState bundle. I prefer onSavedInstanceState.
Hope it helps.
I think there are many ways of which 4 I think are better. It ofcourse depends on what kind of data you want to store.
For Lists or hashmaps, using a singleton class would be helpful.
Using a static class would help, but might leak memory. You should be very careful and always check using logcat, MAT before releasing your app.
Using preferences or database.
Passing data as Intent extra (parcelable if needed).
Using SharedPreferences would be the better way to share some global values across the application.
I have a view that displays all the levels of my game. These levels are read by the activity and then passed into the view. I could read them from the view, but it's not really its responsibility, and I'm a fan of separation of concerns.
Right now, I'm calling a setter for this:
((GameView) findViewById(R.id.game)).setLevels(loadLevels());
However, I don't like the fact that the view will be dysfunctional if I forget to call the setter. Is there a better way to pass the levels in?
It is also a bit a matter of preference. Theoretically it's perfectly fine to pass the levels as you're doing. Alternatively, if you need more than just set the levels, but provide further functionalities (i.e. also saving of levels) I normally use a separate class responsible for handling such things (i.e. a Repository, some "Manager" class etc...). This class is then passed into the View on the constructor preferably s.t. one is forced to provide it. Of course, in order to separate things, I use interfaces rather than specific implementations s.t. it may then look as follows:
public class MyView {
public MyView(ILevelLoader levelLoader){
this.levelLoader = levelLoader;
}
...
}
Often, this may not work, because the view is something instantiated by the framework directly rather than by the application. In such a situation you're forced to do it through an appropriate setter. It is some sort of MVC/MVP pattern.
Just for your interest, you might also want to take a look at IoC containers and dependency injection. Guice provided by Google is a nice framework I've already used on Android.
I hope I didn't miss the point, but here goes:
Generally you have either a function setting something (like the text for a textview), or an attribute you set in the xml.
Take a look over at this answer I got on a question: How to layout a 'grid' of images in the center of the screen
There are some things the custom view needs, but lets take an example: 'numColumns'.
you can set it using setNumColumns (that would be the equivalent of your loadLevels() ? )
you can ignore it, it'll revert to default.
you can set it as an attribute lik so: app:numColumns="3"
You can try to use the attribute or the default in the class to accomplish this.
Make your view an abstract class with an abstract method getLevels()? This way, when you instantiate the class if you forget to pass the levels in your code won't compile.
Whether or not this is better is a matter of taste I guess :)
I am new to Android development.
I want to know how you all manage objects.
For eg we make object as A a = new A(); and then manage that object.
But, here, we call A.class;
My concern is that i dont want to call onCreate(),nor do i want to push UI screen.
I just want to make 1 static object for 1 screen;and want to manage it throughout my application
that is, instead of calling A.class; can i call A a = new A(),and manage that object without pushing,and whenever i need i push that screen. Is there someway ?
Thanks...
I just want to make 1 static object for 1 screen;and want to manage it throughout my application that is
That somehow describe what an Activity is for. Your complete question suggest that you have no idea how Android works and why it is meant to be. You should start at least with the fundamentals and than work through tutorials to get a feeling. Fundamentals can be found here: http://developer.android.com/guide/topics/fundamentals.html