Multiple ImageButtons in a single Android Activity - java

I'm creating an app that needs multiple Image Buttons. When I have more that 1 with the images loaded the app stops responding.
I dont get any error messages it just stops working?
This is the code i'm using:
public class ItemMatch extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_match);
ImageButton Ariel = (ImageButton)findViewById(R.id.imageButtonAriel);
ImageButton Belle = (ImageButton)findViewById(R.id.imageButtonBelle);
//*****SETTING IMAGES TO BUTTONS*****
Ariel.setImageResource(R.drawable.ariel);
Belle.setImageResource(R.drawable.belle);
//******LISTENERS FOR IMAGE BUTTONS*****
Ariel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast aTest = Toast.makeText(getApplicationContext(), "Ariel!", Toast.LENGTH_SHORT);
aTest.show();
}
});
Belle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast aTest = Toast.makeText(getApplicationContext(), "Belle!", Toast.LENGTH_SHORT);
aTest.show();
}
});
//*****COUNTDOWN TIMER*****
final TextView text1=(TextView)findViewById(R.id.textView2);
final TextView score =(TextView)findViewById(R.id.textView3);
new CountDownTimer(30000,1000){
#Override
public void onTick(long millisUntilFinished) {
text1.setText("Time Left: " + millisUntilFinished /1000 + "s");
score.setText("Score: ");
}
#Override
public void onFinish() {
text1.setText("GAME OVER!");
}
}.start();
}
This is my XML for it:
<TextView
android:layout_width="100dp"
android:layout_height="100dp"
android:text=""
android:id="#+id/textView2"
android:clickable="false"
android:textAlignment="center"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="75dp"
android:layout_height="75dp"
android:text=""
android:id="#+id/textView3"
android:layout_alignTop="#+id/textView2"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<ImageButton
android:layout_width="90dp"
android:layout_height="90dp"
android:scaleType="fitXY"
android:id="#+id/imageButtonAriel"
android:layout_above="#+id/imageButtonBelle"
android:layout_alignRight="#+id/textView2"
android:layout_alignEnd="#+id/textView2" />
<ImageButton
android:layout_width="90dp"
android:layout_height="90dp"
android:scaleType="fitXY"
android:id="#+id/imageButtonBelle"
android:layout_alignParentBottom="true"
android:layout_alignLeft="#+id/imageButtonAriel"
android:layout_alignStart="#+id/imageButtonAriel" />
<ImageView
android:layout_width="200dp"
android:layout_height="250dp"
android:scaleType="fitXY"
android:src="#drawable/belle"
android:id="#+id/imageView"
android:layout_below="#+id/textView3"
android:layout_centerHorizontal="true" />

Related

My button for changing activity is not working

