Android Passing Variable doesn't seem to click - android

I have created a random number and would like to pass it along to use in the same file just different class. Please help:
public void Start() {
int number = random.nextInt(3); // Gives a number such that 0 <= number < 2
then a few lines down I try to use number but it's telling me it's not a variable to use:
public void renderBackground(Canvas canvas) {
//TODO: you may wish to change background colors from here
if(number=="0") {
any kind of help is great appreciated!

The problem you are facing is because of the scope of variable number. I'm not sure you are using inner class or a separate class.
If it's a inner class, then declare the number at top of the first class like,
class Firstclass
{
public int number; // scope is public it can be accessed anywhere in class
method();
...
...
class Secondclass
{
method()
{
System.out.println("Your number is : " + number); // here you are accessing variable `number`
}
}
}
Also, try to change
if(number=="0") {
to
if(number==0) {

I think the problem is you are initializing 'number' inside a class, not the main class.
initialize number inside the main class then modify it in your method. ex:

Related

Using PixelCopy to take a screenshot [duplicate]

What is the use of anonymous classes in Java? Can we say that usage of anonymous class is one of the advantages of Java?
By an "anonymous class", I take it you mean anonymous inner class.
An anonymous inner class can come useful when making an instance of an object with certain "extras" such as overriding methods, without having to actually subclass a class.
I tend to use it as a shortcut for attaching an event listener:
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// do something
}
});
Using this method makes coding a little bit quicker, as I don't need to make an extra class that implements ActionListener -- I can just instantiate an anonymous inner class without actually making a separate class.
I only use this technique for "quick and dirty" tasks where making an entire class feels unnecessary. Having multiple anonymous inner classes that do exactly the same thing should be refactored to an actual class, be it an inner class or a separate class.
Anonymous inner classes are effectively closures, so they can be used to emulate lambda expressions or "delegates". For example, take this interface:
public interface F<A, B> {
B f(A a);
}
You can use this anonymously to create a first-class function in Java. Let's say you have the following method that returns the first number larger than i in the given list, or i if no number is larger:
public static int larger(final List<Integer> ns, final int i) {
for (Integer n : ns)
if (n > i)
return n;
return i;
}
And then you have another method that returns the first number smaller than i in the given list, or i if no number is smaller:
public static int smaller(final List<Integer> ns, final int i) {
for (Integer n : ns)
if (n < i)
return n;
return i;
}
These methods are almost identical. Using the first-class function type F, we can rewrite these into one method as follows:
public static <T> T firstMatch(final List<T> ts, final F<T, Boolean> f, T z) {
for (T t : ts)
if (f.f(t))
return t;
return z;
}
You can use an anonymous class to use the firstMatch method:
F<Integer, Boolean> greaterThanTen = new F<Integer, Boolean> {
Boolean f(final Integer n) {
return n > 10;
}
};
int moreThanMyFingersCanCount = firstMatch(xs, greaterThanTen, x);
This is a really contrived example, but its easy to see that being able to pass functions around as if they were values is a pretty useful feature. See "Can Your Programming Language Do This" by Joel himself.
A nice library for programming Java in this style: Functional Java.
Anonymous inner class is used in following scenario:
1.) For Overriding(subclassing), when class definition is not usable except current case:
class A{
public void methodA() {
System.out.println("methodA");
}
}
class B{
A a = new A() {
public void methodA() {
System.out.println("anonymous methodA");
}
};
}
2.) For implementing an interface, when implementation of interface is required only for current case:
interface InterfaceA{
public void methodA();
}
class B{
InterfaceA a = new InterfaceA() {
public void methodA() {
System.out.println("anonymous methodA implementer");
}
};
}
3.) Argument Defined Anonymous inner class:
interface Foo {
void methodFoo();
}
class B{
void do(Foo f) { }
}
class A{
void methodA() {
B b = new B();
b.do(new Foo() {
public void methodFoo() {
System.out.println("methodFoo");
}
});
}
}
I use them sometimes as a syntax hack for Map instantiation:
Map map = new HashMap() {{
put("key", "value");
}};
vs
Map map = new HashMap();
map.put("key", "value");
It saves some redundancy when doing a lot of put statements. However, I have also run into problems doing this when the outer class needs to be serialized via remoting.
They're commonly used as a verbose form of callback.
I suppose you could say they're an advantage compared to not having them, and having to create a named class every time, but similar concepts are implemented much better in other languages (as closures or blocks)
Here's a swing example
myButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
// do stuff here...
}
});
Although it's still messily verbose, it's a lot better than forcing you to define a named class for every throw away listener like this (although depending on the situation and reuse, that may still be the better approach)
You use it in situations where you need to create a class for a specific purpose inside another function, e.g., as a listener, as a runnable (to spawn a thread), etc.
The idea is that you call them from inside the code of a function so you never refer to them elsewhere, so you don't need to name them. The compiler just enumerates them.
They are essentially syntactic sugar, and should generally be moved elsewhere as they grow bigger.
I'm not sure if it is one of the advantages of Java, though if you do use them (and we all frequently use them, unfortunately), then you could argue that they are one.
GuideLines for Anonymous Class.
Anonymous class is declared and initialized simultaneously.
Anonymous class must extend or implement to one and only one class or interface resp.
As anonymouse class has no name, it can be used only once.
eg:
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
});
Yes, anonymous inner classes is definitely one of the advantages of Java.
With an anonymous inner class you have access to final and member variables of the surrounding class, and that comes in handy in listeners etc.
But a major advantage is that the inner class code, which is (at least should be) tightly coupled to the surrounding class/method/block, has a specific context (the surrounding class, method, and block).
new Thread() {
public void run() {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
System.out.println("Exception message: " + e.getMessage());
System.out.println("Exception cause: " + e.getCause());
}
}
}.start();
This is also one of the example for anonymous inner type using thread
An inner class is associated with an instance of the outer class and there are two special kinds: Local class and Anonymous class. An anonymous class enables us to declare and instantiate a class at same time, hence makes the code concise. We use them when we need a local class only once as they don't have a name.
Consider the example from doc where we have a Person class:
public class Person {
public enum Sex {
MALE, FEMALE
}
String name;
LocalDate birthday;
Sex gender;
String emailAddress;
public int getAge() {
// ...
}
public void printPerson() {
// ...
}
}
and we have a method to print members that match search criteria as:
public static void printPersons(
List<Person> roster, CheckPerson tester) {
for (Person p : roster) {
if (tester.test(p)) {
p.printPerson();
}
}
}
where CheckPerson is an interface like:
interface CheckPerson {
boolean test(Person p);
}
Now we can make use of anonymous class which implements this interface to specify search criteria as:
printPersons(
roster,
new CheckPerson() {
public boolean test(Person p) {
return p.getGender() == Person.Sex.MALE
&& p.getAge() >= 18
&& p.getAge() <= 25;
}
}
);
Here the interface is very simple and the syntax of anonymous class seems unwieldy and unclear.
Java 8 has introduced a term Functional Interface which is an interface with only one abstract method, hence we can say CheckPerson is a functional interface. We can make use of Lambda Expression which allows us to pass the function as method argument as:
printPersons(
roster,
(Person p) -> p.getGender() == Person.Sex.MALE
&& p.getAge() >= 18
&& p.getAge() <= 25
);
We can use a standard functional interface Predicate in place of the interface CheckPerson, which will further reduce the amount of code required.
i use anonymous objects for calling new Threads..
new Thread(new Runnable() {
public void run() {
// you code
}
}).start();
Anonymous inner class can be beneficial while giving different implementations for different objects. But should be used very sparingly as it creates problem for program readability.
One of the major usage of anonymous classes in class-finalization which called finalizer guardian. In Java world using the finalize methods should be avoided until you really need them. You have to remember, when you override the finalize method for sub-classes, you should always invoke super.finalize() as well, because the finalize method of super class won't invoke automatically and you can have trouble with memory leaks.
so considering the fact mentioned above, you can just use the anonymous classes like:
public class HeavyClass{
private final Object finalizerGuardian = new Object() {
#Override
protected void finalize() throws Throwable{
//Finalize outer HeavyClass object
}
};
}
Using this technique you relieved yourself and your other developers to call super.finalize() on each sub-class of the HeavyClass which needs finalize method.
You can use anonymous class this way
TreeSet treeSetObj = new TreeSet(new Comparator()
{
public int compare(String i1,String i2)
{
return i2.compareTo(i1);
}
});
Seems nobody mentioned here but you can also use anonymous class to hold generic type argument (which normally lost due to type erasure):
public abstract class TypeHolder<T> {
private final Type type;
public TypeReference() {
// you may do do additional sanity checks here
final Type superClass = getClass().getGenericSuperclass();
this.type = ((ParameterizedType) superClass).getActualTypeArguments()[0];
}
public final Type getType() {
return this.type;
}
}
If you'll instantiate this class in anonymous way
TypeHolder<List<String>, Map<Ineger, Long>> holder =
new TypeHolder<List<String>, Map<Ineger, Long>>() {};
then such holder instance will contain non-erasured definition of passed type.
Usage
This is very handy for building validators/deserializators. Also you can instantiate generic type with reflection (so if you ever wanted to do new T() in parametrized type - you are welcome!).
Drawbacks/Limitations
You should pass generic parameter explicitly. Failing to do so will lead to type parameter loss
Each instantiation will cost you additional class to be generated by compiler which leads to classpath pollution/jar bloating
An Anonymous Inner Class is used to create an object that will never be referenced again. It has no name and is declared and created in the same statement.
This is used where you would normally use an object's variable. You replace the variable with the new keyword, a call to a constructor and the class definition inside { and }.
When writing a Threaded Program in Java, it would usually look like this
ThreadClass task = new ThreadClass();
Thread runner = new Thread(task);
runner.start();
The ThreadClass used here would be user defined. This class will implement the Runnable interface which is required for creating threads. In the ThreadClass the run() method (only method in Runnable) needs to be implemented as well.
It is clear that getting rid of ThreadClass would be more efficient and that's exactly why Anonymous Inner Classes exist.
Look at the following code
Thread runner = new Thread(new Runnable() {
public void run() {
//Thread does it's work here
}
});
runner.start();
This code replaces the reference made to task in the top most example. Rather than having a separate class, the Anonymous Inner Class inside the Thread() constructor returns an unnamed object that implements the Runnable interface and overrides the run() method. The method run() would include statements inside that do the work required by the thread.
Answering the question on whether Anonymous Inner Classes is one of the advantages of Java, I would have to say that I'm not quite sure as I am not familiar with many programming languages at the moment. But what I can say is it is definitely a quicker and easier method of coding.
References: Sams Teach Yourself Java in 21 Days Seventh Edition
The best way to optimize code. also, We can use for an overriding method of a class or interface.
import java.util.Scanner;
abstract class AnonymousInner {
abstract void sum();
}
class AnonymousInnerMain {
public static void main(String []k){
Scanner sn = new Scanner(System.in);
System.out.println("Enter two vlaues");
int a= Integer.parseInt(sn.nextLine());
int b= Integer.parseInt(sn.nextLine());
AnonymousInner ac = new AnonymousInner(){
void sum(){
int c= a+b;
System.out.println("Sum of two number is: "+c);
}
};
ac.sum();
}
}
One more advantage:
As you know that Java doesn't support multiple inheritance, so if you use "Thread" kinda class as anonymous class then the class still has one space left for any other class to extend.

