Android Studio Unknown Class - java

When I declare double variables, and later try to assign values to them, it says unknown class . Secondly, any method calls from objects I have created say cannot resolve symbol .
My code:
private double xCurrentPos, yCurrentPos;
private ImageView test = (ImageView) findViewById(R.id.square);
xCurrentPos = test.getLeft();
yCurrentPos = test.getTop();
This code says that xCurrentPos and yCurrentPos are both unknown classes and that it cannot resolve getLeft or getTop.
Any help would be greatly appreciated. :)

You can't do assignments of variables like that in the context of the class.
From what I can tell you're doing something like this which gives you the errors you described.
public class YourActivity extends Activity {
private double xCurrentPos, yCurrentPos;
private ImageView test = (ImageView) findViewById(R.id.square);
xCurrentPos = test.getLeft();
yCurrentPos = test.getTop();
...
}
You would have to do the assignment as they are being declared like this:
private int xCurrentPos= test.getLeft();
private int yCurrentPos = test.getTop();
Or you do the assignments within an actual method.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
xCurrentPos = test.getLeft();
yCurrentPos = test.getTop();
}
Second, doing this:
private ImageView test = (ImageView) findViewById(R.id.square);
will not work anyway as this will get initialized before onCreate so test will be null.
Even doing this in onCreate after you set the content view will give you values of 0 for both getLeft and getTop as the your views have not been drawn yet. For that you can refer to this. You basically need to do it in an event where you views have already been drawn.

The View class's getLeft() and getTop methods return an int, not a double. You don't need to use double type.

Related

findViewById not accepting type argument even with compileSdkVersion 30

I generally use kotlin for android but my college wants me to use Java. So I created a new java project in android studio.
The problem is I don't want to cast the return value of findViewById() manually. Instead I want to pass EditText as type parameter which the function is not accepting as anticipated. I get the error :
/home/onkar/AndroidStudioProjects/MyApplication2/app/src/main/java/io/github/omkar76/myapplication/MainActivity.java:16: error: cannot find symbol
Log.d("EDITTEXT", findViewById<EditText>(R.id.first_name).getText());
^
symbol: variable findViewById
location: class MainActivity
Why isn't this working? Why is method not found? I even checked source of AppCompatActivity and it does contain required method:
#Override
public <T extends View> T findViewById(#IdRes int id) {
return getDelegate().findViewById(id);
}
My Java code is :
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("EDITTEXT", findViewById<EditText>(R.id.first_name).getText());
}
}
If I don't pass type argument EditText, findViewById returns View which then I need to manually cast. According to this post starting with api 26 you don't need to cast the returned value. I have API 30 SDK. So why this is not working. I am aware of workarounds like assigning return value to an EditText reference but my interest is in knowing why existig approach doesn't work.
Let me know if any other details are required. Please point out what I am doing wrong. Thanks!
I think you're confused with the syntax of java.
Here public <T extends View> T findViewById(#ResId int id) means :
return value cast to T, T is resolved with the left side of the assignment declaration before the equals sign. In the following example
Edittext x = view.findViewById(R.id.abc)
So here T get assigned as Edittext as Edittext is on the left side of the assignment declaration which then returns edittext as a view. Then you can call x to getstring.
Hope this makes it clearer
Actually, Java has no such syntax as Kotlin for findViewById.
The Kotlin syntax:
findViewById<EditText>(R.id.first_name)
The equivalent in Java:
(EditText)findViewById(R.id.first_name);
So, you can do like this in java:
Log.d("EDITTEXT", ((EditText)findViewById(R.id.first_name)).getText().toString());
Note: You have to put toString() to convert from Editable to String explicitly in Java
The simplest way use a variable name
EditText editext = findViewById(R.id.first_name);
then you could use
Log.d("EDITTEXT", editext.getText().toString());

How can I use findviewbyid in static class?

I have a static class:
public static void culculateFprice(){
TextView FinalBuy = (TextView) findViewById(R.id.buyText);
int Pprice = MainActivity.pepperoni.getFinalPrice();
int Cprice = MainActivity.calzone.getFinalPrice();
int QCprice = MainActivity.quattrostagioni.getFinalPrice();
int QFprice = MainActivity.quattroformaggi.getFinalPrice();
int Mprice = MainActivity.mexican.getFinalPrice();
int FinalPrice = Pprice + Cprice + QCprice + QFprice + Mprice;
FinalBuy.setText("Стоимось вашего заказа: " + FinalPrice + " руб.");
}
How can I use find findViewById in this class?
I call this method from this method
public static void onPlus(int i){
ArrayList<String> list = listok();
switch (list.get(i)){
...
}
adapteR.refreshData(listokadd());
culculateFprice();
}
And have problem "Non-static method "findViewById(int)" cannot be referenced from a static context"
I assume this function exists in your Activity class and you would like to process some information based on the View. There are two ways you can solve this:
Remove the static modifier and let the instance take care of this.
Create a field that holds a View reference that gets created as soon as your layout is set.
So your Activity will hold the field:
class MyActivity extends Activity {
static View FinalBuy; // needs to be static, otherwise would give same error
}
#Override
void onCreate(Bundle savedInstance) {
// after setLayout
FinalBuy = (TextView) findViewById(R.id.buyText);
}
But to save your code from a potential runtime error, use an if...else block in your static method:
public static void culculateFprice(){
if(FinalBuy != null) {
// your code here.
}
}
This problem is basic Java and not Android. That is how Java language is designed to provide instance vs. static methods for the programs.
This static View declaration leads to a potential design flaw because this View will outlive the Activity. Instead of this, you should consider using the approach I suggested in the list as option 1 and see why you are unable to use an instance method in your program. You should read more on this thread.
This will likely need you to change your other fields of MainActivity to be declared as non-static as well!

Error when accessing variable from another class

I am trying to use a variable from another class. however, it shows an error at the following code:
public class ItemDetailActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState, String[] args) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_detail);
Toolbar toolbar = (Toolbar) findViewById(R.id.detail_toolbar);
setSupportActionBar(toolbar);
DummyContent Position = new DummyContent();
int picCheck = Position.getPos();
}
}
Here is the getter:
public int getPos(int position) {
return position;
}
Can you show me what my problem here is?
The error:
Error:(31, 32) error: method getPos in class DummyContent cannot be applied to given types;
required: int
found: no arguments
reason: actual and formal argument lists differ in length
Here:
int picCheck = Position.getPos();
Intending to use:
public int getPos(int position)
Notice that one line wants an int parameter; and that the other line doesn't give one.
And the real answer here is: the compiler message already tells you so. Required int, found: no arguments.
Meaning: java compiler messages are easy to read most of the time.
Thus the answer beyond the simple left-over here: if your Java skills are on a level that makes it hard to understand such messages, you are most likely overburdening yourself at this point by trying to do Android programming.

