Textview causing java.lang.ClassCastException: android.widget.TextView - android

I have three textviews and applied clickevent on them, but when i click on any of them the they cause Forceclose error in application. i have also tried changing ids textviews and then clean project and ran the project still that error is not removed.
My XML code is
for one textview
<LinearLayout
android:id="#+id/LL_fb"
android:layout_width="180px"
android:layout_height="27px"
android:layout_above="#+id/txt_msg_regs"
android:layout_alignLeft="#+id/LL_signup"
android:layout_marginBottom="25dp"
android:background="#drawable/facebook" >
<TextView
android:id="#+id/btn_txt_fb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Connect with facebook"
android:layout_gravity="center_vertical"
android:layout_marginLeft="23dp"
android:layout_marginTop="1dp"
android:clickable="true"
android:textColor="#FFFFFF" />
</LinearLayout>
for second textview
<LinearLayout
android:id="#+id/LL_signup"
android:layout_width="180px"
android:layout_height="29px"
android:layout_above="#+id/textView1"
android:layout_alignLeft="#+id/LL_login"
android:background="#drawable/lmyic_signup">
<TextView
android:id="#+id/btn_txt_sinup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="signup with email"
android:layout_gravity="center_vertical"
android:layout_marginLeft="25dp"
android:layout_marginTop="1dp"
android:clickable="true"
android:textColor="#FFFFFF" />
</LinearLayout>
for third one
<LinearLayout
android:id="#+id/LL_login"
android:layout_width="180px"
android:layout_height="29px"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="69dp"
android:background="#drawable/lmyic_login">
<TextView
android:id="#+id/btn_txt_login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Log in"
android:layout_gravity="center_vertical"
android:layout_marginLeft="70dp"
android:layout_marginTop="1dp"
android:textColor="#FFFFFF"
android:clickable="true"/>
</LinearLayout>
this is my android code. This class name in intent are also correct and i verified them.
TextView img_login;
img_login = (TextView)findViewById(R.id.btn_txt_login);
img_login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId() == img_login.getId())
{
Intent i_lin = new Intent(LockmeifyoucanActivity.this,lmiyc_login.class);
startActivity(i_lin);
}
}
});
Please Tell me what is wrong with this. If logcat is needed then ask me for it....

Please post the complete XMl so that we can view the btn_txt_login in that.
It looks it is button because "findViewById(R.id.btn_txt_login);" would return null if this "btn_txt_login" id is not in xml.

you have some problem with textview in lmiyc_login activity.in lmiyc_login corrent line number 46 which maybe:
TextView txtview;
txtview = (TextView)yourlayout.findViewById(R.id.txtviewid);

findViewById(R.id.btn_txt_login);
Is this really a TextView or do you have a Button in your layout as well? I think you're trying to cast a Button to a TextView

Wrong resource ID...
img_login = (TextView)findViewById(R.id.btn_txt_login);
according to your XML should be
img_login = (TextView)findViewById(R.id.txt_login);
etc..

change ur code with this
TextView img_login;
img_login = (TextView)findViewById(R.id.txt_login);
img_login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId().equals(img_login.getId()))
{
Intent i_lin = new Intent(LockmeifyoucanActivity.this,lmiyc_login.class);
startActivity(i_lin);
}
}
});

To resolve this error quickly, set one break point at line:
View view = findViewById(R.id.btn_txt_login);
Then, see on locals tab which component is, looking at gen/R.java.

these are lines from 42-48
setContentView(R.layout.lmyic_login_page);
txtBack = (TextView)findViewById(R.id.ImgViewTxtBack); txtBack.setTypeface(null,Typeface.BOLD);
iv_login = (ImageView)findViewById(R.id.Txtlogin);
iv_login.setOnClickListener(this);
iv_sign_up = (ImageView)findViewById(R.id.TxtSignup);
I think problem is with iv_login = (ImageView)findViewById(R.id.Txtlogin); – Dheeresh Singh 1 min ago edit
because this is 46 line and it should be textview and you are castin it in Imageview – Dheeresh Singh just now edit

if you have duplicate resource Id, that will throw ClasscastException. So make sure you don't have duplicate element id throughout the whole project.

Related

When the button is pressed the app is crashing