So....i am trying to make this button change from main activity to Disciplinas_Activity. But whenever I try to run the app and click the button, the app crashes.
Keep in mind i have other 3 button completly identical ,(other then the fact that they direct to different activities), in the same activity and they all work with the same base code.
Here is the .xml code for Main Activity
<TextView
android:id="#+id/textView_emailnotverified"
android:layout_width="172dp"
android:layout_height="34dp"
android:background="#color/white"
android:text="Email não Verificado!"
android:textColor="#E41F1F"
android:textSize="18dp"
android:visibility="gone"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.066"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.516" />
<TextView
android:id="#+id/textView_studentEmail"
android:layout_width="237dp"
android:layout_height="40dp"
android:text="Email do aluno"
android:textColor="#color/white"
android:textSize="18dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.856"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.395" />
<ImageView
android:id="#+id/imageView4"
android:layout_width="332dp"
android:layout_height="168dp"
android:scaleX="2"
android:scaleY="1.3"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.493"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.028"
app:srcCompat="#drawable/etpr" />
<TextView
android:id="#+id/welcommingtextview5"
android:layout_width="337dp"
android:layout_height="39dp"
android:text="ESCOLA TÉCNICA E PROFISSIONAL DO RIBATEJO"
android:textAlignment="center"
android:textColor="#color/white"
android:textSize="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.459"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.15" />
<TextView
android:id="#+id/ETPRTitle5"
android:layout_width="258dp"
android:layout_height="30dp"
android:text="BEM-VINDO À ETPR"
android:textAlignment="center"
android:textColor="#color/white"
android:textSize="24dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.496"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.105" />
<Button
android:id="#+id/Button_LOGOUT"
android:layout_width="114dp"
android:layout_height="59dp"
android:text="Logout"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.934" />
<Button
android:id="#+id/button_Testes"
android:layout_width="108dp"
android:layout_height="47dp"
android:text="Testes"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.867"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.644" />
<Button
android:id="#+id/button_pdf"
android:layout_width="121dp"
android:layout_height="41dp"
android:text="PDF"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.894"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.753" />
<Button
android:id="#+id/button_historia"
android:layout_width="191dp"
android:layout_height="47dp"
android:text="Sobre o criador"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.149"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.76" />
<ImageView
android:id="#+id/imageView_perfil"
android:layout_width="122dp"
android:layout_height="118dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.055"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.376"
app:srcCompat="#mipmap/ic_launcher" />
<TextView
android:id="#+id/textView_studentname"
android:layout_width="236dp"
android:layout_height="33dp"
android:text="Nome do aluno"
android:textColor="#color/white"
android:textSize="18dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.857"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.329" />
<Button
android:id="#+id/button_emailverification"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Verificar agora"
android:visibility="gone"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.88"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.527" />
<Button
android:id="#+id/changeprofileBTN"
android:layout_width="245dp"
android:layout_height="41dp"
android:text="Mude a imagem de perfil"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.897"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.453" />
<Button
android:id="#+id/button_disciplinas"
android:layout_width="194dp"
android:layout_height="55dp"
android:text="Disciplinas"
android:clickable="true"
android:focusable="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.106"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.644" />
Here is my .java code for main activity
public class MainActivity extends AppCompatActivity {
TextView fullname, email, verifymessage;
FirebaseAuth fAuth;
FirebaseFirestore fstore;
String userID;
Button resendVerification, LogoutBTN, changeprofileBTN, tests, createrInfo, pdfdatabase, buttonDisciplinas;
ImageView profileImage;
StorageReference storageReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fullname = findViewById(R.id.textView_studentname);
email = findViewById(R.id.textView_studentEmail);
LogoutBTN = (Button) findViewById(R.id.Button_LOGOUT);
tests =(Button) findViewById(R.id.button_Testes);
createrInfo =(Button) findViewById(R.id.button_historia);
pdfdatabase =(Button) findViewById(R.id.button_pdf);
buttonDisciplinas = findViewById(R.id.button_disciplinas);
buttonDisciplinas.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, Disciplinas_Activity.class));
}
});
tests.setOnClickListener(new View.OnClickListener() {// menu dos testes
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(),Testes_Activity.class));
}
});
createrInfo.setOnClickListener(new View.OnClickListener() {//página sobre a história da app
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(),AboutMe_Activity.class));
}
});
pdfdatabase.setOnClickListener(new View.OnClickListener() {//pdf database
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(),PDF_Activity.class));
}
});
LogoutBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(getApplicationContext(),LoginScreen.class));
finish();
}
});
profileImage = findViewById(R.id.imageView_perfil);
changeprofileBTN = findViewById(R.id.changeprofileBTN);
fAuth = FirebaseAuth.getInstance();
fstore = FirebaseFirestore.getInstance();
storageReference = FirebaseStorage.getInstance().getReference();
StorageReference profileRef = storageReference.child("utilizadores/"+fAuth.getCurrentUser().getUid()+"/perfil.jpg");
profileRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Picasso.get().load(uri).into(profileImage);
}
});
resendVerification = findViewById(R.id.button_emailverification);
verifymessage = findViewById(R.id.textView_emailnotverified);
userID = fAuth.getCurrentUser().getUid();
DocumentReference documentReference = fstore.collection("utilizadores").document(userID);
documentReference.addSnapshotListener(this, new EventListener<DocumentSnapshot>() {
#Override
public void onEvent(#Nullable DocumentSnapshot documentSnapshot, #Nullable FirebaseFirestoreException error) {
fullname.setText(documentSnapshot.getString("NomeCompleto"));
email.setText(documentSnapshot.getString("Email"));
}
});
FirebaseUser user = fAuth.getCurrentUser();
if (!user.isEmailVerified()){
verifymessage.setVisibility(View.VISIBLE);
resendVerification.setVisibility(View.VISIBLE);
resendVerification.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
user.sendEmailVerification().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(v.getContext(),"Email de verificação enviado.", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d("tag","Erro: Email de verificação não enviado " + e.getMessage());
}
});
}
});
}
changeprofileBTN.setOnClickListener(new View.OnClickListener() { //mudar imagem de perfil
#Override
public void onClick(View v) {
Intent openGalleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(openGalleryIntent,1000);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1000 ){
if (resultCode == Activity.RESULT_OK){//se o resultado for igual então abre galeria
Uri imageUri = data.getData();
//profileImage.setImageURI(imageUri); //insere imagem escolhida na galeria
uploadImageToFirebase(imageUri);
}
}
}
private void uploadImageToFirebase(Uri imageUri) { //upload da imagem para base de dados
StorageReference fileReference = storageReference.child("utilizadores/"+fAuth.getCurrentUser().getUid()+"/perfil.jpg");
fileReference.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
fileReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Picasso.get().load(uri).into(profileImage);
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this,"Erro", Toast.LENGTH_SHORT).show();
}
});
}
}
Here is .xml code for DisciplinasActivity
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:id="#+id/Relative_Layout_Title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="32dp"
android:layout_marginRight="20dp">
<TextView
android:id="#+id/Menu_Title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Disciplinas"
android:textColor="#color/white"
android:textSize="22sp">
</TextView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/Menu_Title"
android:layout_marginTop="6dp"
android:text="ETPR"
android:textColor="#color/white"
android:textSize="14sp">
</TextView>
<TextView
android:id="#+id/Name_Data"
android:textColor="#color/white"
android:textSize="16sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toStartOf="#id/user_icon"
android:text="Nome">
</TextView>
<TextView
android:id="#+id/Email_Data"
android:textColor="#color/white"
android:textSize="16dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/Name_Data"
android:layout_toStartOf="#id/user_icon"
android:text="Email">
</TextView>
<ImageView
android:id="#+id/user_icon"
android:layout_width="62dp"
android:layout_height="62dp"
android:layout_alignParentRight="true"
app:srcCompat="#drawable/cara">
</ImageView>
</RelativeLayout>
<GridLayout
android:id="#+id/MainGrid"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="#+id/Relative_Layout_Title"
android:alignmentMode="alignMargins"
android:columnCount="2"
android:columnOrderPreserved="false"
android:rowCount="2">
<androidx.cardview.widget.CardView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_rowWeight="1"
android:layout_columnWeight="1"
android:layout_margin="12dp"
android:layout_marginTop="70dp"
app:cardCornerRadius="12dp"
app:cardElevation="6dp">
<LinearLayout
android:id="#+id/LinearLayoutSdac"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:orientation="vertical"
android:padding="16dp">
<ImageView
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_gravity="center"
android:src="#drawable/sdac_icon"/>
<TextView
android:layout_width="56dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="12dp"
android:text="SDAC"
android:textColor="#color/black"
android:textSize="18sp">
</TextView>
</LinearLayout>
</androidx.cardview.widget.CardView>
<androidx.cardview.widget.CardView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_rowWeight="1"
android:layout_columnWeight="1"
android:layout_margin="12dp"
android:layout_marginTop="70dp"
app:cardCornerRadius="12dp"
app:cardElevation="6dp">
<LinearLayout
android:id="#+id/LinearLayoutEletronica"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:orientation="vertical"
android:padding="16dp">
<ImageView
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_gravity="center"
android:src="#drawable/eletronica_icon"
app:srcCompat="#drawable/eletronica_icon" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="12dp"
android:text="Eletrónica"
android:textColor="#color/black"
android:textSize="18sp"/>
</LinearLayout>
</androidx.cardview.widget.CardView>
<androidx.cardview.widget.CardView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_rowWeight="1"
android:layout_columnWeight="1"
android:layout_margin="12dp"
android:layout_marginTop="70dp"
app:cardCornerRadius="12dp"
app:cardElevation="6dp">
<LinearLayout
android:id="#+id/LinearLayoutCD"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:orientation="vertical"
android:padding="16dp">
<ImageView
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_gravity="center"
android:src="#drawable/cd_icon"
app:srcCompat="#drawable/cd_icon" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="12dp"
android:text="CD"
android:textColor="#color/black"
android:textSize="18sp" />
</LinearLayout>
</androidx.cardview.widget.CardView>
<androidx.cardview.widget.CardView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_rowWeight="1"
android:layout_columnWeight="1"
android:layout_margin="12dp"
android:layout_marginTop="70dp"
app:cardCornerRadius="12dp"
app:cardElevation="6dp">
<LinearLayout
android:id="#+id/LinearLayoutIMEI"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:orientation="vertical"
android:padding="16dp">
<ImageView
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_gravity="center"
android:src="#drawable/imei_icon"
app:srcCompat="#drawable/imei_icon" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="12dp"
android:text="IMEI"
android:textColor="#color/black"
android:textSize="18sp" />
</LinearLayout>
</androidx.cardview.widget.CardView>
</GridLayout>
<Button
android:id="#+id/ExitButton"
android:layout_marginTop="20dp"
android:layout_width="121dp"
android:layout_height="69dp"
android:layout_gravity="center"
android:layout_marginBottom="#+id/RelativeLayout"
android:text="Sair"
android:textColor="#color/white"
android:textSize="16dp" />
</LinearLayout>
Here is my .Java code for DisciplinasActivity
public class Disciplinas_Activity extends AppCompatActivity {
GridLayout gridPrincipal;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_disciplinas);
gridPrincipal = (GridLayout)findViewById(R.id.MainGrid); //identifica qual a grelha
//ação
setSingleEvent(gridPrincipal);
}
private void setSingleEvent(GridLayout gridPrincipal) {
for (int i =0;i<gridPrincipal.getChildCount();i++)
{
CardView cardView = (CardView)gridPrincipal.getChildAt(i);
final int finalI = i;
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(),TeacherLoginScreen.class));//muda para Disciplina de Sdac
}
});
}
}
}
What am i missing...? if all the other 3 buttons work...why doesnt this one work? (I am a total newbie but i
I really need the help)
Consider your code
button = (Button)findViewById(R.id.button1);
You do not need to explicitly cast widgets anymore unless it's a special case like a RadioButton from a resource ID.
Please check that the button you're clicking is actually the button you set all this up for.
Add
android:clickable="true";
android:focusable="true";
to your buttons in the XML layout.
I'm guessing ConstraintLayout is creating this problem, you shouldn't come across this issue if you use LinearLayout.
In your .xml code for DisciplinasActivity you have some mistakes on the dimensions that you are using:
<GridLayout
...
android:id="#+id/MainGrid"
...
android:layout_marginBottom="#+id/Relative_Layout_Title" <!-- E.G 20dp -->
>
<Button
android:id="#+id/ExitButton"
...
android:layout_marginBottom="#+id/RelativeLayout" <!-- E.G 20dp -->
... />
For margins, padding, etc you have to use a dimension, like dp,in,mm,etc not a reference to other view, or you could use dimmens.xml maybe you are confusing android:layout_marginBottom with android:layout_constraintBottom_toBottomOf or another property. Check for this in all the elements in your .xml
This answer is due to this log that you posted:
ComponentInfo{studying.app.tkappv6/studying.app.tkappv6.Disciplinas_Activity}:
java.lang.UnsupportedOperationException: Can't convert to dimension:
type=0x12
In the MainActivity
Change the to "v.getContext()" istead of "MainActivity.this"
tests.setOnClickListener(new View.OnClickListener() {// menu dos testes
#Override
public void onClick(View v) {
startActivity(new Intent(v.getContext(), Testes_Activity.class));
}
});
createrInfo.setOnClickListener(new View.OnClickListener() {//página sobre a história da app
#Override
public void onClick(View v) {
startActivity(new Intent(v.getContext(), AboutMe_Activity.class));
}
});
pdfdatabase.setOnClickListener(new View.OnClickListener() {//pdf database
#Override
public void onClick(View v) {
startActivity(new Intent(v.getContext(),PDF_Activity.class));
}
});
LogoutBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(v.getContext(),LoginScreen.class));
finish();
}
});
I was Looking into the code and i've never used this method, but it's strange for me so it's good to pay attention, I think is wrong to set a "Void", if the method is not going to receive any value, but since is a #Override method if it was that way from the beginning you don't need to change;
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(v.getContext(),"Email de verificação enviado.", Toast.LENGTH_SHORT).show();
}
Give a try and let's see if works!

