Android method rewrite to Lambda - android

I've want to rewrite the method to Lamda.
CheckCar.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
CheckMotor.setChecked(false);
et_mileage.setText(String.valueOf(DistanceTextD_Car));
}
});enter code here
Lamda:
CheckCar.setOnClickListener(view->CheckMotor.setChecked(false));
But how to add et_mileage.setText(String.valueOf(DistanceTextD_Car));

Just change the single expression to a statement block
CheckCar.setOnClickListener(view -> {
CheckMotor.setChecked(false));
et_mileage.setText(String.valueOf(DistanceTextD_Car));
});
As the docs say, the arrow token -> is followed by
A body, which consists of a single expression or a statement block.

CheckCar.setOnClickListener(view-> {
CheckMotor.setChecked(false);
et_mileage.setText(String.valueOf(DistanceTextD_Car));
});

Related

Handle Promise from Android WebView with evaluateJavascript

I'm working with the Android WebView and trying to handle the return of a JavaScript promise from the WebView on the Java side after calling it with evaluateJavascript.
document.java
Button buttonAnnotations = findViewById(R.id.buttonAnnotations);
buttonAnnotations.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
wv.evaluateJavascript("javascript:getAnnotations();", new ValueCallback<String>() {
#Override
public void onReceiveValue(String value) {
Toast.makeText(getApplicationContext(), value, Toast.LENGTH_SHORT).show();
}
});
}
});
index.html
async function getAnnotations() {
await pdfViewer.getAnnotations().then(result => {
return JSON.stringify(result ,null,2);
});
}
If I change the getAnnotations() function to not be async and return a string all works fine, so I'm trying to figure out how to handle this promise in the java code to get the result.
I've seen a few similar questions but none of the answers seemed to work in this case.
As I mentioned in the comment, you are returning a Promise from the async function getAnnotations (which cannot be used directly in onReceiveValue).
In order to "push" the result from getAnnotations back to Android, you have to use the JavascriptInterface:
In your Activity you can define:
#JavascriptInterface
public void onAnnotations(String result) {
Toast.makeText(WebViewActivity.this, result, Toast.LENGTH_LONG).show();
}
and register it with:
webView.addJavascriptInterface(this, "bridge");
In this case the method onAnnotations resists within the Activity which also contains the webView. Therefore I use "this" for the first Argument.
The "bridge" is the namespace, where you can find the function onAnnotations on the JavaScript side.
Now all you have to do, is to make the call from JavaScript to Android:
function getAnnotations() {
pdfViewer.getAnnotations().then(result => {
bridge.onAnnotations(JSON.stringify(result ,null,2));
});
}

Android studio login system

