Using Child Class In Android - android

Sorry, I'm a newbie to Java and Android...
I've made an app that has a big main activity, I'm wanting to split it up into some child classes to make things easier to read, edit etc.
From my main class I (think) I am instantiating, and calling the child class, from within OnResume :
SetupButtons SetupButtonsObject = new SetupButtons ();
SetupButtonsObject.buildthem();
And in the child class I do:
class SetupButtons extends main {
void buildthem(){
//a load of things to setup buttons
}
}
The code I am using in buildthem() works fine when used in the main class, but is giving a nullpointer exception when used in the child class.
do I need to pass the main context to the child or something?
Many Thanks
Tom

Anything you use in the childclass that is not set there, but set in the main class, you must in some way get from the main class. So yeah, you need some context.
But before you do that: you might want to divide your app in classes that are logical parts of your sollution, as you can read in any OOP description. So not just chop it up in parts because it makes it smaller, chop it up in logical units that are actual good objects.
A quick type, hope I did not make any mistakes here, but see comments in child class.
class Parent{
public static int foo = 1;
public static int bar = 0;
public function somefunction(){
bar = 1;
myChild = new Child();
}
}
class Child extends Parent{
//you can find foo = 1
//but not bar = 0;
}

The Activity class isn't supposed to be instantiated by developer directly, leave this work to the android. If you wish to split it up why do you extend your main activity? You rather need to divide your app in logical parts as Nanne said.

In same class you can call that method directly. Like buildthem();

Related

Android app with weak reference and singleton

I'm in the process of completely redesigning my Android app. Before, EVERYTHING was in the same class.
So I tried to redraw everything so that the code is clearer apart Admob than the doc advice to put in the Main thread, I separate the different part of my code in class. So I used two technique: I created a songleton that contains variables that I want to have access to constantly,and I call my classes via weak reference.
Here is what it looks like:
For example, the UIManager class that needs to update the game's IU have a weak reference looks like this:
private static SoftReference<UIManager> ManageUI;
static{ManageUI= new SoftReference<>(null);}
static UIManager get()
{
if(ManageUI.get()==null)
{
ManageUI= new SoftReference<>(new UIManager());
}
return ManageUI.get();
}
GameManager Manager=GameManager.getInstance();
to be able to use the findviewbyid for example I place in method argument the main class that is the mainthread
the singleton that contains all my variables that I want to have permanent access to looks like this:
private GameManager()
{}
/** Holder */
private static class Manager
{
/** Instance unique non préinitialisée */
private final static GameManager instance = new GameManager();
}
/** Point d'accès pour l'instance unique du singleton */
public static GameManager getInstance()
{
return Manager.instance;
}
To separate all in different class, I pass argument to my method so I can call au stuff belong to Activity like that:
(My main class is called GamePlay)
void OpenGlobalScene(GamePlay activity)
{
Manager.OnTitle=false;
if (!checkLayout(activity,R.id.globalscene)) {
LayoutInflater(activity,9, true);
LinearLayout GamePlan = (LinearLayout) activity.findViewById(R.id.globalscene);
GamePlan.setAlpha(Manager.AlphaBord);
}
}
For now, I have not noticed any problems except a few slownesses on old android phone 4.4.2.
Also compared to my old code were EVERYTHING was in the same class, it's much easier to change pieces of code (going to the inapp billing V3 was simpler since everything was in one class that I call like the others with weak referencre)
My questions are:
-What are the problems that such a structure might pose?
I had also chosen that structure to not load or leave in memory things that are not useful
-How are chance that Android will erase from memory an action in progress called with weak reference?
-As you can see I pass the activity has argument to the method, sometimes I pass it from a method to another. Is that fact can cause some trouble?
Thank you for your help.
Check Dagger2 is better than the clasic singleton https://developer.android.com/training/dependency-injection/dagger-android?hl=es-419
thanks for your answer and your tips. I'am gonna check this out.
Anyone else know something about consequences on memory when using weak references ?

Can we make a static method in a single class to move Intent multiple activities?

