Red line error with correct code - java

image
Well i have this problem when the code is correct, but it gives me red line error!
can anybody help me.
Main.java
package com.example.sout;
import android.content.DialogInterface;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import
~
import android.widget.ImageView;
public class Main extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
ImageView iv = (ImageView) findViewById(R.id.img1);
iv.setBackgroundResource (R.anim.animation);
~~~~~~~~~~~~~~~~
iv.setOnClickListener(new OnClickListener());
~~~~~~~~~~~~~~~ ~
}
in (note the ~ characters above):
iv.setBackgroundResource (R.anim.animation);
iv.setOnClickListener(new OnClickListener());
The setBackgroundResource and setOnClickListener are red too.

The error in iv.setBackgroundResource (R.anim.animation); comes because that method takes integer as a parameter .So change it to the following,
iv.setBackgroundResource (R.drawable.image1); //image1 is a drawable which is inside your drawable folder.
and the second error comes because you have not imported the required package and have not overridden the methods required for that. Change it to the following,
iv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//do your task here
}
});
after changing press ctrl+shift+p to import the required packages.

Sometimes, at least with Eclipse, it gets it into it head that there's an error and it won't let it go. But, with Eclipse, you can at least put the cursor over a marker and it will explain what the problem is (or what it thinks it is). I'd try to hover over the errant lines to see if a popup box appears telling you what it thinks.
If you're sure it's wrong, often I've found that saving the file (or all files) will fix it. Sometimes adding then deleting a space on the errant line will fix it.
However, I notice that you have an incomplete import at the top of your file and this may be preventing the syntax checker from properly analysing the source file.
My advice is to fix that first, then try those other two tricks (save then, if that doesn't work, edit and undo on the errant line). Hopefully that will make it disappear.
Of course, you may want to check, just in case, your R.java file to ensure that member exists in there somewhere. I've been bitten by my own misspellings before.

Related

How to get the context inside a mouse click listener

In Android Studio, developing in Java, I have the following (a somewhat minimized version of what I'm trying to do).
package com.example.japanesequiz;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
String[] hiragana = {"あ", "か"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button generate = findViewById(R.id.generate);
TextView questionText = findViewById(R.id.question_text);
RadioGroup radioGroup = new RadioGroup(this);
MainActivity ma_inst = this;
generate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Random rand = new Random();
int hir_index = rand.nextInt(2);
questionText.setText(hiragana[hir_index]);
RadioButton rb1 = new RadioButton(ma_inst);
rb1.setId(View.generateViewId());
rb1.setText("Ah");
radioGroup.addView(rb1);
RadioButton rb2 = new RadioButton(ma_inst);
rb2.setId(View.generateViewId());
rb2.setText("Ka");
radioGroup.addView(rb2);
}
});
}
}
The basic idea is that I want to have the main screen initially mostly blank, but with a button at the bottom. When tapped, it eventually show some text and a radio button group. (I haven't yet fully built out the rest, of course.)
But at this stage what I expect when I launch the app is to see the mostly blank screen, and maybe if I tap the button it will generate some text and options (that then do nothing, further implementation to come).
But the app never launches. Instead, Graddle finishes building, I get a terminal saying that it's launching the app, but it hangs and times out.
If I had to guess -- and this is a guess because I'm very new to Android development -- there is some issue with grabbing the this instance and then using it in the OnClickListener. I'm not certain what the issue is, but it's the only thing I see here that looks fishy. Also, I'm not sure how else one is supposed to add objects to the current activity from inside of the anonymous class passed into the OnClickListener since, there, a reference to this then refers to the anonymous inner class.
I know that it is possible to use a lambda instead, and that probably resolves the issue, but I want to really understand what's going on here, since it seems like it might be conceptually important for later development.
My question: If I have correctly understood this much, then how does a lambda get around this issue? If I've not correctly understood then I'd appreciate any insight, thanks!
There are many questions in one question. First, let me try to answer your title question: "How to get context inside a mouse click listener":
There are many ways, but you can consider this one (your click lisener's onClick has the signature void onClick(View view), hence you have access to view.
view.getContext()
Next, nothing wrong with these though you better migrate to view binding https://developer.android.com/topic/libraries/view-binding as butterknife is deprecated officially
Button generate = findViewById(R.id.generate);
TextView questionText = findViewById(R.id.question_text);
Next, you don't really need this trick in order to get activity in your lambda:
MainActivity ma_inst = this;
Instead and if really needed, you can always do Context context = MainActivity.this;
Lastly, I think the issue the app never launches roots into something else not related with title question you posted, unfortunately.

android app test error

When I run my first app, I got error.
Code of the activity:
package com.pradeep.ulc;
import android.app.Activity;
import android.os.Bundle;
public class New1Activity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
Error:
R cannot be resolved to a variable New1Activity.java /new1/src/com/pradeep/ulc line 11 Java Problem
How can I fix it?
1) Make sure the package name is correctly set everywhere
2) Try doing a clean build to regenerate R.java.
If you must use a different package, import the R.java from the package specified in the manifest.
It means that you have problem in your resources, so R file cannot be generated.
What do you have in res/layout/main.xml file?

