If statement depending on the random image shown - android

I have a imageview that randomly generate 1 out of 2 possibles images clicking on one button.
I want that when one image is showed (R.drawable.aa) and I press other button, a toast is shown.
My problem is that once a random image is shown and click on the other button, nothing happens.
package com.example.isaiasalarcon.menu;
import java.util.Random;
import java.util.jar.Attributes;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import static com.example.isaiasalarcon.menu.R.drawable.aa;
public class buho extends Activity {
// UI components
private Button drawButton;
private Button boton2;
private ImageView cardImage;
// Random object
private final static Random random = new Random();
// The card deck
private final static int[] cardDeck = new int[] {
R.drawable.aa,
R.drawable.a2,
};
private Integer q;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_buho);
drawButton = (Button)findViewById(R.id.drawButton);
boton2 = (Button)findViewById(R.id.button2);
cardImage = (ImageView)findViewById(R.id.cardImage);
drawButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0)
{
Integer q = cardDeck[random.nextInt(cardDeck.length)];
cardImage.setImageResource(q);
}
});
boton2.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
if (q.equals(R.drawable.aa)) {
Toast toast = Toast.makeText(buho.this, "si", Toast.LENGTH_LONG);
toast.show();
} else {
Toast toast = Toast.makeText(buho.this, "no", Toast.LENGTH_LONG);
toast.show();
}
}
});
}
}

two things:
1) Integer q I don't see a reason why this needs to be an Integer. You should be able to int
2) your q inside the onClick is creating a NEW variable called q. You need to update your code to the following: (note how it doesn't have the Type declaration before it, so it means to use the previously declared variable)
drawButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0)
{
q = cardDeck[random.nextInt(cardDeck.length)];
cardImage.setImageResource(q);
}
});

Related

How can i randomize question in a quiz app

I made a simple quiz on Android Studio which contains 3+ questions. How to make the questions become random without duplicated. This app does not use a database. I'm new to programming so I don't know what to do about this
MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog; import android.graphics.Color; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
TextView totalQuestionsTextView;
TextView questionTextView;
Button ansA,ansB,ansC,ansD;
Button submitBtn;
int score=0;
int totalQuestions = QuestionAnswer.question.length;
int currentQuestionIndex = 0;
String selectedAnswer = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
totalQuestionsTextView = findViewById(R.id.total_questions);
questionTextView = findViewById(R.id.question);
ansA = findViewById(R.id.ans_A);
ansB = findViewById(R.id.ans_B);
ansC = findViewById(R.id.ans_C);
ansD = findViewById(R.id.ans_D);
submitBtn = findViewById(R.id.submbit_btn);
ansA.setOnClickListener(this);
ansB.setOnClickListener(this);
ansC.setOnClickListener(this);
ansD.setOnClickListener(this);
submitBtn.setOnClickListener(this);
totalQuestionsTextView.setText("Total Questions : "+totalQuestions);
loadNewQuestion();
}
#Override
public void onClick(View view) {
ansA.setBackgroundColor(Color.WHITE);
ansB.setBackgroundColor(Color.WHITE);
ansC.setBackgroundColor(Color.WHITE);
ansD.setBackgroundColor(Color.WHITE);
Button clickedButton = (Button) view;
if(clickedButton.getId()==R.id.submbit_btn){
currentQuestionIndex++;
loadNewQuestion();
}else{
//choices button clicked
selectedAnswer = clickedButton.getText().toString();
clickedButton.setBackgroundColor(Color.MAGENTA);
}
}
void loadNewQuestion(){
if(currentQuestionIndex == totalQuestions){
finishQuiz();
return;
}
questionTextView.setText(QuestionAnswer.question[currentQuestionIndex]);
ansA.setText(QuestionAnswer.choices[currentQuestionIndex][0]);
ansB.setText(QuestionAnswer.choices[currentQuestionIndex][1]);
ansC.setText(QuestionAnswer.choices[currentQuestionIndex][2]);
ansD.setText(QuestionAnswer.choices[currentQuestionIndex][3]);
}
void finishQuiz(){
String passStatus = "";
if (score > totalQuestions*0.60){
passStatus = "Passes";
}else{
passStatus = "Failed";
}
new AlertDialog.Builder(this)
.setTitle(passStatus)
.setMessage("Score is "+score+" out of "+ totalQuestions)
.setPositiveButton("Restart",(dialogInterface, i) -> restartQuiz())
.setCancelable(false)
.show();
}
void restartQuiz(){
score = 0;
currentQuestionIndex = 0;
loadNewQuestion();
}
QuestionAnswer.java
import java.util.Arrays; import java.util.List; import java.util.Random;
public class QuestionAnswer {
public static String[] question = {
"Which company own the android?",
"Which one is not the programming language?",
"Where are you watching this video"
};
public static String choices[][] = {
{"Google", "Apple", "Nokia", "Samsung"},
{"Java", "Kotlin", "Notepad", "Python"},
{"Facebook", "Whatsapp", "Instagram", "Youtube"},
};
public static String correctAnswers[] = {
"Google",
"Notepad",
"Youtube"
};
}
how can i add shuffle.collection or random to make my app show random question instead
You need to find out about Random class first in Java. Thereafter, you will create a random number using Random class in onClick function, then set a question's index to your Random number