i am trying to create a login system on android studio using java, i have tried a piece of code i have found and modifies it to my own program- i am getting errors that the tutorial cannot explain and would appreciate if someone could tell me what i'm doing wrong.
on line 10 under username it says expression expected
The else statement says there should be an if but as you can see there is ?
public void LoginButton(){
UserName = findViewById(R.id.UserName);
userPassword = findViewById(R.id.userPassword);
userPin = findViewById(R.id.userPin);
GoBtn.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
if (UserName.getText().toString().equals("user");// here i would preferably link to a database but do to time restaitns i have modeled it with user
userPassword.getText().toString().equals("pass");
{
Toast.makeText(MainActivity.this, "Username and password is correct",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this, StudentActivity.class);
startActivity(intent);
}
else {
Toast.makeText(MainActivity.this,"Username and password is NOT correct",
Toast.LENGTH_SHORT).show();
}
}
I need this to lead the user to the next activty if the input is correct but so far i cannot get it to run due to the errors.
Issues
You can't use a semicolon (;) right after if statement because an empty ; is also considered a statement.
If Statement is incorrect: It has to be a valid statement
Many braces ({ and }) are missing
Here is a sample code
public void LoginButton() {
UserName = findViewById(R.id.UserName);
userPassword = findViewById(R.id.userPassword);
userPin = findViewById(R.id.userPin);
GoBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (UserName.getText().toString().equals("user") &&
userPassword.getText().toString().equals("pass")) {
// use your code
} else {
// use your code
}
}
});
}
Suggestion: Please read more Java
your if condition syntax is wrong you need to use AND operator(&&).
change these lines
if (UserName.getText().toString().equals("user");
userPassword.getText().toString().equals("pass");
to
if((UserName.getText().toString().equals("user")) && (userPassword.getText().toString().equals("pass")))

Android Questions App Answer==MyAnswer not null

I make android questions app. I can not find the right answer. Answer list.
Right answer: String answer = quizList.get(position).getAnswer();
Button Click:
buttonA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (answer =="A"){
lblsignboard.setText("Ok");
}
else
{
lblsignboard.setText("No");
}
}
});
Answer = "A", but this code does not work. Always gives the answer is no.
When you are comparing strings in java,always use .equals
Because the function (.equals) checks the actual contents of the string, the == operator checks whether the references to the objects are equal.
and now furthur using equalsignorecase you need not to worry about search string is in caps or small.
buttonA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (equalsIgnoreCase("a")){
lblsignboard.setText("Ok");
}else{
lblsignboard.setText("No");
}
}
});
You can use this way too, to keep you code working even the answer key is of different case. Use either equals("A") or equalsIgnoreCase("a").
buttonA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (answer.equals("A") || equalsIgnoreCase("a")){
lblsignboard.setText("Ok");
}else{
lblsignboard.setText("No");
}
}
});
In Android we make use of two things to compare strings:
1. equals : this is used when you want to compare even case of the string.
2. equalsIgnoreCase: This is just for content comparison.
Here is the small illustration as how it works:
String myString = "heLLo";
if(myString.equals("hello"))
{
System.out.print("equals");
}
else if(myString.equalsIgnoreCase("hello"))
{
System.out.print("equalsIgnoreCase");
}
Here equalsIgnoreCase will be printed.
Strings can only compare by .equals method not by ==. Also you have to check string is null or not because .equals method may invoke
nullpointerexception and you app may crash.
buttonA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(answer!=null &&(answer.equals("A")||equalsIgnoreCase("a"))) {
lblsignboard.setText("Ok");
} else {
lblsignboard.setText("No");
}
}
});
String can compare is .equals or .eqalignorecase not a '==' sign.'==' using a int value compare.
String answer=item.get(position).getAnswer();
if(answer!=null && (answer.equals("A")||equalsIgnoreCase("a")){
Log.e("Comapare","----------Success");
}else{
Log.e("Comapare","----------not compare");
}

Why is that unreachable code?

I'm generating a question and answers of that randomly. And I want to generate new random arrays and answer options according to those when users chose the correct answer. But it says "unreachable code" when I add a boolean while loop... What is theproblem?
Thanks...
final boolean basadon = false;
while(basadon)
{
Random soru = new Random();
final int[] rastgele = new int[1];
for (int i=0; i<1; i++)
{
rastgele[i]= soru.nextInt(8);
}
ArrayList<Integer> cevap = new ArrayList<Integer>();
for (int k = 0; k <= 7; ++k)
{
cevap.add(k);
}
final Integer[] rastgele2 = new Integer[4];
if (rastgele[0]!=cevap.get(0))
{
rastgele2[0]=cevap.get(0);
}
else
{
rastgele2[0]=cevap.get(3);
}
if (rastgele[0]!=cevap.get(1))
{
rastgele2[1]=cevap.get(1);
}
else
{
rastgele2[1]=cevap.get(3);
}
if (rastgele[0]!=cevap.get(2))
{
rastgele2[2]=cevap.get(2);
}
else
{
rastgele2[2]=cevap.get(3);
}
rastgele2[3]=rastgele[0];
Collections.shuffle(Arrays.asList(rastgele2));
view.setText(countries.get(rastgele[0]));
cevap1.setBackgroundResource(heads[rastgele2[0]]);
cevap1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (rastgele[0]==rastgele2[0])
{
cevap1.setBackgroundResource(heads[8]);
countries.remove(rastgele[0]);
basadon=true;
}
else {
cevap1.setBackgroundResource(heads[9]);
}
}
});
cevap2.setBackgroundResource(heads[rastgele2[1]]);
cevap2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (rastgele2[1]==rastgele[0])
{
cevap2.setBackgroundResource(heads[8]);
countries.remove(rastgele[0]);
basadon=true;
}
else {
cevap2.setBackgroundResource(heads[9]);
}
}
});
cevap3.setBackgroundResource(heads[rastgele2[2]]);
cevap3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (rastgele2[2]==rastgele[0])
{
cevap3.setBackgroundResource(heads[8]);
countries.remove(rastgele[0]);
basadon=true;
}
else {
cevap3.setBackgroundResource(heads[9]);
}
}
});
cevap4.setBackgroundResource(heads[rastgele2[3]]);
cevap4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (rastgele2[3]==rastgele[0])
{
cevap4.setBackgroundResource(heads[8]);
countries.remove(rastgele[0]);
basadon=true;
}
else {
cevap4.setBackgroundResource(heads[9]);
}
}
});
}
} }
Looks like you start with basedon value as false and later set it to true inside the loop.
So, Change
final boolean basedon = false
while (basedon) {
....
}
to
boolean basedon = false;
do {
....
} while (basedon);
while(basadon) is always false, so you never enter the loop. What you really mean is probably while(basadon==false). Also, don't declare basalon as final boolean because you want to modify its value later, and that will give error.
Why are you declaring all of those variables as final?
If bsadon for example needs to change from false to true, it can't be final. A final value is exactly that, a constant, it won't change.
Don't declare something as final unless you want it to keep the same value for the entire runtime of your program.
You are saying basadon is always "false", that's what final means, so the compiler is telling you you will never enter the while, since you need it to evaluate "true" to enter.
The expression between () in you while clause, needs to evaluate to true for the code to enter.
To your specific question which you have asked:
Why does the compiler give unreachable code warning
The answer is that since the condition in while loop is always false, there is no chance that the code in while loop will get executed. The warning is given to indicate that (given the current code situation) you have wasted your effort in typing that portion of code and it is guaranteed never to be executed. To rectify this, you can remove the final modifier from basedon and put a programming logic to set the value of basedon which will decide whether to enter the loop or not. If you want the loop to always run put while(true).
But I believe that what you wanted to ask was how to make the random question and answer generator. For that you'll have to post a bigger chunk of your code (It looks like you are trying to put a loop over a listener callback ?) and phrase your question to ask specific problems (possibly post a separate question).
It's probably complaining because basadon is known to be false and the body of the while loop cannot be reached. You can suppress the complaint by adding this annotation to the method:
#SuppressWarnings("unused")
You might also try removing the final modifier from the declaration of basadon. That might resolve the issue (but I'm not sure about that).
EDIT I finally noticed that you are trying to modify basadon directly from within your click listeners. That obviously won't work if basadon is final, yet you cannot access local variable unless it is final. I suggest you change basadon to be a (non-final) field of the enclosing class. Then all the warnings and errors should go away.

Login not working

I have written the simple code for Login authentication with hardcoded password.my problem is evenif I am entering the correct password my control is going in elese loop
edt=(EditText)findViewById(R.id.edt);
btn=(Button)findViewById(R.id.sub);
s1=edt.getText().toString();
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.d("mynameeeeee",s1);
if(s1=="123")
{
Toast.makeText(getApplicationContext(), "Successful",Toast.LENGTH_LONG).show();
}
else
{
Log.d("coming in elseeeee","coming in elseeeee");
Toast.makeText(getApplicationContext(), "not valid",Toast.LENGTH_LONG).show();
}
}
});
Here's the problem :
You are storing a reference of the edit text content at creation time, when the edit text is empty.
You should retrieve the content of the edit text EVERYTIME you want to compare, which is when the button is clicked in your case :
Do the following :
edt=(EditText)findViewById(R.id.edt);
btn=(Button)findViewById(R.id.sub);
btn.setOnClickListener ( new OnClickListener () {
#Override
public void onClick ( View v ) {
Log.d ( "mynameeeeee" , edt.getText().toString() );
if ( edt.getText().toString().equals ( "123" ) )
{
Toast.makeText(getApplicationContext(), "Successful",Toast.LENGTH_LONG).show();
}
else
{
Log.d("coming in elseeeee","coming in elseeeee");
Toast.makeText(getApplicationContext(), "not valid",Toast.LENGTH_LONG).show();
}
}
});
the string should be compared like:
if(s1.equals("123")) {}
Change your if statement like this
if(s1.equals("123"))
{
Toast.makeText(getApplicationContext(), "Successful",Toast.LENGTH_LONG).show();
}
else
{
Log.d("coming in elseeeee","coming in elseeeee");
Toast.makeText(getApplicationContext(), "not valid",Toast.LENGTH_LONG).show();
}
When comparing strings always use .equals() function
== Checks whether both the variable are referring to same object. In this case since they are referring to different object so the result of == is false.
use equals() method s1.equals("123") to check the content of the string object.

Categories

Resources