I am trying to run an app and when I try to tap the button the app crashes when it is supposed to save data for backup
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.back4app.userregistrationexample, PID: 31963
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.AppCompatButton with id 'btn_addbalance'
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:423)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:380)
at android.view.View.performClick(View.java:6329)
at android.view.View$PerformClick.run(View.java:25002)
at android.os.Handler.handleCallback(Handler.java:809)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:166)
at android.app.ActivityThread.main(ActivityThread.java:7555)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:469)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:963)
I/Process: Sending signal. PID: 31963 SIG: 9
Application terminated.
Here in the balance I only put the code that I think is needed but if the whole class is needed I will edit it too
Balance
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.app_bar_balance);
Parse.initialize(new Parse.Configuration.Builder(this)
.applicationId("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
.clientKey("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
.server("https://parseapi.back4app.com/").build()
);
LiveQueryClient.init("wss://" + "aaaa.back4app.io", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", true); // Example: 'wss://livequerytutorial.back4app.io'
LiveQueryClient.connect();
Balance = (EditText) findViewById(R.id.txt_editbalance);
final Button addbalance = findViewById(R.id.btn_addbalance);
addbalance.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Validating the log in data
boolean validationError = false;
StringBuilder validationErrorMessage = new StringBuilder("Please, insert ");
if (isEmpty(Balance)) {
validationError = true;
validationErrorMessage.append("an balance");
}
validationErrorMessage.append(".");
if (validationError) {
Toast.makeText(Balance.this, validationErrorMessage.toString(), Toast.LENGTH_LONG).show();
return;
}
//Setting up a progress dialog
final ProgressDialog dlg = new ProgressDialog(Balance.this);
dlg.setTitle("Please, wait a moment.");
dlg.setMessage("Adding Load...");
dlg.show();
ParseUser balance = new ParseUser();
balance.setUsername(Balance.getText().toString());
balance.signUpInBackground(new SignUpCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
dlg.dismiss();
} else {
dlg.dismiss();
ParseUser.logOut();
Toast.makeText(Balance.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
});
}
I tried to change the names switching it back and forth hoping that it might fix the problem
app bar balance
<?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">
<TextView
android:id="#+id/txt_currentbal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="59dp"
android:text="Current Balance" />
<TextView
android:id="#+id/txt_balance"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="96dp"
android:text="android:id" />
<TextView
android:id="#+id/txt_addbal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="185dp"
android:text="Add Balance" />
<EditText
android:id="#+id/txt_editbalance"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="230dp"
android:ems="10"
android:hint="Add Balance"
android:inputType="number" />
<Button
android:id="#+id/btn_addbalance"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="177dp"
android:onClick="onclick"
android:text="Add Balance" />
</RelativeLayout>
Now I removed the android:onClick="onclick" and now it looks like this but when I run it again on my phone now it doesn't do anything and the run doesn't even respond when the button is pressed
You already set ClickListener from your from your code. So button onClick attribute not needed.
Just remove this line from the Button.
android:onClick="onclick"
It will look like this
<Button
android:id="#+id/btn_addbalance"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="177dp"
android:text="Add Balance" />
This will solve your problem.
In your XML you use a button from the support library (widget.AppCompatButton), but in your code you're trying to cast it to a regular Button. Either use the regular Button in your XML code, or use the AppCompatButton in the Java code.
Seeing that you are using the support library (you're using the AppCompatActivity), I'd advice you to change 'Button' to 'AppCompatButton' in your Java code.
put onclick() method in the button view of your xml
If you want to use in XML onClick then use like this :
<Button
android:id="#+id/btn_addbalance"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="177dp"
android:onClick="onClick"
android:text="Add Balance" />
you have entered in wrong format
do this : "onClick"
instead of : "onclick"
you can check in logcats it's shows also same thing in it, So change it :
Could not find method onclick(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'btn_addbalance'
by the way there is no need to add attribute in xml if you are doing in java

Android: Unable to Prevent buttons from increasing size and overlapping with other buttons

I am new to Android Programming, what I am trying to do in this Android Application is to create a xml page filled with buttons.
When I click the button, the button would change to light green color and when I click it again, it would change to light grey
The error: I am getting is when I click the button, it increases in size and overlaps with the other buttons, please help me out here, it is not user friendly in this case
attached below is the code:
lockerbooking.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="#+id/sisButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="16dp"
android:layout_marginTop="28dp"
android:text="#string/sis"
/>
<Button
android:id="#+id/solButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/soeButton"
android:layout_alignBottom="#+id/soeButton"
android:layout_alignParentRight="true"
android:text="#string/sol" />
<Button
android:id="#+id/soeButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/sisButton"
android:layout_alignBottom="#+id/sisButton"
android:layout_centerHorizontal="true"
android:text="#string/soe" />
</RelativeLayout>
Code:
makeBooking.java
public class makeBooking extends Activity {
Button sisButton;
Button solButton;
Button soeButton;
Button sobButton;
super.onCreate(savedInstanceState);
// Get the message from the intent
setContentView(R.layout.lockerbookpage);
Intent intent = getIntent();
// Initialize TextViews
sisButton = (Button) findViewById(R.id.sisButton);
solButton = (Button) findViewById(R.id.solButton);
soeButton = (Button) findViewById(R.id.soeButton);
sobButton = (Button) findViewById(R.id.sobButton);
}
public OnClickListener solButtonListener = new OnClickListener(){
boolean flag = true;
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(flag){
solButton.setBackgroundColor(Color.GREEN);
}
else{
solButton.setBackgroundColor(Color.LTGRAY);
}
flag=!flag;
}
};
...The code goes on
Please help me out here, I am eager to learn
to avoid overlapping of buttons, use fixed width and height for buttons:
change this:
android:layout_width="wrap_content"
android:layout_height="wrap_content"
to some this like this:
android:layout_width="100dp" //what ever size suits your layout
android:layout_height="50dp" //fixing this,will not overlap the buttons

What's wrong with this code of changing background of an imagebutton?

I am trying to change the image of an imagebutton using the following codes. Eclipse crashes but there is no error discovered… I've also used setBackgroundResource instead of setImageResource, but it didn't work. Nothing in Logcat, nither in errors. Please help me to find the right way.
I have two images for this imagebutton. - edit_on & edit_off
xml
Java
imageblockButton = (ImageButton)findViewById(R.id.buttonblock);
imageblockButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
imageblockButton.setImageResource(R.drawable.edit_on);
Intent intent1 = new Intent (context, ActivityBlockList.class);
startActivity(intent1);
v.setClickable(true);
}
});
my xml looks like…
<ImageButton android:id="#+id/buttonblock"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="0sp"
android:scaleType="centerCrop"
android:background="#drawable/edit_off" />
In your xml
<ImageButton android:id="#+id/buttonblock"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="0sp"
android:scaleType="centerCrop"
android:src="#drawable/edit_off" />
use src instead of background
and
ImageButton btn = (ImageButton)findViewById(R.id.buttonblock);
btn.setImageResource(R.drawable.newimage);
Try this
imageblockButton.setBackgroundDrawable(getResources().getDrawable(R.drawable.edit_on));