what is the difference between "this" and "xxx.this" in android

example:
Why can I write like that MainActivity.this.getContentResolve();
but can not write like that this.getContentResolve(); in MainActivity.java
If you need to access instance of enclosing class from inner class you need to make declaration like this - ClassName.this.anyClassMethod();
For more info read this article Nested Classes
This syntax becomes relevant when using inner classes.
public class A {
String str = "A";
public class B {
String str = "B";
public String getStr() {
return A.this.str; //returns A
}
}
}
It's long described but i think your question is related to anonymous class.
When you are inside class and want to refer to the current object of the class you can use this for example:
public class MyActivity extends Activity{
int foo;
public Test(int _foo){
this.foo = _foo;
}
}
but when you want to refer to the current class object from anonymous class inside it you should use class.this for example:
MyActivity.this
Full example for Inner Class:
public class Test {
int foo = 1;
public class InnerTest {
public String getFoo() {
return Test.this.foo;
}
}
}
Why can I write like that MainActivity.this.getContentResolve() but
can not write like that this.getContentResolve()?
Because your trying to access the context of outer class (MainActivity) in the inner class. we use TheActivityClassName.this in the inner class to access the outer TheActivityClassName class’s context.
When we are accessing the activity context in inner class we need a reference to the activity class name so we pass it like MainActivity.this
and when we need it in the class then we can reference it simply like this.something
You should have a look here to get good grasp on what context is actually
Hope it helps
There is no difference if you are calling getContentResolver() from any direct method of the activity. You can write both MainActivity.this.getContentResolver(); and this.getContentResolver(); as well as simply getContentResolver() with the same effect. In this case, the this keyword refers to the current instance of the MainActivity.
However, if you are within an inner class or inside an implementation of an interface/abstract method inside the MainActivity, then this will refer to an instance of the inner class or the interface you are implementing. In that case, you have to call MainActivity.this to get access to the instance of the MainActivity.