I have more than 50+ activities in a single project so each and every time I need to write code to move a single activity from one to other.
What is in my mind, may I make a single function which can move more than one activity from a single static method of a class?
Like given in code below.
public static void moveActivity(Parameters)
{
//Code to move activity
}
Or may I follow any other idea for the same.
Any help would be really appreciated.
Thanks in advance.
What is in my mind, may I make a single function which can move more than one activity from a single static method of a class?
I believe not because startActivity needs a Context which can't be used in a static context, I believe.
Or may I follow any other idea for the same.
This depends on what you are doing but maybe ViewPager and/or Fragments could make your life easier. If you have that many Activities then most likely you won't want to try and manage them all from one function anyway because you have to consider extras, flags, etc... You will have two lines to start an Activity (sometimes more) just write the code. What you are trying to do will most likely result in more headaches, IMHO.
If there is a lot of the same data that you are passing around and that is your concern then you can use Bundles to pass them all around.
Try this:
public class Utils {
public static void launchActivity(
Class<? extends Activity> nextActivityClass,
Activity currentActivity, Map<String, Integer> extrasMap) {
Intent launchIntent = new Intent(currentActivity, nextActivityClass);
if (extrasMap != null && extrasMap.size() > 0) {
Set<String> keys = extrasMap.keySet();
for (String key : keys) {
launchIntent.putExtra(key, extrasMap.get(key));
}
}
launchIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
currentActivity.startActivity(launchIntent);
}
}
To use it:
From your activity class, make this call:
Utils.launchActivity(ActivityB.class, this, extrasMap);

How to extend two library class in java class android [duplicate]

This question already has answers here:
Extending from two classes
(13 answers)
Closed 9 years ago.
I want to extend two library class files in a java class.How to do this.
You have not given more details about the question.
You can only extend a single class. And implement interfaces from many sources.
Extending multiple classes is not available.
You can use nested classes or inner classes
class A extends B {
private class C extends D {
// A , B , C , D accessible here
}
}
Why Use Nested Classes?
Compelling reasons for using nested classes include the following:
It is a way of logically grouping classes that are only used in one place: If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together. Nesting such "helper classes" makes their package more streamlined.
It increases encapsulation: Consider two top-level classes, A and B, where B needs access to members of A that would otherwise be declared private. By hiding class B within class A, A's members can be declared private and B can access them. In addition, B itself can be hidden from the outside world.
It can lead to more readable and maintainable code: Nesting small classes within top-level classes places the code closer to where it is used.
when to use nested classes
You can find more solutions on this link
Edit
This is an answer to you comment. You want to call method of outer class in inner class. This is an example.
class Outer {
void show() {
System.out.println("inside outter show");
}
class Inner{
void show() {
Outer.this.show(); //this is calling Outer class method into Inner class
Example e = new Example(); //create object of another class
e.show(); //call to method
System.out.println("inside inner show");
}
}
public static void main(String[] args) {
Outer o = new Outer();
Inner i = o.new Inner(); //create an object of Inner class
i.show(); //this is calling Inner class method from outside method
}
}
class Example
{
void show()
{
System.out.println("inside example show");
}
}
Output:
inside outter show
inside example show
inside inner show
Unfortunately in JAVA you can only extend a single class that means each Class can only extend one class. you can implement many interfaces but not extend.
however there are ways in which you can sort of surpass it, you can just make the libs public and then include them so you could create an instance and use their functions, you can create an inner class and use it for whatever purposes you need...
you can also create a chain of extension like:
public class A extends Activity
public class B extends A
so B will extend both...sort of
its hared to give you a working solution when we dont exactly know the issue,do you mean adding support libs? adding SDK? or really extending two classes (which is impossible straight forward).
#Aniket gave you an example of how to work around it so to speak...
hope I helped
sorry for the bad news:)

How to structure an app with many activities?