dynamic textsize change in ice cream sandawich

I am trying to change text size when button is clicked.
xml :
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="hello_world"
android:textSize="30sp"
android:layout_margin=""/>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_marginTop="72dp"
android:layout_toLeftOf="#+id/textView1"
android:text="Button1" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/button1"
android:layout_toRightOf="#+id/textView1"
android:text="Button2" />
This is my code :
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtmain=(TextView)findViewById(R.id.textView1);
txtmain.setTextSize(TypedValue.COMPLEX_UNIT_SP ,30);
//txtmain.setTextSize(TypedValue.COMPLEX_UNIT_SP ,30);
txtmain.setTextAppearance(getApplicationContext(), 12);
btn1=(Button)findViewById(R.id.button1);
btn2=(Button)findViewById(R.id.button2);
txtmain.setBackgroundColor(Color.YELLOW);
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
txtmain=(TextView)findViewById(R.id.textView1);
txtmain.setTextSize(TypedValue.COMPLEX_UNIT_SP ,30);
System.out.println("txtmain get height:"+txtmain.getHeight());
//Toast.makeText(getApplicationContext(),"txtmain get
//height:"+txtmain.getHeight() , Toast.LENGTH_LONG).show();
}
});
btn2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
txtmain=(TextView)findViewById(R.id.textView1);
txtmain.setTextSize(TypedValue.COMPLEX_UNIT_SP ,80);
System.out.println("txtmain get height:"+txtmain.getHeight());
//Toast.makeText(getApplicationContext(),"txtmain get
//height:"+txtmain.getHeight() , Toast.LENGTH_LONG).show();
}
});
When I click button 1, it gives proper output but when I click button 2 after clicking button1 output changes.
Here is my output :
This would appear to be quite similar to known a known issue on ICS, see https://code.google.com/p/android/issues/detail?id=22493 and https://code.google.com/p/android/issues/detail?id=17343. The second of these suggests that a workaround is to add a "\n" to the text in the text view. Reading up those pages and those they link to may help resolve the issue for you.
The problem is
txtmain.setHeight(41);
in first button click, So it will change the height of the textview from WRAP CONTENT to a fixed size. Just remove it..
Why are you setting the text box height wen you click the button1?

Android toggle button display wrong value after orientation change