How to pass data from one class to another, when Bundle can't be used?

I have two Classes. Class A is an Activity that has integer variables that need to be used in Class B (not an Activity). I have been able to use Bundles to transfer data of variables from one Activity to another Activity before. The problem is that this time, Class B is not an Activity and extends ImageView so that the draw() function can be used. Because of this, I am unable to use normal Activity functions, such as Bundle-Intents or SharedPreferences to transfer data in primitive variables from Class A to my Class B. I receive an error saying that "getIntent() is undefined for type".
So my question is, how can Class B use the variables in Class A if I am unable to bundle? Is there another way?
Someone said they did not understand my question so hopefully the below example will help demonstrate better.
public Class1 extends Activity {
//so Class1 has some primitive data, and is an Activity w/layout
int var1;
int var2;
Bitmap bitmap;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view);
}
}
A different class needs to draw onto canvas, but also needs to use the
information in var1 and var2 to be able to draw properly. But how to obtain that information?
public Class2 extends ImageView {
/*I am unable to use normal Activity functions, so I
*cannot onCreate, for example. I also cannot bundle,
*getIntent(), or use getSharedPreferences(). So how do I get var1
*and var2 value? */
}
Update: I was able to get this to work using getters. I attempted this before, but it was not returning the correct values. If anyone else ever gets stuck with this similar issue, remember to setup your variables with "static". I'm still learning all the differences, but without static my getter was not working. Once I added static to my variables, everything worked out. So that's one observational tip (even without fully understanding the logic as to why). Thank you to all the responders for your tips.
You can do this in different way.
First of all you can use static variable to do this. Such that you can declare a variable in class A public static String variable; and from class B you can get the value of this variable like this way ClassA.variable.
Another way you can use by passing a context of class A to B and then use SharedPreference.
Or create a new class which extends android Application. From class A you can set different variable value in application class. Now you can retreive those values from Application class. Hope this can help you.
Some code Sample using static variable
public Class1 extends Activity {
public static int var1 =20;
public static int var2 = 30;
}
Now get the variable value from class two
public Class2 extends ImageView {
Class1.var1;
Class.var2;
}
Second way using getter.
public Class1 extends Activity{
int var1 =10;
int var2 =20;
public int getVar1() {
return var1;
}
public int getVar2() {
return var2;
}
}
Now you can get the variable value in Class2
public Class2 extends ImageView {
Class1 class1= new Class1();
class1.getVar1;
class1.getVar2;
}
Also you can use SharedPreference. Hope it can help you. Thanks.
Various options exist:
The Activity can pass the information to Class B:
class B {
public void tellMeInformat(int usefulNumber) {
// Do something
}
}
Or, you can pass the Activity to the ImageView:
class A {
initiation {
B mySpecialImageView = /* Set it upo */;
B.setParentActivity(this);
}
}
class B {
private myA = null;
public void setParentActiviy {
myA = A;
}
private void doSomething {
int usefulNumber = A.getUsefulNumbner();
// Do something
}
}