Android Studio button going in to wrong page

In my main page I have 3 different buttons.
Login (loginB)
Create a new account (createB)
Terms of conduct (termsB)
So far it has worked just fine, but for some reason I have now faced a problem with the create new account button. It did go to the right page before but now it goes to a wrong page. It should be going to the CreateAccount -page but it is going to the Menu -page.
I have the java code in the MainActivity were the buttons are here:
public class MainActivity extends AppCompatActivity {
Button loginB;
Button termsB;
Button createB;
EditText emailL,passwordL;
FirebaseAuth fAuth;
ProgressBar progressB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createB = findViewById(R.id.createB);
createB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openCreateAccount();
}
});
termsB = findViewById(R.id.termsB);
termsB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openTermsOfConduct();
}
});
emailL = findViewById(R.id.emailL);
passwordL = findViewById(R.id.passwordL);
fAuth = FirebaseAuth.getInstance();
loginB = findViewById(R.id.loginB);
progressB = findViewById(R.id.progressB);
loginB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = emailL.getText().toString().trim();
String password = passwordL.getText().toString().trim();
if(TextUtils.isEmpty(email)){
emailL.setError("Email is required.");
return;
}
if(TextUtils.isEmpty(password)){
passwordL.setError("Password is required.");
return;
}
if(password.length() <6){
passwordL.setError("Password must be at least 6 characters.");
}
progressB.setVisibility(View.VISIBLE);
//authenticate the user
fAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Toast.makeText(MainActivity.this, "Logged in successfully", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),Menu.class));
}
else{
Toast.makeText(MainActivity.this, "Error " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
progressB.setVisibility(View.INVISIBLE);
}
}
});
}
});
}
public void openCreateAccount(){
Intent intent = new Intent(this, CreateAccount.class);
startActivity(intent);
}
public void openTermsOfConduct(){
Intent intent = new Intent(this, TermsOfConduct.class);
startActivity(intent);
}
}
Main Activity xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity"
android:background="#drawable/tausta">
<TextView
android:layout_width="match_parent"
android:layout_height="180dp"
android:fontFamily="sans-serif"
android:paddingVertical="30dp"
android:text="Login"
android:textAlignment="center"
android:textColor="#000"
android:textSize="90sp"
android:layout_marginBottom="25dp"
/>
<EditText
android:id="#+id/emailL"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginHorizontal="30dp"
android:layout_marginBottom="30dp"
android:textColor="#fff"
android:textSize="25sp"
android:hint="Email"
android:textColorHint="#fff"
/>
<EditText
android:id="#+id/passwordL"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginHorizontal="30dp"
android:inputType="textPassword"
android:layout_marginBottom="30dp"
android:textColor="#fff"
android:textSize="25sp"
android:hint="Password"
android:textColorHint="#fff"
/>
<Button
android:id="#+id/loginB"
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="Login"
android:layout_marginHorizontal="30dp"
android:layout_marginBottom="25dp"
android:background="#drawable/button_bg"
/>
<Button
android:id="#+id/createB"
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="Create a new account"
android:layout_marginHorizontal="30dp"
android:layout_marginBottom="25dp"
android:background="#drawable/button_bg"
/>
<Button
android:id="#+id/termsB"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Terms and conditions"
android:layout_marginHorizontal="30dp"
android:textColor="#0070ff"
android:textAlignment="center"
android:background="#android:color/transparent"
/>
<ProgressBar
android:id="#+id/progressB"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="invisible"
/>
</LinearLayout>
CreateAccount java:
public class CreateAccount extends AppCompatActivity {
Button registerB;
EditText nameR,emailR,pnumberR,passwordR;
FirebaseAuth fAuth;
ProgressBar progressB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_account2);
nameR = findViewById(R.id.nameR);
emailR = findViewById(R.id.emailR);
pnumberR = findViewById(R.id.pnumberR);
passwordR = findViewById(R.id.passwordR);
progressB = findViewById(R.id.progressB);
fAuth = FirebaseAuth.getInstance();
//check if user registered
if(fAuth.getCurrentUser() != null){
startActivity(new Intent(getApplicationContext(),Menu.class));
finish();
}
registerB = findViewById(R.id.registerB);
registerB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = emailR.getText().toString().trim();
String password = passwordR.getText().toString().trim();
if(TextUtils.isEmpty(email)){
emailR.setError("Email is required.");
return;
}
if(TextUtils.isEmpty(password)){
passwordR.setError("Password is required.");
return;
}
if(password.length() <6){
passwordR.setError("Password must be ata least 6 characters.");
return;
}
progressB.setVisibility(View.VISIBLE);
//register the user to FireBase
fAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Toast.makeText(CreateAccount.this, "User created.", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),Menu.class));
}
else{
Toast.makeText(CreateAccount.this, "Error " +task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
}
CreateAccount xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".CreateAccount"
android:background="#drawable/tausta"
>
<TextView
android:layout_width="match_parent"
android:layout_height="100dp"
android:fontFamily="sans-serif"
android:paddingVertical="20dp"
android:text="Create new account"
android:textAlignment="center"
android:textColor="#000"
android:textSize="40sp"
android:layout_marginBottom="25dp"
/>
<EditText
android:id="#+id/nameR"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Full name"
android:textColorHint="#fff"
android:textSize="25sp"
android:layout_marginHorizontal="25dp"
android:layout_marginBottom="30dp"
/>
<EditText
android:id="#+id/emailR"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Email"
android:textColorHint="#fff"
android:textSize="25sp"
android:layout_marginHorizontal="25dp"
android:layout_marginBottom="30dp"
/>
<EditText
android:id="#+id/pnumberR"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Phone number"
android:textColorHint="#fff"
android:textSize="25sp"
android:layout_marginHorizontal="25dp"
android:layout_marginBottom="30dp"
/>
<EditText
android:id="#+id/passwordR"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Password"
android:textColorHint="#fff"
android:textSize="25sp"
android:layout_marginHorizontal="25dp"
android:layout_marginBottom="30dp"
/>
<Button
android:id="#+id/registerB"
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="Register"
android:layout_marginHorizontal="30dp"
android:layout_marginBottom="25dp"
android:background="#drawable/button_bg"
/>
<ProgressBar
android:id="#+id/progressB"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="invisible"
/>
</LinearLayout>
I guess you should definitely check(R.layout.activity_create_account2)and whether it is the correct xml for the CreateAccount.java
P.S. While posting questions, always mention the correct name of the xml too.
The following code might be the cause:
if(fAuth.getCurrentUser() != null){
startActivity(new Intent(getApplicationContext(),Menu.class));
finish();
}
Can you check if it's going into the if block?

How can i changing text button by user input

in my exercise in which there are a grid of 3x3 buttons some with numbers others without, I should put those without numbers a number from 0-9, however, put by the user then changing the text of the button. How can I do? I tried something but it doesn't work even when I search on the internet it didn't give me the result I wanted.
This is the code
public class MainActivity extends AppCompatActivity {
private Button btn;
private EditText edit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.button_X00);
edit = (EditText) findViewById(R.id.edit_dialog);
btn.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
showDialog(edit.getText().toString());
return true;
}
});
}
private void showDialog(String str) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("input text");
View view = LayoutInflater.from(this).inflate(R.layout.activity_main, null);
final EditText edit_dialog = (EditText) view.findViewById(R.id.edit_dialog);
edit_dialog.setText(str);
builder.setView(view);
builder.setNegativeButton("cancel",null);
builder.setPositiveButton("confirm", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
btn.setText(edit_dialog.getText().toString());
}
});
builder.show();
}
}
THIS IS THE XML CODE
<LinearLayout
android:id="#+id/linearLayout2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/text_view_p8"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="GRIGLIAMOD10"
android:textSize="30sp" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="418dp"
android:layout_height="586dp"
android:layout_marginTop="49dp"
android:orientation="vertical"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/linearLayout2">
<androidx.gridlayout.widget.GridLayout
android:id="#+id/tabellaX"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="60dp">
<EditText
android:id="#+id/edit_dialog"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:id="#+id/button_X22"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:freezesText="true"
android:text=""
app:layout_column="2"
app:layout_row="2" />
<Button
android:id="#+id/button_X00"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:freezesText="true"
android:text=""
app:layout_column="0"
app:layout_row="0"
android:focusable="false"/>
<Button
android:id="#+id/button_X01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:freezesText="true"
android:text="" />
<Button
android:id="#+id/button_X12"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:freezesText="true"
android:text=""
app:layout_column="2"
app:layout_row="1" />
<Button
android:id="#+id/button_X02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:freezesText="true"
android:text=""
app:layout_column="2"
app:layout_row="0" />
<Button
android:id="#+id/button_X20"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:freezesText="true"
android:text=""
app:layout_column="0"
app:layout_row="2" />
<Button
android:id="#+id/button_X21"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:freezesText="true"
android:text="" />
<Button
android:id="#+id/button_X10"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:freezesText="true"
android:text=""
app:layout_column="0"
app:layout_row="1" />
<Button
android:id="#+id/button_X11"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:freezesText="true"
android:text=""
app:layout_column="1"
app:layout_row="1" />
</androidx.gridlayout.widget.GridLayout>
</LinearLayout>
So here is one possible solution.
First in your XML you can avoid using both Linear layouts since you are using a Constraint layout. So the XML looks as follow.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="#+id/text_view_p8"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="GRIGLIAMOD10"
android:textSize="30sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.gridlayout.widget.GridLayout
android:id="#+id/tabellaX"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="60dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/text_view_p8">
<Button
android:id="#+id/button_X00"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:freezesText="true"
android:text=""
app:layout_column="0"
app:layout_row="0" />
<Button
android:id="#+id/button_X01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:freezesText="true"
android:text=""
/>
<Button
android:id="#+id/button_X12"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:freezesText="true"
android:text=""
app:layout_column="2"
app:layout_row="1" />
<Button
android:id="#+id/button_X02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:freezesText="true"
android:text=""
app:layout_column="2"
app:layout_row="0" />
<Button
android:id="#+id/button_X20"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:freezesText="true"
android:text=""
app:layout_column="0"
app:layout_row="2" />
<Button
android:id="#+id/button_X21"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:freezesText="true"
android:text=""
/>
<Button
android:id="#+id/button_X22"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:freezesText="true"
android:text=""
app:layout_column="2"
app:layout_row="2" />
<Button
android:id="#+id/button_X10"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:freezesText="true"
android:text=""
app:layout_column="0"
app:layout_row="1" />
<Button
android:id="#+id/button_X11"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:freezesText="true"
android:text=""
app:layout_column="1"
app:layout_row="1" />
</androidx.gridlayout.widget.GridLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
I also changed the Java file and I left some comments in case you want a different behavior from your app.
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.util.ArrayList;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.gridlayout.widget.GridLayout;
public class MainActivity extends AppCompatActivity implements View.OnLongClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get all the buttons from the grid - be careful if you add another type of Touchable
ArrayList<View> gridButtons = ((GridLayout) findViewById(R.id.tabellaX)).getTouchables();
for (View v : gridButtons) {
((Button) v).setOnLongClickListener(this);
}
}
#Override
public boolean onLongClick(View v) {
// show the dialog ONLY if the button isn't set
if (((Button) v).getText().toString().isEmpty())
showDialog(v);
return true;
}
private void showDialog(final View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Input a number");
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_NUMBER);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// get only the first inserted number(i.e. input: 45; take only the 4)
((Button) v).setText(input.getText().toString().substring(0, 1));
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
}
EDIT
In the comment section below the answer you asked me if I can edit the behavior of the App.
If you click on the first button where there is the number, for example "4", this must be added to all the other buttons that have a number, if the second button has a number 3, this becomes 7. But if for example 5 to 6 is added this must not become 11 but 1 must be of module 10.
package hr.hello.dm.test;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.util.ArrayList;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.gridlayout.widget.GridLayout;
public class MainActivity extends AppCompatActivity implements View.OnLongClickListener, View.OnClickListener {
private ArrayList<View> gridButtons;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get all the buttons from the grid - be careful if you add another type of Touchable
gridButtons = ((GridLayout) findViewById(R.id.tabellaX)).getTouchables();
for (View v : gridButtons) {
((Button) v).setOnLongClickListener(this);
((Button) v).setOnClickListener(this);
}
}
#Override
public void onClick(View v) {
if(((Button) v).((Button) v).getText().toString().isEmpty())
return;
int value = Integer.parseInt(((Button) v).getText().toString());
for (View btn : gridButtons) {
if(v.getId() != btn.getId() && !((Button) btn).getText().toString().isEmpty()) {
int btnValue = Integer.parseInt(((Button) btn).getText().toString());
((Button) btn).setText(String.valueOf((value + btnValue)%10));
}
}
}
#Override
public boolean onLongClick(View v) {
if (((Button) v).getText().toString().isEmpty())
showDialog(v);
return true;
}
private void showDialog(final View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Input a number");
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_NUMBER);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
int value = Integer.parseInt(input.getText().toString());
((Button) v).setText(String.valueOf(value));
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
}
As far as i understand what you are trying to do, codes below may help you.
public class MainActivity extends AppCompatActivity{
Button[] buttons;
private final String TAG = this.getClass().getSimpleName();
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttons = new Button[9];
buttons[0] = (Button) findViewById(R.id.button_X00);
buttons[1] = (Button) findViewById(R.id.button_X10);
buttons[2] = (Button) findViewById(R.id.button_X20);
buttons[3] = (Button) findViewById(R.id.button_X01);
buttons[4] = (Button) findViewById(R.id.button_X11);
buttons[5] = (Button) findViewById(R.id.button_X21);
buttons[6] = (Button) findViewById(R.id.button_X02);
buttons[7] = (Button) findViewById(R.id.button_X12);
buttons[8] = (Button) findViewById(R.id.button_X22);
for (int a = 0; a<buttons.length;a++){
showDialog(buttons[a]);
}
}
private void showDialog(final Button btn) {
btn.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("input text");
View view = View.inflate(MainActivity.this,R.layout.dialog_activity, null);
builder.setView(view);
final EditText edit_dialog = view.findViewById(R.id.edit_dialog);
builder.setNegativeButton("cancel",null);
builder.setPositiveButton("confirm", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
try {
btn.setText(edit_dialog.getText().toString());
}catch (Exception e){
Log.e(TAG, e.getMessage() + " " );
}
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
return true;
}
});
}
}
activity_main:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.gridlayout.widget.GridLayout
android:id="#+id/tabellaX"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="60dp">
<Button
android:id="#+id/button_X22"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:freezesText="true"
app:layout_column="2"
app:layout_row="2" />
<Button
android:id="#+id/button_X00"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:freezesText="true"
app:layout_column="0"
app:layout_row="0"
android:focusable="false"/>
<Button
android:id="#+id/button_X01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:freezesText="true" />
<Button
android:id="#+id/button_X12"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:freezesText="true"
app:layout_column="2"
app:layout_row="1" />
<Button
android:id="#+id/button_X02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:freezesText="true"
app:layout_column="2"
app:layout_row="0" />
<Button
android:id="#+id/button_X20"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:freezesText="true"
app:layout_column="0"
app:layout_row="2" />
<Button
android:id="#+id/button_X21"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:freezesText="true"
app:layout_column="1"
app:layout_row="2"/>
<Button
android:id="#+id/button_X10"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:freezesText="true"
app:layout_column="0"
app:layout_row="1" />
<Button
android:id="#+id/button_X11"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:freezesText="true"
app:layout_column="1"
app:layout_row="1" />
</androidx.gridlayout.widget.GridLayout>
</LinearLayout>
and here is dialog_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/text_view_p8"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="center"
android:text="GRIGLIAMOD10"
android:textSize="30sp" />
<EditText
android:id="#+id/edit_dialog"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"/>
</LinearLayout>