How can set my button a random color to the background. Android

Sorry for my bad English I'm a beginner of android and now I'm stuck.
Now my Question is how can I set the random colors to the background with the OnClickListener. Can you maybe help my with this problem?
I have one class (Kleurenpalet.java)
package com.example.pstek.randomcolor;
import android.graphics.Color;
import java.util.Random;
public class Kleurenpalet{
private static String[] kleur = {
"#39add1", // light blue
"#3079ab", // dark blue
"#3FD52D", // green
"FFFF0000", // red
""};
public int getRandomColor() {
Random rand = new Random();
int color = rand.nextInt(kleur.length);
return Color.parseColor(kleur[color]);
}
}
And I have my main class :
package com.example.pstek.tegeltjeswijsheid;
import android.support.constraint.ConstraintLayout;
import android.support.constraint.solver.widgets.ConstraintWidget;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Layout;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
private ConstraintLayout layout;
private Button randombutton;
int randomColor = new Kleurenpalet().getRandomColor();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
layout = findViewById(R.id.layout);
randombutton = findViewById(R.id.button);
randombutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
layout.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), ;
}
});
}
}
in the MainActivity code this :
public class MainActivity extends AppCompatActivity {
private ConstraintLayout layout;
private Button randombutton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
layout = findViewById(R.id.layout);
randombutton = findViewById(R.id.button);
randombutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int randomColor = new Kleurenpalet().getRandomColor();
layout.setBackgroundColor(randomColor);
}
});
}
}
Perhaps call setBackgroundColor with the initialized color:
layout.setBackgroundColor(randomColor);
Or a different one each time:
layout.setBackgroundColor(new Kleurenpalet().getRandomColor());
I do not understand what you try to do here:
layout.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), ;
Why did you leave empty space there? Moreover, if you parse color in your Kleurenpalet, you must use without ContextCompat. Just set your color like this:
layout.setBackgroundColor(randomColor);
ContextCompat is for parsing color from resources file, for instance:
layout.setBackgroundColor(
ContextCompat.getColor(
getApplicationContext(),
R.color.colorPrimary
)
);
You must put "Random Num" and "layout set Color" in button click event :
randombutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int randomColor = new Kleurenpalet().getRandomColor();
layout.setBackgroundColor(randomColor);
}
});

A simple app with a textview and two buttons that trigger toasts not working

It's just a simple text with two buttons that creates toasts and change the text. I'm very new to this AS so I really don't know how to even attempt to fix this..
Any help is very appreciated...
MainActivity.java:
package com.example.david.davidisawesome;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate: Started.");
final TextView firstText = (TextView) findViewById(R.id.firstText);
Button firstButton = (Button) findViewById(R.id.firstBtn);
Button secondButton = (Button) findViewById(R.id.secondBtn);
firstButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "onClick: First Button Clicked.");
toastMessage("You Clicked the first button");
firstText.setText("Nice Job.");
}
});
secondButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "onClick: Second Button Clicked.");
toastMessage("You Clicked the second button");
firstText.setText("Good Effort.");
}
});
}
private void toastMessage(String message){
Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
}
}
In picture:
activity_main.xml:
Error:
It is not finding your xml elements. The error shows that you have a null exception on setting the onclick interface to the button. So start by confirming that you are inflating the proper xml and finding the proper id.
More specifically your secondBtn is not found.

How to implement the prev and next button