I am making an application presenting a showroom and at this points I have created way too much classes.
The main view is a GridView containing all the series of cars.(Each GridView Item opens a new class, so there are 9 classes with very similar code)
How can I structure it?
To put a bit more flesh on #g00dy, start by creating a class
class BMW {
// Reference codes for every series
public final static int SERIES_1 = 0;
public final static int SERIES_2 = 1;
// etc
public final static int NUMBER_SERIES = 9;
// All the code needed for every car
// eg.
public String giveManufacturuer() {
return "BMW"; // But see #g00dy - use string resources
}
public String giveSeries() {
return XXXXX; // Depends on which approach you choose, see below
}
public String giveModelName() {
return XXXXX; // Depends on which approach you choose, see below
}
}
You can either load all the variations into this class (add in references codes for every car and set up some tables to make indexing easy).
Or you could extend the class using inheritance for each class:
class Series1 extends BMW {
#Override
public String giveSeries {
return "Series 1";
}
}
class Series1M3Door extends Series1 {
#Override
public String giveModelName {
return "3 Door";
}
}
When you then instantiate the final class it will have all three functions working correctly.
This approach is neat, but will still give you a lot of classes. I suspect that for what you are doing, some well thought out information tables (accessed by series and model code) may work better inside a hidden class.
A different, perhaps better approach, might be to structure the code using the information that you are returning as the core classes.
I do not actually have the time to write all this down, mean a unifying class, but here's hint for you. Use a flag, which will indicate the model of the car (Z4,M6 for example), then use it inside the class to determine the tree on which the code should run. Replace the hardcoded values with string resources (just do it, no other remarks are necessary). When instantiating the class and using it's functions, take into account the flag and put it inside an if() condition or inside a switch. If some models require more code than the others, you can always encapsulate it in the part of the code which is responsible for the model. But avoid nesting too much ifs, because it will get messy, like having 100 classes defined which do 99% the same thing as the others. Always try to re-use your code as much as possible. It will reduce the writing (copy/pasting) repetitive stuff, also the size of the application, the memory it will need etc. Conclusion: try combining the common parts of the classes into one class ( to RULE THEM ALL :-) ) and use flags, to let the program knwo what to do there.

Beginner - using variables defined in one class in another class

So, lets say in my main activity, i have an array declared like this, that im not having any problems using inside any of main's methods:
public int currentPrices[] = {0,0,0,0,0,0,0,0,0};
Now, my buyDialog class is as follows:
package foosh.Frontier;
import android.app.Activity;
import android.os.Bundle;
import foosh.Frontier.*;
public class buyDialog extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// Be sure to call the super class.
super.onCreate(savedInstanceState);
currentPrices[0]=999;
//insert setup magic here
setContentView(R.layout.buydialog);
} }
Eclipse persistently says that currentPrices can't be resolved. How do I link a child activity to the parent activity's variables?
I may have done my intent wrong, as I'm quite new at constructing them. But here's that line, from main:
case R.id.buyButton1:
currentRes = masterRes.get(0);
Intent intent = new Intent();
intent.setClass(main.this, buyDialog.class);
startActivity(intent);
The simple answer is you have to qualify it with the containing instance's name.
So if the instance is myinstance to access the currentPrices field, you would do this:
myinstance.currentPrices
However, you really should be using getters and setters and there are a lot more issues here regarding actually getting a handle on the instance of the activity. I would suggest looking into an intro Java book before you get your hands dirty with Android. Check out http://math.hws.edu/javanotes/ for a good online introduction.
Based on your tag, I assume you have some notion of global variables. There is no such thing in Java. In practice, you can have static variables that are globally accessible. For instance
public class MyClass{
public static int MY_VALUE = 4;
}
You can access by writing
MyClass.MY_VALUE
However, with instance variables, that is, one's that aren't qualified by the static keyword, you have have an instance of the class that has been allocated via the new keyword.
For example
MyClass someInstance = new MyClass();
someInstance.currentPrices
The reason this is more complicated with Activities is because you don't have access to the instance of the activity class that is being used unless you do something really creative.
Does that make sense?
If you ever need to do this without making a static variable, you can also pass the array through the Intent as an extra, like so:
intent.putExtra("currentPrices", currentPrices);
startActivity(intent);
Then, once you're in the new Activity, retrieve it like so:
int[] currentPrices = getIntent().getIntArrayExtra("currentPrices");
It looks like you're modifying the original from the dialog though, so short of using startActivityForResult() and handling it that way, Chris' method is much simpler.

Categories

Resources