How do I delegate a string without redefining it , in another class?

I am pretty new to android and trying to figure out delegation. To explain the same.
I have a search box for which I am defining a search text string as follows in class FragmentA:
protected EditText mSearchView;
Now, I have another class FragmentB extends Fragment A, which is using the same in a method as follows:
private void displayQuotes(final String searchAutoSuggestTitle, final String searchAutoSuggestSubTitle, final String searchAutoSuggestSymbol) {
killLastSearchAutoSuggestTask();
String text = mSearchView.getText().toString().toLowerCase() + " " + mSearchView.getText().toString().toLowerCase();
if(searchAutoSuggestSymbol.toLowerCase().contains(mSearchView.getText().toString().toLowerCase())){
QuotesFragmentWebView.newInstanceForSearch(getFragmentManager(), searchAutoSuggestSymbol, null);
}
else if(!searchAutoSuggestSymbol.toLowerCase().contains(text)){//mSearchView.getText().toString()))&&""&&(searchAutoSuggestSymbol.contains(mSearchView.getText().toString()))){
AnswersWebViewFragment.newInstanceForSearch(getFragmentManager(), searchAutoSuggestSymbol, null);
} else {
}
hideSearchView();
}
Now, the values are retrieved for mSearchView text for the text typed in. Now I have another class Fragment C which extends Fragment implements Onclicklistener,mainactivity, and no specific classes. I have a URL in there which I am defining as :
public final static String search_1_result = "https://mobile13.cp.com/fwd/results/answers/service/v1/?q="+mSearchView.getText().toString()+"%20revenue&ui.theme=novadark&uuid=PADACT-002";
But, I wonder how do I make it recognize the mSearchView.getText().toString() value(including recognizing mSearchView which it is throwing as an error,since its not defined in that specific class) . Also how do I carry on the typed value in Fragment B for the search, to be used in the url given above?
Thanks!
brian
Refer to this thread :
How do I use the parameter defined in another class?
I had a similar issue ,
You just need to define a function say
-public fragment(or your class can be your view class) extends whatever{
-public void thisfunction(){
//code to add
}
}
call that in the class you require and define the functionality in the main class from which you wish to delegate and call it inside the function referring to the fragment class.(exactly the same as in the class reference I gave you),don't forget to get the required listeners with implements functionality, in the example onrawerclosedlistener.