Meaning of R.layout.activity_main in android development (JAVA language)

What is the meaning of R.layout.activity_main ?
I understand that "." operator is used to define variables of a particular object but in this case its been used twice so I can't make anything out of it. Also what exactly is "R" and "layout"?
I mean obviously they are classes (right?) but what is their function ? Basically explain R.layout.activity_main !
Please comment if question too vague or too broad.
R.java is a class (with inner classes, like layout or string) generated during the build process with references to your app's resources. Every resource you create (or which is provided by Android) is referenced by an integer in R, called a resource id.
R.layout.* references any layout resource you have created, usually in /res/layout. So if you created an activity layout called activity_main.xml, you can then use the reference in R.layout.activity_main to access it. Many built-in functionality readily accepts such a resource id, for example setContentView(int layoutResid) which you use during the creation of your activity and where you probably encountered this particular example.
If you create a string resource (in strings.xml) like this:
<string name="app_name">Application name</string>
it will get a new reference in R.string.app_name. You can then use this everywhere where a string resource is accepted, for example the android:label for your application in AndroidManifest.xml, or on a TextView; either in the xml:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/app_name"
/>
or in code: textview.setText(R.string.app_name).
You can access resources programmatically using the Resources class, to which you can get a reference by calling getResources on any context (like your activity). So for example you can get your app name described above in your activity by calling this.getResources().getString(R.string.app_name).
You can also supply different resources for different device properties/settings (like screen size or language), which you can access using the same references in R. The easiest example here, imho, is strings: if you add a new values folder in /res with a language specifier (so /res/values-nl for Dutch) and you add strings with the same identifier but a different translation and the resource management system cleverly figures out which one to provide for you based on your user's device.
I hope this helps a bit. For more information on resources see the documentation.
R is an auto-generated class, and describe the resources of your project. It contains static inner classes. layout is one of them. R.layout refers to the inner class called layout. activity_main is a public static final member of the class layout
In Android R is an Java-class that is auto-generated from your resources by the build process.
The R.layout member is a auto-generated class that contains all IDs for layouts.
R.layout.activity_main is a static final int member that represents the ID of the layout-file in layout/activity_main.xml.
Okay, so R is a generated class. If you're lucky enough you'll never see it nor have to touch it, otherwise you did something very wrong.
When you make a layout, or any change to a layout, Android Studio generates quite a couple files for you. This includes a R.java file. Here's a piece of an R.java class:
public final class R {
public static final class anim {
public static final int abc_fade_in = 0x7f050000;
public static final int abc_fade_out = 0x7f050001;
public static final int abc_grow_fade_in_from_bottom = 0x7f050002;
public static final int abc_popup_enter = 0x7f050003;
public static final int abc_popup_exit = 0x7f050004;
public static final int abc_shrink_fade_out_from_bottom = 0x7f050005;
public static final int abc_slide_in_bottom = 0x7f050006;
public static final int abc_slide_in_top = 0x7f050007;
public static final int abc_slide_out_bottom = 0x7f050008;
public static final int abc_slide_out_top = 0x7f050009;
}
public static final class attr {
public static final int actionBarDivider = 0x7f010062;
public static final int actionBarItemBackground = 0x7f010063;
public static final int actionBarPopupTheme = 0x7f01005c;
public static final int actionBarSize = 0x7f010061;
public static final int actionBarSplitStyle = 0x7f01005e;
public static final int actionBarStyle = 0x7f01005d;
public static final int actionBarTabBarStyle = 0x7f010058;
public static final int actionBarTabStyle = 0x7f010057;
public static final int actionBarTabTextStyle = 0x7f010059;
As you can see, in this case if I'd type
R.anim.abc_fade_in
I'd be selecting the value 0x7f050000;.
Every layout file is mapped out in this R file, and gets an ID by which android recognizes it. The layouts are located in R.Layout. So, R.layout.activity_main gets you the value of variable activity_main of the class layout of the class R.
And again, don't try finding or changing your generated R file. Things can go very wrong if you do that.
From https://stackoverflow.com/a/4953282/1393766
R is a class containing the definitions for all resources of a particular application package. It is in the namespace of the application package.
If you want to inflate a layout inside your activity class,you can use R.layout.activity_main where layout specifies that your resource is a layout and it's name is activity_main.
If you want to use a drawable image in a layout inside your activity class,you can use R.drawable.image_name where drawable specifies that your resource is a drawable image.
Also,R.java class is an autogenerated class which is not supposed to alter manually.

Problem accessing variable[] from another class

I know this a pretty basic question, and already found another ones like mine, but I honestly don't know what I'm doing wrong.
public class InteractiveArrayAdapter extends ArrayAdapter<Model> {
private final List<Model> list;
private final Activity context;
public int teste;
public InteractiveArrayAdapter(Activity context, List<Model> list) {
super(context, R.layout.rowbuttonlayout, list);
this.context = context;
this.list = list;
}
public int getTest()
{
return teste;
}
static class ViewHolder {
protected TextView text;
protected CheckBox checkbox;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
teste = 2;
....
}
}
and other class:
try{
InteractiveArrayAdapter adapt = new InteractiveArrayAdapter(this,
getAPPS(0));
int test = adapt.getTest();
Toast.makeText(this, Integer.toString(test), Toast.LENGTH_LONG).show();
Log.v("TAG",Integer.toString(test));
}catch(Exception e)
{
Log.v("EXCEPTION",e.toString());
}
EDIT: I was getting null for a stupid mistake, and now I'm getting the primitive and expected 0 as most of you say.
At some point of my app, everytime a checkboxes is clicked that method getView is executed. I want to store that to an array[] of strings progressively (i+1) (i just put int to be easier to understand - realize now it was a mistake), and then when users inputs ok I want to access the whole array. Wondering if it's possible the way I want.
So when I do this
InteractiveArrayAdapter adapt = new InteractiveArrayAdapter(this,
getAPPS(0));
This is meaningless, because I don't need to execute anything again, I just want to retrieve the created array - if possible!
Your code won't even compile. return this.teste; should be return this.test;.
Well, this isn't a direct copy/paste, since this obviously wouldn't compile. Whenever you're dealing with an actual error or issue, it's really best to paste the actual code. We're all programmers, so we can read it.
But based on the structure you've shown above, either the typo you've put in the line return this.teste (should be return this.test) is in your code, or you didn't initialize the instance variable test in your constructor.
Without showing us the actual code you're writing, it's impossible to say (especially the section that initializes the test variable, and the part that returns its value are missing - we're not mind readers, I'm afraid).
So, those are two potential candidates. On another note, however, if you mark the test variable as public, then you don't need to have getter/setter methods for them, since any class can access them without going through a method call. That's what public does.
But that is what should happen according to your code. You don't call B method to update teste variable.

Categories

Resources