-6

I have written a simple code for alert dialog box. On clicking button the the alert box is created. But my application crashes as i try to run it. Is there a problem in my casting method? i have clean and build the project but it didn't works for me. I am new to android development.

Main activity code

package com.example.user.alert_dialog;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;


public class MainActivity extends AppCompatActivity {
    private  Button bt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bt=(Button)findViewById(R.id.button);


        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
           public void onClick(View view) {
               Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                       .setAction("Action", null).show();
                buttonlistener();
            }
        });
    }
    public void buttonlistener(){
        bt=(Button)findViewById(R.id.button);
        bt.setOnClickListener(


           new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    AlertDialog.Builder a_builder = new AlertDialog.Builder(MainActivity.this);
                    a_builder.setMessage("Do you Want To Close This App!!!").setCancelable(false)
                            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    finish();
                                }
                            })
                            .setNegativeButton("No", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.cancel();
                                }
                            });
                }
            }
    );
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}

Logcat

E/AndroidRuntime: FATAL EXCEPTION: main
 Process: com.example.user.alert_dialog, PID: 7068
 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.user.alert_dialog/com.example.user.alert_dialog.MainActivity}: java.lang.ClassCastException: android.widget.RelativeLayout cannot be cast to android.widget.Button
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
     at android.app.ActivityThread.-wrap11(ActivityThread.java)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
     at android.os.Handler.dispatchMessage(Handler.java:102)
     at android.os.Looper.loop(Looper.java:148)
     at android.app.ActivityThread.main(ActivityThread.java:5417)
     at java.lang.reflect.Method.invoke(Native Method)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
  Caused by: java.lang.ClassCastException: android.widget.RelativeLayout cannot be cast to android.widget.Button
     at com.example.user.alert_dialog.MainActivity.onCreate(MainActivity.java:23)
     at android.app.Activity.performCreate(Activity.java:6237)
     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
     at android.app.ActivityThread.-wrap11(ActivityThread.java) 
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
     at android.os.Handler.dispatchMessage(Handler.java:102) 
     at android.os.Looper.loop(Looper.java:148) 
     at android.app.ActivityThread.main(ActivityThread.java:5417) 
     at java.lang.reflect.Method.invoke(Native Method) 
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

content_main xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.user.alert_dialog.MainActivity"
    tools:showIn="@layout/activity_main"
    android:id="@+id/relativeLayout">
    final RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.relativeLayout);
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Alert"
        android:id="@+id/button"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="43dp"
        android:onClick="setContentView" />
</RelativeLayout>

Main activity xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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"
    android:fitsSystemWindows="true"
    tools:context="com.example.user.alert_dialog.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include
        android:id="@+id/button"
        layout="@layout/content_main" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
  • 5
    if you read the crash log you will see what the problem is – Tim Aug 11 '17 at 13:08
  • i think problem in `bt=(Button)findViewById(R.id.button);` line. check your button id is given to any button or relativelayout – Bipin Gawand Aug 11 '17 at 13:10
  • 1
    `Caused by: java.lang.ClassCastException: android.widget.RelativeLayout cannot be cast to android.widget.Button` You cannot transform an orange into a pineapple. Unless you're a magician. – Phantômaxx Aug 11 '17 at 13:28
  • 1
    Possible duplicate of [Explanation of "ClassCastException" in Java](https://stackoverflow.com/questions/907360/explanation-of-classcastexception-in-java) – Sufian Aug 11 '17 at 14:35

2 Answers2

1

You crash log clearly states that you are getting this exception -

java.lang.ClassCastException: android.widget.RelativeLayout cannot be cast to android.widget.Button

it also states that its happening in which line

com.example.user.alert_dialog.MainActivity.onCreate(MainActivity.java:23)

This means that you are trying to cast a view of type RelativeLayout to Button.

And you are doing it in your onCreate in the line -

bt=(Button)findViewById(R.id.button);

So pls go and check if your R.id.button is a RelativeLayout id in your xml file activity_main

Kapil G
  • 4,081
  • 2
  • 20
  • 32
  • 1
    you don't have to spoonfeed answers to lazy users, let them figure it out themselves – Tim Aug 11 '17 at 13:13
  • i am not able to see problem in R.id.button in my relative layout – Muhammad Bilal Aug 11 '17 at 13:23
  • @MuhammadBilal there is a lot wrong in your xml. i wont solve it but give you a hint. You have java code running in xml. i am not sure if its a paste mistake or actual code. then on button click you have a call to setContentView which is wrong at so many levels. So rectify your xml and things might start working. See a basic course of layout designing in android – Kapil G Aug 11 '17 at 13:28
0

In your MainActivity class your are setting (activity_main) as your layout but your button is defined in (content_main.xml) which you have posted here.

In MainActivity change

setContentView(R.layout.activity_main);

to

setContentView(R.layout.content_main); to solve your issue.

Also comment below code in your Main Activity

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
       public void onClick(View view) {
           Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                   .setAction("Action", null).show();
            buttonlistener();
        }
    });

Your code has so many silly mistakes. You need to learn android basics.

Shubhendra Singh
  • 456
  • 1
  • 6
  • 16