Clean deleted R. Cant run any of my codeI

I did clean project and now i cannot run any of my code. Any files that has to do with R, just says cannot be resolved as a field. I've looked at so many other stackoverflow posts with similar problems but none seems to actually help. Help please!!
I have about 15 classes but here is an example
package com.Class;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
public class NewAccount extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(this);
}
}
If R.java is not being generated, chances are there are some other errors in your code than the ones referring to the R file. Find these errors, solve them, and then R will be regenerated.
Did you import the R file?
import com.example.myapp.R;
This may be useful too: R cannot be resolved - Android error

android "main cannot be resolved or is not a field"

i m new to this platform, please help me to find what is the error...
setContentView(R.layout.main); // this line shows the error.
Code:
package com.example.helloandroid;
import android.R;
import android.app.Activity;
import android.os.Bundle;
public class HelloAndroidActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
Try deleting the line import android.R then clean your project.
Just adding more details on why the error is coming.
As there is an import of android.R so setContentView() is looking for a layout file 'android.R.layout.main' and there is no main.xml in the layout files that come along with SDK. So, using the correct R.java import will work.
clean Project then try To Run because i faced same problem before a month and remember layout/main.xml must be their and it must not contains any error.
you can Also Do this
import android.R;
or
import your.application.packagename.R; Now Clear Project and Run it.
You must have to simply change the
setContentView(R.layout.main);
... to:
setContentView(R.layout.activity_main);
... because Layout contains this .xml file.
I hope your problem will be solved.
First remove import android.R;
After any change on xml fiels you must clean project.
Build > Clean Project
after that every things corrects.

setContentView(R.layout.main); error

package com.elfapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
private Button btn_Login;
private EditText et_UserName;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn_Login = (Button) findViewById(R.id.button_login);
btn_Login.setOnClickListener(this);
et_UserName = (EditText) findViewById(R.id.editText_userName);
}
public void onClick(View v) {
if (v.equals(btn_Login)) {
// skriver ut en toast när man klickar på knappen
Toast.makeText(MainActivity.this, "Ansluter till server...", Toast.LENGTH_SHORT).show();
// används i debuggern för att påvisa att programmet exekverat hit
Log.v("ThisApp", "onClick Successful");
// TODO skickar det som står i et_UserName till controller (genom TCP/IP), som ska kolla om användaren finns
// send et_UserName.getText().toString() to controller
// if(username exists)
Intent intent = new Intent(this, RoomActivity.class);
this.startActivity(intent);
}
}
}
I'm getting an error on the line containing setContentView(R.layout.main);
Not sure about what the error/exception is because I'm not used to working in Eclipse..
This just happend to me a minute ago, but after researching a while, and read this post I notice this.
There is a custom R class with you app name, so when you try to import the missing class (in Eclipse, press Ctrl + Shift + O to import missing classes (Cmd + Shift + O on Mac)), you should see two posible classes the normal:
import android.R;
And a custom class with your project namespace:
import com.yourname.yourapp.R;
If you choose the custom class, problem solved!
Just take 2 steps and problem would be more likely to get solved:
Step 1:
Clean your project by clicking Project -> Clean.
Step 2:
Rebuild your project by clicking Project -> Build All.
Also make sure that your layout xml files are syntax error free and you don't have any image which has non-acceptable names (such as a "-" between image name).
Also I request you to have a look at problems window and let me know what errors are being shown there.
Using NetBeans 7.0:
If you fix imports before R.java has been generated for your project (before building it the first time) it will add the line:
import android.R;
which will override the local R.java that you are trying to reference.
Deleting that line resolved the errors for me.
Step 1 :
import android.*;
Step 2 :
clean your project
Step 3 :
Enjoy !!!
if you have multiple packages with different classes then it will be confusing: try this:
import package_name_from_AndroidManifest.R;
is this already solved?
i also had this problem. I solved it just by cleaning the project.
Project>Clean>Clean projects selected below>Check [your project's name]
This problem usually happen if eclipse accidentally compile the main.xml incorrectly.
The easiest solution is to delete R.java inside gen directory.
Once we delete, than eclipse will generate the new R.java base on the latest main.xml
Simply:
Right click on your project.
Go to properties.
Select android (second option in the Left panel).
Click "add..." (in library), select your project.
Click ok.
And finally, clean your project.
If this doesn't work, make sure that "android-support-v7-appcompat" is in your Project Explorer.
If it isn't there, you can add it by importing a simple project from: C:/android-sdks\extras\android\support\v7\appcompat
use code : setContentView(R.layout.activity_main); instead ofsetContentView(R.layout.main);

Categories