Here is my problem.
I've got a simple activity which set a layout, and add rows in a table-layout(itself in a scroll view).
Those table-rows have a custom layout with a text-field and a toggle button.
Each toggle button has a value taken from a database, and when I first create the activity, the values are OK. But when I turn the device and then change the orientation, all the toggles-button take "false" value. I printed the values that I set in the Logcat, and the values are the good ones (those in the database).
I thought something like the layout I want is hidden behind another layout, but I made some tests and the text-fields change with new values, so I really don't understand why the toggle buttons don't work.
Here is the code :
TableRow layout :
<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<RelativeLayout
android:id="#+id/relativelayout_row_parametres"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:layout_weight="1.0">
<TextView
android:id="#+id/textview_row_parametres"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#android:color/black"
android:textStyle="bold"
android:textSize="20sp"
android:layout_marginLeft="2dp"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
/>
<ToggleButton
android:id="#+id/togglebutton_row_parametres"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="2dp"
android:textOn="#string/togglebutton_on"
android:textOff="#string/togglebutton_off" />
</RelativeLayout>
</TableRow>
Activity Layout :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<ImageView style="#style/header" />
<LinearLayout
android:layout_width="fill_parent" android:layout_height="0dp"
android:layout_weight="0.8"
android:background="#drawable/gradient_bg"
android:padding="10dip"
android:orientation="vertical">
<ScrollView
android:layout_width="fill_parent" android:layout_height="0dp"
android:layout_weight="0.85"
android:fillViewport="true"
android:padding="10dip"
android:layout_gravity="center">
<TableLayout
android:id="#+id/tablelayout_parametres"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/cornered_bg"
android:paddingTop="5dip"
android:paddingBottom="5dip">
</TableLayout>
</ScrollView>
<Button
android:id="#+id/button_parametres_accept"
android:gravity="center"
android:text="#string/accept_changes"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="0.15"
android:layout_gravity="center_horizontal" />
</LinearLayout>
</LinearLayout>
And the activity code:
public class Parameters extends Activity {
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Map<String, Boolean> changes = new HashMap<String, Boolean>();
final Context ctx = getApplicationContext();
LanguageManager.updateConfig(this);
setContentView(R.layout.parametres);
CountryDB[] countries = Database.instance(getApplicationContext()).getCountries();
TableLayout tabLayout = (TableLayout) findViewById(R.id.tablelayout_parametres);
for(int i =0; i<countries.length; i++){
TableRow newRow = (TableRow) getLayoutInflater().inflate(R.layout.row_parametres, null);
TextView textView = (TextView) newRow.findViewById(R.id.textview_row_parametres);
ToggleButton toggleButton = (ToggleButton) newRow.findViewById(R.id.togglebutton_row_parametres);
toggleButton.setChecked(countries[i].isToSynchronize());
toggleButton.setTag(countries[i]);
Log.e("setChecked",""+toggleButton.getId()+"/"+countries[i].isToSynchronize());
textView.setText(countries[i].getLabel());
toggleButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
CountryDB countryTemp = (CountryDB) v.getTag();
changes.put(countryTemp.getLabel(), ((ToggleButton)v).isChecked());
}
});
tabLayout.addView(newRow);
TableRow rowDivider = (TableRow) getLayoutInflater().inflate(R.layout.row_divider, null);
tabLayout.addView(rowDivider);
}
Button buttonValidation = (Button) findViewById(R.id.button_parameters_accept);
buttonValidation.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Iterator<String> iterator = changes.keySet().iterator();
while(iterator.hasNext()){
String stringTemp = iterator.next();
Database.instance(ctx).updateCountry(stringTemp, changes.get(stringTemp));
}
Intent intent = new Intent(ctx, Splash.class);
String result = "restart";
String from = "parameters";
Intent returnIntent = new Intent();
returnIntent.putExtra("result", result);
returnIntent.putExtra("from", from);
setResult(RESULT_OK, returnIntent);
startActivity(intent);
}
});
}
}
In the Log.e, I print the values, and they are good, the display on togglebuttons is wrong, they are just all "false".
Thanks for your help.
Between onCreate() and onResume() , Android tries to restore the old state of the toggle Buttons. Since they don't have unique ID's , Android wont succeed and everything is false again. Try to move your setChecked() calls into onResume() ( maybe onStart() works too).
Here is a pretty good answer to the same Question:
ToggleButton change state on orientation changed
you have to save data before Orientation.
Android have method onSaveImstamceState(Bundle outState) and onRestoreInstanceState(BundleInstaceState)
override these method in Activity.
There's a simpler solution: you only need to add configChanges property to your activity declaration, like stated here. This way you can prevent Activity restart when orientation changes. So in your manifest you should have something like
<activity android:name=".Parameters"
android:configChanges="orientation|keyboardHidden">
or if your buildTarget>=13
<activity android:name=".Parameters"
android:configChanges="orientation|keyboardHidden|screenSize">
Edit: Like reported on comments below, this is not an optimal solution. The main drawback is reported in a note of the document linked above:
Note: Handling the configuration change yourself can make it much more difficult to use alternative resources, because the system does not automatically apply them for you. This technique should be considered a last resort when you must avoid restarts due to a configuration change and is not recommended for most applications.

Categories

Resources