I want to implement 2 activities , one is a listview with image and text which works well now. The other one is a onClicklistener when I click any ListItem it will start another activity to show more information, with 1 previous button and next button to see the Prev information or next. However there is something wrong with the button. It can only see the previous one and next one once. Which means you can't click the next button twice. Any suggestions will be appreciated .
Here is my main activity code
package com.example.manchesterunited;
import com.example.manchesterunited.R;
import android.os.Bundle;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Intent;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
static PlayerData data = new PlayerData();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CustomAdapter adapter = new CustomAdapter(this);
setListAdapter(adapter);
}
public void onListItemClick(ListView l,View v, int pos, long id){
int playerId = (int)id;
Toast.makeText(getApplicationContext(),"Selected "+data.getName(pos),Toast.LENGTH_SHORT).show();
Intent intent = new Intent(this, InfoActivity.class);
intent.putExtra("playerId", playerId);
startActivity(intent);
}
}
And here is the second activity
package com.example.manchesterunited;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class InfoActivity extends Activity {
TextView dobText;
TextView pobText;
TextView internationalText;
Button prevButton;
Button nextButton;
PlayerData data = new PlayerData();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_info);
dobText = (TextView)findViewById(R.id.textView1);
pobText = (TextView)findViewById(R.id.textView2);
internationalText = (TextView)findViewById(R.id.textView3);
prevButton = (Button)findViewById(R.id.prev);
nextButton = (Button)findViewById(R.id.next);
Intent intent = getIntent();
final int playerId = intent.getExtras().getInt("playerId");
dobText.setText("Birthdate:"+String.valueOf(data.getPlayer(playerId).getDob()));
pobText.setText("Birthplace:"+String.valueOf(data.getPlayer(playerId).getPob()));
internationalText.setText("International:"+data.getPlayer(playerId).getInternational());
prevButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int newId = playerId-1;
dobText.setText("Birthdate:"+String.valueOf(data.getPlayer(newId).getDob()));
pobText.setText("Birthplace:"+String.valueOf(data.getPlayer(newId).getPob()));
internationalText.setText("International:"+data.getPlayer(newId).getInternational());
}
});
nextButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int newId = playerId+1;
dobText.setText("Birthdate:"+String.valueOf(data.getPlayer(newId).getDob()));
pobText.setText("Birthplace:"+String.valueOf(data.getPlayer(newId).getPob()));
internationalText.setText("International:"+data.getPlayer(newId).getInternational());
}
});}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_info, menu);
return true;
}
}
You're not updating the playerID.
You're just getting a new ID.
you should put
int newId = playerId+1;
playerID = newId; //insert this line
so that when you click again,
playerID gets updated.
You are always adding just 1 to player ID which will now point to next item. But as soon as you re-click the button it will have the same player ID that was passed through intent. So again it will add in the same value. Make a new variable which will store the current player ID that is visible and keep on incrementing it then you will be able to browse next and vice versa in the previous case.
You can't increment player ID as it has been declared as final, so you can either make a global variable or put a variable in intent and increment it on button clicks.
nextButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
//make newId global then it will work. And keep on updating it when the button is clicked accordingly.
newId = playerId+1;
dobText.setText("Birthdate:"+String.valueOf(data.getPlayer(newId).getDob()));
pobText.setText("Birthplace:"+String.valueOf(data.getPlayer(newId).getPob()));
internationalText.setText("International:"+data.getPlayer(newId).getInternational());
}
});}
Try this on InfoActivity,
private int playerId;
...
...onCreate(...){
...
playerId = intent.getExtras().getInt("playerId");
prevButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
...
playerId--;
dobText.setText("Birthdate:"+String.valueOf(data.getPlayer(playerId).getDob()));
pobText.setText("Birthplace:"+String.valueOf(data.getPlayer(playerId).getPob()));
internationalText.setText("International:"+data.getPlayer(playerId).getInternational());
}
}
nextButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
...
playerId++;
dobText.setText("Birthdate:"+String.valueOf(data.getPlayer(playerId).getDob()));
pobText.setText("Birthplace:"+String.valueOf(data.getPlayer(playerId).getPob()));
internationalText.setText("International:"+data.getPlayer(playerId).getInternational());
}
}
}

I want to display seperate alerts for name and pass fields

Here is my code:
package com.example.userpage;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class UserPage extends Activity {
AlertDialog.Builder builder;
private final static int EMPTY_TEXT_ALERT = 0;
#Override
public Dialog onCreateDialog(int id) {
switch(id) {
case EMPTY_TEXT_ALERT: {
builder = new AlertDialog.Builder(this);
builder.setMessage("Message:Fields Empty!!!")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
return builder.create();
}
}
return null;
}
String tv,tv1;
EditText name,pass;
TextView x,y;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.widget44);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent obj = new Intent(UserPage.this,UserPage.class);
startActivity(obj);
}
});
x = (TextView) findViewById(R.id.widget46);
y = (TextView) findViewById(R.id.widget47);
name = (EditText)findViewById(R.id.widget41);
pass = (EditText)findViewById(R.id.widget43);
Button button1 = (Button) findViewById(R.id.widget45);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//tv= name.getText().toString();
//tv1 = pass.getText().toString();
x.setText(tv);
y.setText(tv1);
tv = name.getText().toString();
if(tv.trim().equals("")) {
// text is empty
showDialog(EMPTY_TEXT_ALERT);
}
tv1 = pass.getText().toString();
if (tv1.trim().equals(""))
{
showDialog(EMPTY_TEXT_ALERT);
}
}
});
}
}
What is happening when you try to run it? Which part are you having a problem with?
From what I can tell your code is not going to display any dialogs because you've never called the dialog.show() method. You'd have to do something like this for the way you have it set up:
showDialog(EMPTY_TEXT_ALERT).show();
If you are trying to make it two separate dialogs, one for name, and one for pass then all you'd have to do is make another id variable and add a case: for it inside the switch statement that inside your showDialog(id) method.
You should also really consider using descriptive names for your variables. Your code would be easier to understand if you didn't use names like x,y, and widget#.

Categories

Resources