What is the data type of 'MyActivity.this' - Android

well my question is that there aren't pointers in JAVA ...
but when we have to start another activity we do like this :
Intent in = new Intent(MyActivity.this, NewActivity.class);
startAcitivity(in);
So my question is that what is the data type of MyActivity.this ??
In java pointers are not explicitly allowed,
However passing by reference(object) in Java is something which is implicitly based on pointer concept.
In your case, you are passing the context of parent class to child class,
which is actually passing by reference concept.
Hope this helps.
Writing MyActivity.this is the same as writing this, if you are in a non-nested class, or to top-level class.
See this example:
public class TopLevel{
public static void main(String[] args){
new TopLevel().printClass();
}
public TopLevel(){
new LowerLevel().printClass();
}
public void printClass(){
System.out.println("Outer Class: ");
// Will print something like "TopLevel.class"
System.out.println(this.getClass());
}
public class LowerLevel{
// This is a Nested-Class.
public void printClass(){
System.out.println("Nested Class: ");
// Will print "TopLevel$LowerLevel.class"
System.out.println(this.getClass());
// Will print "TopLevel.class" again
System.out.println(TopLevel.this.getClass());
}
}
}
Some using this in the nested-class does not reference to the same instance as when using it in the top-level class. Therefor, to get the "context" of the outer class in your nested class, you also specify the class you want the this-context from.

Categories

Resources