the role of "this" in TextView textView = new TextView(this); - java

I am new to Android programming. I want to know that in this code what does the this in
TextView textView = new TextView(this);
this would point to which class or method? I copied this code from here.

The reason you need this when creating a TextView is because one of the the constructors of TextView (the one that you're calling) takes a Context object as a parameter.
That basically means you must give TextView a Context in order to create it.
Where do you get this context from? Well, an activity is a kind of context (Activity is a subclass of Context)! And you're creating the TextView in an activity class right? So just use this activity as the context!
Got it? Use this activity as the context for the TextView! That's why you put this in there. this refers to the object that the code is currently running on.
Since this refers to an object created from the class, you can't use this in a static method because a the code in a static method does not run on any object.
Another use of this is in constructors:
class MyClass {
private int a, b;
public MyClass(int a, int b) {
this.a = a;
this.b = b;
}
}
Since the compiler can't know which a or b you mean, you must add this to refer the a that's in the class.

this refers to the current object's instance that was invoked or initialized.
See: What does "this" mean?

Related

How to run a class multiple times?

I want to run a class multiple times, lets say I have a class
public class setTextClass {
public void setTextClass (String text){
this.text = text;
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
textview.setText(text);
}
public void run{
textview.setText(text);
}
}
So, As I see, if I initiate the class doing:
setTextClass hi = new setTextClass("hello");
The code on the onCreate will run right? (this is my first question)
And then, if I run the code:
hi.run()
The code over the run method will be executed and also will pass the text variable that was assigned at the initialization?. This is my second question. I'm learning java, sorry if this is a really basic question
First of all, it's difficult to address question with basic java and Android misconceptions in a Stack Overflow answer. SO is not made for these kind of question, that's why you are getting downvotes. So, that said, I'll try to help you a little bit:
First answer: "The code on the onCreate will run right? (this is my first question)"
No. You are probably mixing up because of onCreate method from Android's Activity class, right? But a constructor is something general for all classes in java, while onCreate is a method specific to some Android complex classes, like Activity or Fragment. It is a method related to the lifecycle of these classes and you should read more about it here.
So, in this simple class that you showed, onCreate will not be called in the constructor (unless you explicitly call it in the constructor). You should assign the text to textView inside your constructor.
Second question: "The code over the run method will be executed and also will pass the text variable that was assigned at the initialization?"
Yes, it will run and use the variable assigned to this.text on the constructor. BUT, you are missing the declaration of this global variable for it to work:
public class setTextClass {
private TextView textView;
private String text; // You have to declare your global variables here
public void setTextClass (TextView textView, String text){ // You should pass your TextView in the constructor and assign it to your global variable, so it's not null when you assign text to it;
this.textView = textView;
this.text = text;
textview.setText(text); // Moved from your onCreate method to the constructor
}
public void run{
textview.setText(text);
}
}
I hope I could make myself clear, but you should study more java and do some basic tutorials to better understand the language and it's concepts, so you can ask more specific questions here. Read here about classes, objects, constructors and more
Your onCreate function will not run when you do the initialization:
setTextClass hi = new setTextClass("hello");
instead what will run as its constructor(which should not have a return type because its return type is the object itself) ie:
public setTextClass (String text){
this.text = text;
}
And as for the second question the text variable, that variable only exist in the scope of the constructor or setTextClass method. So if you wanted to do something like that you would need to create and set a class variable.
It seems like you need to do a lot more learning and go through examples of OOP design and scope. I would check out these resources if i were you:
http://www.learnjavaonline.org/en/Objects
http://www.learnjavaonline.org/en/Functions

NullPointerException in super class method's constructor when testing using mockito

I have a super class:
public class A extends Fragment{
public A(Context context){
super(context);
}
}
and class B inherits it:
public class B extends A{
public B(Context context){
super(context);
}
}
In my test class where I'm using Robolectric and Mockito, when I instantiate class B like so: B b = new B(context)
I get a nullpointerexception in class A's constructor's super method. Am I doing something wrong?
Here's the test code:
#Mock Context context;
#Before
public void setup() {
initMocks(this);
B b = new B(context);
}
Simple answer: it isn't that easy.
The exception stack trace which you are hiding from us would tell you/us that those NPE happens within some base Android code. Thing is: you are passing a context object into the Fragment constructor.
Guess what: the Fragment code then starts using that context object. It makes a whole series of calls on that object, in order to retrieve other objects, to then make calls on those objects.
Right now, you only mocked a Context object. Any calls to it that are supposed to return a value will return null by default. Mockito doesn't know anything about the classes you are mocking. So, when you want that a certain call returns something else than null, you have to specify that behavior.
So, the "short" answer is: you have to prepare that mock object to be able to be used like this. The long answer ... was already given; and you need to study its details in depth!
Beyond that; you can have a look into another question dealing with the exact same problem.

what is 'this' doing out here relativelayout lyt=new relativelayout(this) [duplicate]

This question already has answers here:
What is the meaning of "this" in Java?
(22 answers)
Closed 5 years ago.
Relativelayout lyt = new Relativelayout(this)
what is 'this' doing out here.
is that the 'this' keyword in java,if yes what's happening behind the scenes.
i just want how are we using 'this' keyword here
As you can see on the documentation, 'this' is the context. I guess this code line is on a class which extends activity, so 'this' represent the activity in which you want to insert the new layout.
You will need the Context class is when creating a view dynamically in an activity.
For example, you may want to dynamically create a ** RelativeLayout** from code. To do so, you instantiate the ** RelativeLayout** class. The constructor for the RelativeLayout class takes a Context object, and because the Activity class is a subclass of Context, you can use the this keyword to represent the Context object.
In Java, this means current object i.e. object you are currently working with.
When you say Relativelayout lyt=new Relativelayout(this) basically you are passing your current object while creating an object of Relativelayout (of course as long as Relativelayout has a contructor which accepts whatever is the type of this).
As an aside, you cannot use this in static context.
See below sample code with comments for explanation so it will be very easy for your to understand.
public class Class1 {
public static void main(String[] args) {
new Class1().test(); // see here I couldn't do "Class2 class2 = new Class2(this);" because "this" cannot be used in "static" context, so I had to create an object of Class1
}
private void test() {
Class2 class2 = new Class2(this); // here this means current object of "Class1"
}
}
public class Class2 {
private Class1 class1;
Class2(Class1 _class1){
this.class1 = _class1; // here "this" means the object of Class2.
}
}
And finally for your question about keyword, yes "this" is a keyword in Java, refer JLS specs for complete list (ยง3.9)

Can I move objects between activities without intents in Android?

The point is that from Activity A to B I need to create Activity B every time, but I don't close Activity A because when I return to Activity A from B, I simply finish Activity B but I don't create Activity A because I didn't finished it. That is what I want.
The problem is when I try to pass data and objects from Activity B to A. I can't use intents and putExtra() because I don't start Activity A, I simply resume it with onResume().
SharedPreferences don't let me to pass objects so does anyone knows if there's any method to pass objects from B to A?
SOLUTION: http://www.javatpoint.com/android-startactivityforresult-example
Thanks to #brightstar #ThMBc #Avtar Guleira #Edy Bolos that's was I looking for :)
You can start activity B using startActivityForResult, and then return from it to A your data inside intent. You can find example on it here:
http://developer.android.com/reference/android/app/Activity.html
There are different methods for different cases. If the object created in B is going to be used application wide, you might consider giving it to the appliction, so that every activity can reach it by
.getAppliction().getMyField()
Note that using a static field in a general class almost comes down to the same thing, but this follows the rules of encapsulation.
If B is launched purely for the creation of the resulting object then starting an activity for result is the way to go, as brightstar said:
.startActivityForResult()
as documented in the android dev docs
Technically you can also pass objects through sharedPrefs if you serialize them (e.g. converting them to a json object and passing a string in prefs), but that is not really the way one would do this.
Yes you can do it.
For Example:
Create a standalone java class
Class C {
public static ArrayList<YourObject> myList;
}
Import the C class header
enter code here
Class B {
myList.add()
}
import C class header
Class A{
myList.get(index)
}
Use an Singleton-Class to store and retrieve objects.
public class Model {
private static Model model = null;
private Object myObject;
private Model() {}
public static Model getInstance() {
if (model == null) {
model = new Model();
}
return model;
}
public Object getMyObject(){
return myObject;
}
public setMyObject(Object myObject){
this.myObject = myObject;
}
}
When you are in Activity A you store the objects you need in the model and retrieve them afterwards in activity B
You can create another Class and create static properties which will hold your objects for you. Please look.
Class Utils {
public static MyObject object;
public static int index;
}
Use it like
Utils.object = new MyObject();
Utils.index = 4;
You cann't transfer object as per you scenario because you are not calling Activity A directly(means startactivity).You can achieve this scenario in another way. You have to set/save data in Application class from Activity B and then you can get data from application class in activiy A onResume() method and do whatever you want.
Follow below steps:
Just start Activity B using startActivityForResult method instead of
startActivity
Then override onActivityResult in your Activity A.
When you want to finish or onBackPressed Activity B. just pass data using intent
in setResult Method
For complete documentation you can view this link:
Getting a Result from an Activity
So, when ever Activity B will finished OnActivityResult will be called of Activity A. In this method you will get Intent that you have set from Activity B. You can whatever you wan to do man then.
Please just don't use static fields!!! It really bad practice, and you can encounter concurrency issues.
You can easily accomplish your request by starting activity B with startActivityForResult, and then in activity B you can catch the result by overriding onActivityResult method, like described here: http://developer.android.com/reference/android/app/Activity.html#StartingActivities

How can I pass a reference to the current activity

I am trying to pass a reference of the current activity to an object but can't seem to find a method that will do this easily. Previously I was able to do this simple passing with the "this" reference of the current context. I then changed my activity from implementing OnClickListener to creating an OnClickListener object so that I could pass it as a parameter. This is when I ran into trouble as I was trying to create the object after I clicked on a button, this means I can no longer pass the activity with "this" because "this" is now a reference of the OnClickListener.
public class MyActivity extends Activity {
private Object mObject;
private OnClickListener mListener = new OnClickListener() {
public void onClick(View v) {
Object mObject = new Object(this);
}
}
}
public class Object {
private Activity mActivity;
public Object(Activity a) {
mActivity = a;
mActivity.setContentView(R.layout.layout);
}
}
Seems like an easy fix but I can't find the answer...
Any help is greatly appreciated.
You are right, this now references the OnClickListener, as it references the current class, and you are working inside an anonymous class. You can reference the outer activity by passing mActivity.this:
Object mObject = new Object(mActivity.this);
Btw: I think I'd rename the mActivity class, as normal class naming convention is for it to start with an uppercase letter.
Add mActivity. to this
Object mObject = new Object(mActivity.this);
In your context, this refers to a listener instance, but you need the outer class's instance there, so you need to add class name to this

Categories