What is a better way to structure my code here?

I'm a newbie trying to write an app which input/outputs a number between 1-10 after pressing a button. I'm hoping to have this code throw an exception when the input value is outside the 1-10 boundary.
Caused by: java.lang.reflect.InvocationTargetException
I believe it has to do with the way I put my rand() function inside the onClick() listener. Am I on the right track that it's just written very poorly?
Thanks very much if you can help.
Here is my code:
public Button button;
public TextView textView;
public EditText editText;
Random r;
public int max=0;
public int min=0;
public int temp=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button)findViewById(R.id.button);
editText=(EditText)findViewById(R.id.editText);
editText.setText("");
textView=(TextView) findViewById(R.id.output);
}
public void onClick(View view) {
rand(Integer.parseInt(editText.getText().toString()));
}
public void rand(int temp) throws IndexOutOfBoundsException{
temp = Integer.parseInt(editText.getText().toString());
if(temp >10 || temp<0){
throw new IndexOutOfBoundsException("out of bounds... between 1-10");
}
if(!editText.equals("")){
min = 10-temp;
max = r.nextInt(min + 1)+1;
}
String set = String.valueOf(max);
textView.setText(set);
}
Also, here is my XML
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimaryDark"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
</android.support.v7.widget.Toolbar>
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_row="1"
android:layout_column="0"
android:layout_columnSpan="0"
android:text="Enter a Number Between 1 and 10:"
android:textSize="30sp" />
<EditText
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_row="2"
android:layout_column="0"
android:ems="10"
android:inputType="number" />
<Button
android:id="#+id/button"
android:layout_width="369dp"
android:layout_height="wrap_content"
android:layout_row="3"
android:layout_column="0"
android:layout_columnSpan="2"
android:text="Button"
android:onClick="onClick"
android:textSize="30sp" />
<TextView
android:id="#+id/output"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_row="4"
android:layout_column="0"
android:text="output"
android:textSize="30sp" />
U have to put your function call into a try/catch block:
public void onClick(View view) {
try{
rand(Integer.parseInt(editText.getText().toString()));
}catch(IndexOutOfBoundsException e){
e.printStackTrace();
}

onButtonClick is never used in source code?

I am writing a simple app which is working fine but the issue I have is that I am using a password condition to trigger a button click if entered correctly.
The issue is that my source code is saying 'onButtonClick' is never used and when I manually press that button in the app, it suddenly force closes and crashes. Anyone know what I am doing wrong. I am extending Activity, at the start of the source code. Should I be extending AppCompatActivity?
public class Gvoice extends Activity implements OnClickListener{
ListView lv1;
static final int check = 1111;
Button b1;
Button b_home;
EditText a1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gvoice);
lv1 = (ListView)findViewById(R.id.LVGVoiceReturn);
b1 = (Button)findViewById(R.id.GVoice);
a1 = (EditText) findViewById(R.id.editTextHome);
b1.setOnClickListener(this);
//This now handles an automatic press of the bVoice button 1 second after the activity is opened
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
b1.callOnClick();
}
}, 1000);
}
public void onButtonClick(View v) {
if (v.getId() == R.id.BHome) {
String str = a1.getText().toString();
//Go to the relevant page if any part of the phrase or word entered in the 'EditText' field contains 'xxx' which is not case sensitive
if (str.toLowerCase().contains("home")) {
Intent userintent = new Intent(Gvoice.this, PocketSphinxActivity.class);
startActivity(userintent);
} else {
Toast.makeText(getApplicationContext(), "Incorrect Information", Toast.LENGTH_SHORT).show();
}
}
}
public void onClick(View v){
Intent i1 = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
i1.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
i1.putExtra(RecognizerIntent.EXTRA_PROMPT, "Please Repeat Again");
startActivityForResult(i1, check);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == check && resultCode == RESULT_OK){
ArrayList<String> results = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
lv1.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, results));
a1.setText((String) lv1.getItemAtPosition(0)); //Get the first phrase in the first row of list view
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
b_home.performClick();
}
}, 500); //Automatically click the 'Blogin' button after 500ms
}
super.onActivityResult(requestCode, resultCode, data);
}
}
Update: Below is the xml file. Please note that onButtonClick has been added to the xml file but still it force closes the app when the button is clicked using the condition statement:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ececec">
<ImageView
android:layout_width="100dip"
android:layout_height="100dip"
android:background="#drawable/patient_two"
android:id="#+id/pimage"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="85dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Patient Name: Joe Blogs"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Cause of Injury: Car crash"
android:id="#+id/textView2"
android:layout_below="#+id/pimage"
android:layout_centerHorizontal="true"
android:layout_marginTop="15dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Date of Birth:"
android:id="#+id/textView3"
android:layout_below="#+id/textView2"
android:layout_toStartOf="#+id/textView2"
android:layout_marginTop="25dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Gender:"
android:id="#+id/textView4"
android:layout_below="#+id/textView3"
android:layout_alignStart="#+id/textView3" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Occupation:"
android:id="#+id/textView5"
android:layout_below="#+id/textView4"
android:layout_alignStart="#+id/textView4" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Address:"
android:id="#+id/textView6"
android:layout_below="#+id/textView5"
android:layout_alignStart="#+id/textView5" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medical History"
android:id="#+id/textView7"
android:layout_marginTop="15dp"
android:layout_below="#+id/textView6"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Heart attack"
android:id="#+id/textView8"
android:layout_marginTop="15dp"
android:layout_below="#+id/textView7"
android:layout_alignStart="#+id/textView6" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Arthritis"
android:id="#+id/textView9"
android:layout_below="#+id/textView8"
android:layout_alignStart="#+id/textView8" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Tests Completed"
android:id="#+id/textView10"
android:layout_marginTop="15dp"
android:layout_below="#+id/textView9"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="X-Ray"
android:id="#+id/textView11"
android:layout_below="#+id/textView10"
android:layout_alignStart="#+id/textView9"
android:layout_marginTop="15dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="..."
android:id="#+id/textView12"
android:layout_below="#+id/textView11"
android:layout_alignStart="#+id/textView11" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Tests Due"
android:id="#+id/textView14"
android:layout_below="#+id/textView12"
android:layout_centerHorizontal="true"
android:layout_marginTop="15dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="..."
android:id="#+id/textView15"
android:layout_below="#+id/textView14"
android:layout_alignStart="#+id/textView12"
android:layout_marginTop="15dp" />
<ListView
android:layout_width="150dp"
android:layout_height="50dp"
android:id="#+id/lvVoiceReturn1"
android:textColor="#color/white"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter"
android:id="#+id/Blogin1"
android:onClick="onButtonClick"
android:layout_alignParentBottom="true"
android:layout_toStartOf="#+id/bVoice1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Speak"
android:id="#+id/bVoice1"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/TFusername1"
android:layout_alignParentStart="true"
android:hint="Speech to Text" />
You can 4 method handle button click :
method 1 :
public class Mtest extends Activity {
Button b1;
public void onCreate(Bundle savedInstanceState) {
...
Button b1 = (Button) findViewById(R.id.b1);
b1.setOnClickListener(myhandler1);
...
}
View.OnClickListener myhandler1 = new View.OnClickListener() {
public void onClick(View v) {
// it was the 1st button
}
};
}
method 2 :
class MTest extends Activity implements OnClickListener {
public void onCreate(Bundle savedInstanceState) {
...
Button b1 = (Button) findViewById(R.id.b1);
b1.setOnClickListener(this);
...
}
#Override
public void onClick(View v) {
}
}
method 3 in xml and android:onClick="HandleClick" :
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="HandleClick" />
public class MTest extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void HandleClick(View view) {
}
}
method 4 :
public class MTest extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b1 = (Button) findViewById(R.id.b1);
b1.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
// do stuff
}
});
}
}
The issue was to do with initially not adding onButtonClick in the xml file and also not correctly assigning the button labels in the java file.
lv1 = (ListView)findViewById(R.id.LVGVoiceReturn);
b1 = (Button)findViewById(R.id.GVoice);
a1 = (EditText) findViewById(R.id.editTextHome);
c1 = (Button)findViewById(R.id.BHome);
b1.setOnClickListener(this);
The following corrects the issues and everything is working fine now. Hope this can help others in the future

Categories

Resources