I am trying to get radio button value on click of a button but it is showing red line error below this line:
I want to know why this error is showing as I am unable to understand.
radioSexButton = (RadioButton)findViewById(selectedId);
inconvertible types,cannot cast android.view.view to RadioButton
Below is my code:
XML code:
<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=".RadioButton"
android:padding="20dp">
<RadioGroup
android:id="#+id/radioSex"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="#+id/radioMale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Male"
android:checked="true" />
<RadioButton
android:id="#+id/radioFemale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female" />
</RadioGroup>
<Button
android:id="#+id/btnDisplay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Display" />
JAVA code:
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.Toast;
public class RadioButton extends AppCompatActivity {
private RadioGroup radioSexGroup;
private RadioButton radioSexButton;
private Button btnDisplay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_radio_button);
radioSexGroup = findViewById(R.id.radioSex);
btnDisplay = findViewById(R.id.btnDisplay);
btnDisplay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int selectedId = radioSexGroup.getCheckedRadioButtonId();
radioSexButton = (RadioButton)findViewById(selectedId);
// find the radiobutton by returned id
Toast.makeText(getApplicationContext(),
radioSexButton.getText(), Toast.LENGTH_SHORT).show();
}
});
}
}
Someone please let me know how to resolve this issue any help would be appreciated.
THANKS
According to the exception message you're getting it appears to be an issue with casting the view returned by findViewById(int). Try the following steps below;
Rename your activity so that it's name doesn't clash with the view's type
Don't cast the return value of findViewById(int). It will automatically do that for you based on the type of your variable.
Make sure you have the correct imports.
After taking the above steps the resulting activity should be like below
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton; // this is the important part
import android.widget.RadioGroup;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
// activity name changed!
public class RadioButtonActivity extends AppCompatActivity {
private RadioGroup radioSexGroup;
private RadioButton radioSexButton;
private Button btnDisplay;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
radioSexGroup = findViewById(R.id.radioSex);
btnDisplay = findViewById(R.id.btnDisplay);
btnDisplay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int selectedId = radioSexGroup.getCheckedRadioButtonId();
radioSexButton = findViewById(selectedId);
// find the radiobutton by returned id
Toast.makeText(getApplicationContext(),
radioSexButton.getText(), Toast.LENGTH_SHORT).show();
}
});
}
}
You're encountering the issue because you're attempting to cast the return value of findViewById(int) into "RadioButton" which in your code is referring to the activity instead of android.widget.RadioButton
change your code to below code
private View radioSexButton; //make View
int radioButtonID = radioSexGroup.getCheckedRadioButtonId();
radioSexButton = radioSexGroup.findViewById(radioButtonID);
Related
I am using this code to get the id of the button which is clicked and then use the id to get the text and hint of the same button
I don't know why but maybe this code this crashing the app after I use getID() method.
I am using Relative Layout.
The Java code
package com.example.firstapp;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity{
public AlertDialog.Builder dialogBuilder;
public AlertDialog dialog;
public EditText Name,Password;
public Button Save,Cancel,temp,ok,x;
public String file_location = "Passwords.txt";
public String name_x,pass_y;
public LinearLayout mylayout = null;
public RelativeLayout rl = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void View_Password(Button x){
ok = (Button) findViewById(R.id.button6);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
};
public void NewPassword(){
dialogBuilder = new AlertDialog.Builder(this);
final View NewPassSaveView = getLayoutInflater().inflate(R.layout.newpasspopup, null);
Name = (EditText) NewPassSaveView.findViewById(R.id.editTextTextPersonName);
Password = (EditText) NewPassSaveView.findViewById(R.id.editTextTextPersonName2);
Save = (Button) NewPassSaveView.findViewById(R.id.button4);
Cancel = (Button) NewPassSaveView.findViewById(R.id.button);
dialogBuilder.setView(NewPassSaveView);
dialog = dialogBuilder.create();
dialog.show();
Save.setOnClickListener(new View.OnClickListener() {
#SuppressLint("ResourceType")
#Override
public void onClick(View view) {
if (TextUtils.isEmpty(Name.getText().toString())) {
Name.setError("This Field is compulsory");
return;
} else if (TextUtils.isEmpty(Password.getText().toString())) {
Password.setError("This Field is compulsory");
return;
}
rl = (RelativeLayout) findViewById(R.id.layout2);
Toast.makeText(getApplicationContext(), "Password Saving...", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "Password Saved", Toast.LENGTH_SHORT).show();
Button temp = new Button(MainActivity.this);
temp.setLayoutParams(new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
));
rl.addView(temp);
temp.setText(Name.getText().toString());
temp.setHint(Password.getText().toString());
temp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int btn_id = v.getId();
btn2string(btn_id);
}
});
dialog.dismiss();
}
});
Cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
}
public void AddNew(View view) {
NewPassword();
}
public void btn2string(int x){
Button btn = findViewById(x);
name_x = btn.getText().toString();
pass_y = btn.getHint().toString();
See_Password(name_x,pass_y);
}
public void See_Password(String name,String pass){
Toast.makeText(getApplicationContext(), "Name: "+name+"\n"+"Password: "+pass, Toast.LENGTH_SHORT).show();
}
}
//The XML
<?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:id="#+id/heading"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="#+id/textView4"
android:layout_width="319dp"
android:layout_height="50dp"
android:text="Password Manager"
android:textSize="34sp"
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.051" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="28dp"
android:layout_marginRight="28dp"
android:onClick="AddNew"
android:text="Add new"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView4"
app:layout_constraintVertical_bias="0.973" />
<RelativeLayout
android:id="#+id/layout2"
android:layout_width="366dp"
android:layout_height="541dp"
android:layout_marginTop="28dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.488"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView4"
app:layout_constraintVertical_bias="0.0"/>
</androidx.constraintlayout.widget.ConstraintLayout>
Please tell if there is any other way to do this or tell the mistakes in the above code so that I can get the hint and text of that button which is clicked...
Thank You.
Inside,
NewPassword()
method just change the following code.
public void NewPassword(){
......
save.setOnClickListener(...){
........
temp.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
int btn_id = v.getId(); // remove this line.
btn2String(temp); //directly pass temp i.e. Button you created.
}
});
dialog.dismiss();
}
});
..........
}
And, pass Button type as a parameter in btn2String() method. as below:
public void btn2String(Button x){
Button btn = findViewById(x); // remove this line of code.
name_x = x.getText().toString();
pass_y = x.getHint().toString();
See_Password(name_x, pass_y);
}
My app doesn't response when i type
Android app project that has two (2) text fields and one (1) button. The button will
compare the input from the text fields and display a response (SAME if values are the same
and NOT THE SAME if they are not) if it is clicked. You may need to create a new activity
for this.
package com.demesaict203.fieldchecker;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button checkbtn = (Button)findViewById(R.id.checkBtn);
checkbtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
EditText firstttextEditText = (EditText) findViewById(R.id.firsttextEditText);
EditText secondtextEditText = (EditText) findViewById(R.id.secondtextEditText);
if (firstttextEditText.equals(secondtextEditText)){
Intent sameTextIntent = new Intent(getApplicationContext(),SameText.class);
startActivity(sameTextIntent);
}
else{
Intent notsameTextIntent = new Intent(getApplicationContext(),NotTheSame.class);
startActivity(notsameTextIntent);
}
}
});
}
}
Here is my XML code:
<?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:id="#+id/checkButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="#+id/firsttextEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/enter_word"
android:inputType="textPersonName"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:autofillHints="" tools:targetApi="o" />
<EditText
android:id="#+id/secondtextEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/enter_word"
android:importantForAutofill="no"
android:inputType="textPersonName"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/firsttextEditText" />
<Button
android:id="#+id/checkBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/check"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.2"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/secondtextEditText" />
</androidx.constraintlayout.widget.ConstraintLayout>
first of all, you can't compare two EditText references together to get the result of text values equality.
you can get the text wrote in the editText using getText() method
then start to compare both strings values.
also, I suggest declaring EditText out of scope setOnClickListener so that not declare new instances every time the user click button.
so your final java code can be like :
package com.demesaict203.fieldchecker;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText firstttextEditText = (EditText) findViewById(R.id.firsttextEditText);
EditText secondtextEditText = (EditText) findViewById(R.id.secondtextEditText);
Button checkbtn = (Button) findViewById(R.id.checkBtn);
checkbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String firstValue = firstttextEditText.getText().toString();
String secondValue = secondtextEditText.getText().toString();
if (firstValue.equals(secondValue)) {
Intent sameTextIntent = new Intent(getApplicationContext(), SameText.class);
startActivity(sameTextIntent);
} else {
Intent notsameTextIntent = new Intent(getApplicationContext(), NotTheSame.class);
startActivity(notsameTextIntent);
}
}
});
}
}
I suggest you learn more about EditText from here
you are comparing the EditText, not the text inside the edit text. maybe change your codes to something like this.
String firstttextEditText = findViewById(R.id.firsttextEditText)).getText().toString();
String secondtextEditText = findViewById(R.id.secondtextEditText).getText().toString();
if (firstttextEditText.equals(secondtextEditText)){
Intent sameTextIntent = new Intent(getApplicationContext(),SameText.class);
startActivity(sameTextIntent);
}
else{
Intent notsameTextIntent = new Intent(getApplicationContext(),NotTheSame.class);
startActivity(notsameTextIntent);
}
I am new to android programming and have ran into a problem. I am trying to create a voting app where when a user opens up the application and the MainActivity is shown, from here they press a button to go into the second Screen (Screen2) which shows images of people and their names as buttons. When a persons name (in a button on Screen2) is pressed , a text field shows the number of times the button is pressed in an another activity (Screen4) . The problem here is that when i try to show this (Screen4), the app crashes. I am quite new to this so if you didn't understand my issue or need more information please let me know. Any help is appreciated. Thank you.
EDIT : After some help I used Intent to try send the data across but now when when the button in screen2 is pressed the app refreshes and then takes me back to the mainActivity and when this process is tried again the app crashes.
This is the new Screen2 :
package com.example.myapplication1;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class Screen2 extends AppCompatActivity {
TextView showValue;
int counter = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen2);
showValue = findViewById(R.id.VoteCountAnnie);//VoteCountAnnie is the On click for the Textview in a different activity.
}
public void AnCount(View v) {
//increase the count
counter++;
showValue.setText(Integer.toString(counter));
}
public void ButtonToGoToTheOtherActivity(View v) {
Intent intent = new Intent(this, Screen4.class);
intent.putExtra("valueOfCounter", counter); //the code for sending data to the other activity.
startActivity(intent);
}
}
This is the XML for screen 2 :
<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".Screen2">
<Button
android:id="#+id/AnnieBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginLeft="32dp"
android:text="#string/annie_liou"
android:onClick="AnCount"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/imageView5"
/>
This is my Screen4:
package com.example.myapplication1;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Screen4 extends AppCompatActivity {
private Button Button3;
int counter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen4);
Button3 = (Button) findViewById(R.id.Button3);
Button3.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) { openActivity4();
}
}
);
counter = getIntent().getIntExtra("valueOfCounter", 0); // 0 is default value
}
public void openActivity4() {
Intent intent = new Intent(Screen4.this, MainActivity.class);
startActivity(intent);
}
}
Here is the XML for screen4:
<?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:id="#+id/MainScreen"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Screen4">
<TextView
android:id="#+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="193dp"
android:layout_marginLeft="193dp"
android:layout_marginEnd="109dp"
android:layout_marginRight="109dp"
android:layout_marginBottom="660dp"
android:text="This is 4th screen"
android:textSize="32sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.664"
app:layout_constraintStart_toStartOf="parent" />
<Button
android:id="#+id/Button3" // return to main screen
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="532dp"
android:text="Return"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView5" />
<TextView
android:id="#+id/VoteCountAnnie" // textview where i want the increment to show
android:layout_width="121dp"
android:gravity="center"
android:layout_height="52dp"
android:layout_marginStart="116dp"
android:layout_marginLeft="116dp"
android:layout_marginTop="82dp"
android:layout_marginEnd="174dp"
android:layout_marginRight="174dp"
android:text="0"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView5" />
</androidx.constraintlayout.widget.ConstraintLayout>
This is my main Activity Screen (not used for the clicking but if there is something wrong in this that could affect the other Screens please let me know) :
package com.example.myapplication1;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private Button button;
private Button button2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openActivity2();
}
});
button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
openActivity3();
}
}
);
}
public void openActivity2() {
Intent intent = new Intent(this, Screen2.class);
startActivity(intent);
}
public void openActivity3() {
Intent intent = new Intent(this, Screen3.class);
startActivity(intent);
}
}
Here is the XML for screen 4:
This works same using intent .
Main Class :
package com.example.cameraone;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
public static String EXTRA_VOTE_KEY = "com.example.cameraone.EXTRA_VOTE_KEY";
private Button counter,show;
private int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState != null){
count = savedInstanceState.getInt(EXTRA_VOTE_KEY);
}
counter = findViewById(R.id.bt_counter);
show = findViewById(R.id.bt_show);
counter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
count++;
}
});
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
go();
}
});
/* Intent intent = new Intent(this,DisplayCount.class);
//intent.putExtras(intent);
startActivity(intent,bundle);*/
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(EXTRA_VOTE_KEY,count);
}
public void go(){
Intent intent = new Intent(this,DisplayCount.class);
intent.putExtra(EXTRA_VOTE_KEY,count);
startActivity(intent);
}
}
Activity of Main Class :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
tools:context=".MainActivity">
<Button
android:id="#+id/bt_counter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:text="PressMe"
/>
<Button
android:id="#+id/bt_show"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/bt_counter"
android:text="Done"
/>
</RelativeLayout
Display Class :
package com.example.cameraone;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.Button;
import android.widget.TextView;
import org.w3c.dom.Text;
public class DisplayCount extends AppCompatActivity{
private TextView textView;
private int count;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_count_activity);
textView = findViewById(R.id.tv_vote_count);
Intent intent = getIntent();
count = intent.getIntExtra(MainActivity.EXTRA_VOTE_KEY,0);
textView.setText(Integer.toString(count));
}
}
Activity of display class :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_gravity="center">
<TextView
android:id="#+id/tv_vote_count"
android:layout_width="wrap_content"
android:inputType="number"
android:layout_height="wrap_content"
android:textStyle="bold"
android:maxLength="10"/>
</RelativeLayout>
Manifest :
include following in your manifest file :
<activity android: name =".DisplayCount"></activity>
add following to manifest :
// Main Activity //
- List item
package com.example.cameraone;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
public static String EXTRA_VOTE_KEY = "com.example.cameraone.EXTRA_VOTE_KEY";
private Button counter,show;
private int count = 0;
#Override
protected void onCreate(#Nullable final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
counter = findViewById(R.id.bt_counter);
show = findViewById(R.id.bt_show);
counter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
count++;
}
});
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
go();
}
});
}
public void go(){
DisplayCount.setVoteCount(count);
Intent intent = new Intent(this, DisplayCount.class);
startActivity(intent);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(EXTRA_VOTE_KEY,count);
}
}
/** Class to display: **/
- List item
package com.example.cameraone;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.Button;
import android.widget.TextView;
import org.w3c.dom.Text;
public class DisplayCount extends AppCompatActivity{
private TextView textView ;
private static int count ;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_count_activity);
textView = findViewById(R.id.tv_vote_count);
textView.setText(Integer.toString(count));`enter code here`
}
public static void setVoteCount(int c){
count = c;
}
}
/***** Activity files *****/
- List item
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_gravity="center">
<TextView
android:id="#+id/tv_vote_count"
android:layout_width="wrap_content"
android:inputType="number"
android:layout_height="wrap_content"
android:textStyle="bold"
android:maxLength="10"/>
</RelativeLayout>
/**** Activity That display's ****/
-List item
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
tools:context=".MainActivity">
<Button
android:id="#+id/bt_counter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:text="PressMe"
/>
<Button
android:id="#+id/bt_show"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/bt_counter"
android:text="Done"
/>
</RelativeLayout>
As Mike M. said you are using id of a textview which is in a different activity. In android we cannot access ids of views in a different activity. We can only access ids of view in the same activity in which we are.
So that is for the error you are getting.
For accessing Data from another activity you can pass the data like this:
public class Screen2 extends AppCompatActivity {
int counter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen1);
showValue = (TextView) findViewById(R.id.VoteCountAnnie);//VoteCountAnnie is the Id for the Textview in a different activity.
}
public void AnnieCountInc (View view) {
//increase the count
counter++;
showValue.setText(Integer.toString(counter));
}
//make another button with a method like
public void ButtonToGoToTheOtherActivity(View view){
Intent intent =new Intent(this,Screen4.class);
intent.putExtra("valueOfCounter",counter); //the code for sending data to the other activity.
startActivity(intent);
}
Then in your Screen4 activity you can get the value of "counter" in the onCreate method by:
counter = getIntent().getIntExtra("valueOfCounter",0); // 0 is default value
This is one method.
You can also use a static variable to pass on data easily by defining your counter varaible as
public static int counter;
Then you can access it directly and it will show you the value.
I have a table row which contains textviews
I am trying to use intents to click on the text view to move to the next activity but when I click on the text view I get the following error
java.lang.IllegalStateException: Could not find method onClick(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatTextView with id 'tv_msisdn'
at android.view.View$DeclaredOnClickListener.resolveMethod(View.java:4479)
at android.view.View$DeclaredOnClickListener.onClick(View.java:4443)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
Code Hear
package com.tela.mobile.home;
import android.content.Intent;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.view.View.OnClickListener;
import com.tela.mobile.R;
public class DeviceAlertDetail extends Activity implements OnClickListener
{
private TextView tv_number;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tablerow_overage);
TextView textView = (TextView)findViewById(R.id.tv_number);
tv_number.setOnClickListener(this);
}
public void onClick(View view)
{
Intent intent = new Intent(this, SearchResultsActivity.class);
this.startActivity(intent);
}
}
and I am setting onClick for the textView in my layout file as follows
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_column="1"
android:layout_weight="1"
android:padding="1dp"
android:text="number"
android:id="#+id/tv_number"
android:textSize="12sp"
android:maxLines="1"
android:onClick="onClick"
android:clickable="true"
android:ellipsize="end"
/>
You don't have to implement OnClickListener when you use android:onClick="onClick" just let public void onClick(View view) as it and remove implements OnClickListener from the activity
Your code gonna be like
package com.tela.mobile.home;
import android.content.Intent;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.view.View.OnClickListener;
import com.tela.mobile.R;
public class DeviceAlertDetail extends Activity
{
private TextView tv_number;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tablerow_overage);
}
public void onClick(View view)
{
Intent intent = new Intent(this, SearchResultsActivity.class);
this.startActivity(intent);
}
}
and
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1"
android:layout_weight="1"
android:padding="1dp"
android:text="number"
android:id="#+id/tv_number"
android:textSize="12sp"
android:maxLines="1"
android:onClick="onClick"
android:clickable="true"
android:ellipsize="end"
/>
I think you didn't initialize correctly tv_number.
You have created an unused local variable TextView textView, which may have confused you in thinking that you initialized tv_number.
Please replace
TextView textView = (TextView)findViewById(R.id.tv_number);
With
tv_number = (TextView)findViewById(R.id.tv_number);
I think you are misplace reference name.
Just change
tv_number.setOnClickListener(this);
with
textView.setOnClickListener(this);
Your Code Become
//Activity
package com.tela.mobile.home;
import android.content.Intent;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.view.View.OnClickListener;
import com.tela.mobile.R;
public class DeviceAlertDetail extends Activity implements OnClickListener
{
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tablerow_overage);
textView = (TextView)findViewById(R.id.tv_number);
textView.setOnClickListener(this);
}
public void onClick(View view)
{
Toast.makeText(this,"Code Working Fine Now Remove Comments Of Below",Toast.LENGTH_LONG).show();
//Intent intent = new Intent(this, SearchResultsActivity.class);
//this.startActivity(intent);
}
}
//.xml becomes
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1"
android:layout_weight="1"
android:padding="1dp"
android:text="number"
android:id="#+id/tv_number"
android:textSize="12sp"
android:maxLines="1"
android:clickable="true"
android:ellipsize="end"
/>
I'm learning to use the external class. This project is just an example. I have a class that extends Activity and in this class I want to access my Login button. And the Login Button will run the external class that implements OnClickListener in OnClickListenerLogin().
In OnClickListenerLogin I want to get EditText value in Login.xml. But whenever I call it, the value returns "".
What's missing from my code and what is the right code for my OnClickListenerLogin so I can get the EditText value in Login.xml?
Login.xml
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true"
tools:context="com.example.phonekiosk.LoginActivity" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ffffff">
<!-- Login Form -->
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dip">
<!-- Email Label -->
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#372c24"
android:text="Username"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
android:layout_marginBottom="20dip"
android:singleLine="true"
android:id="#+id/txtUsername"/>
<!-- Password Label -->
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#372c24"
android:text="Password"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
android:singleLine="true"
android:password="true"
android:id="#+id/txtPassword"/>
<!-- Login Button -->
<Button
android:id="#+id/btnLogin"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dip"
android:text="Login" />
</LinearLayout>
<!-- Login Form Ends -->
</RelativeLayout>
</ScrollView>
PhoneKiosk.java
package com.example.phonekiosk;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class LoginActivity extends Activity {
Button btnLogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new OnClickListenerLogin());
}
}
OnClickListenerLogin.java
package com.example.phonekiosk;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebView.FindListener;
import android.widget.EditText;
import android.widget.Toast;
public class OnClickListenerLogin implements OnClickListener {
#Override
public void onClick(View view) {
final Context context = view.getContext();
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View formLogin = inflater.inflate(R.layout.login, null);
final EditText txtUsername = (EditText) formLogin.findViewById(R.id.txtUsername);
final EditText txtPassword = (EditText) formLogin.findViewById(R.id.txtPassword);
String username = txtUsername.getText().toString();
String password = txtPassword.getText().toString();
Log.d("test", username + "-" + password);
}
}
You are not using the same view as that created by LoginActivity.
Your code that inflates the view in onClick need to be removed.
You can pass the reference to EditText of user name & password to your OnClickListenerLogin by implementing a constructor for it.
public class OnClickListenerLogin implements OnClickListener {
private EditText txtUsername;
private EditText txtPassword;
public OnClickListenerLogin (EditText userEditText, EditText passwordEditText) {
this.txtUsername = userEditText;
this.txtPassword = passwordEditText;
}
#Override
public void onClick(View view) {
String username = txtUsername.getText().toString();
String password = txtPassword.getText().toString();
Log.d("test", username + "-" + password);
}
}
In the login activity, you can do following
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(
new OnClickListenerLogin(
(EditText) findViewById(R.id.txtUsername),
(EditText) findViewById(R.id.txtPassword));
}
Disclaimer: I have entered the code directly here, not checked for compilation issue due to typo. I hope you get the essence of the solution
no need of external class here
you can simply set onClickListener to your login button and perfrom your action in onClick method.
public class LoginActivity extends Activity {
Button btnLogin;
EditText txtUsername,txtPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
txtUsername = (EditText) findViewById(R.id.txtUsername);
txtPassword = (EditText) findViewById(R.id.txtPassword);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
String username = txtUsername.getText().toString();
String password = txtPassword.getText().toString();
// your action here
}
});
}
}
One solution would be to simple make the onClickListener a inner class of your Login Class
public class LoginActivity extends Activity {
Button btnLogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
............
}
//inner class
class OnClickListenerLogin implements OnClickListener {
.........
}
}//Login class ends
Inner classes exist primarily to solve these kind of problems , try reading about them .
this is very simple so you should proceed like below for getting the value from edittext.
public class LoginActivity extends Activity implements OnClickListener{
Button btnLogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
final EditText txtUsername = (EditText) formLogin.findViewById(R.id.txtUsername);
final EditText txtPassword = (EditText) formLogin.findViewById(R.id.txtPassword)
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new OnClickListenerLogin());
}
public click(View view)
{
String username = txtUsername.getText().toString();
String password = txtPassword.getText().toString();
Log.d("test", username + "-" + password);
}
}