由于ClassCastException,应用程序无法运行

时间:2013-07-28 18:07:46

标签: java android

我是Java和Android应用程序的新手。我不知道我现在的练习代码会发生什么。它会被java.lang.RuntimeException: Unable to start activity ComponentInfo{}:java.lang.ClassCastException: android.widget.LinearLayout强制关闭。

logcat的

07-28 17:29:44.870: D/AndroidRuntime(518): Shutting down VM

07-28 17:29:44.870: W/dalvikvm(518): threadid=1: thread exiting with uncaught exception (group=0x40015560)

07-28 17:29:44.880: E/AndroidRuntime(518): FATAL EXCEPTION: main

07-28 17:29:44.880: E/AndroidRuntime(518): java.lang.RuntimeException: Unable to start 
activity     
ComponentInfo{com.Elson.ProjectVersion/com.Elson.ProjectVersion.EnterScoresActivity}:      java.lang.ClassCastException: android.widget.LinearLayout

07-28 17:29:44.880: E/AndroidRuntime(518):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)

07-28 17:29:44.880: E/AndroidRuntime(518):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)

07-28 17:29:44.880: E/AndroidRuntime(518):  at android.app.ActivityThread.access$1500(ActivityThread.java:117)

07-28 17:29:44.880: E/AndroidRuntime(518):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)

07-28 17:29:44.880: E/AndroidRuntime(518):  at android.os.Handler.dispatchMessage(Handler.java:99)

07-28 17:29:44.880: E/AndroidRuntime(518):  at android.os.Looper.loop(Looper.java:130)

07-28 17:29:44.880: E/AndroidRuntime(518):  at android.app.ActivityThread.main(ActivityThread.java:3683)

07-28 17:29:44.880: E/AndroidRuntime(518):  at    java.lang.reflect.Method.invokeNative(Native Method)

07-28 17:29:44.880: E/AndroidRuntime(518):  at 
java.lang.reflect.Method.invoke(Method.java:507)

07-28 17:29:44.880: E/AndroidRuntime(518):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)

07-28 17:29:44.880: E/AndroidRuntime(518):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)

07-28 17:29:44.880: E/AndroidRuntime(518):  at dalvik.system.NativeStart.main(Native Method)
07-28 17:29:44.880: E/AndroidRuntime(518): Caused by: java.lang.ClassCastException: android.widget.LinearLayout

07-28 17:29:44.880: E/AndroidRuntime(518):  at com.Elson.ProjectVersion.EnterScoresActivity.setUpViews(EnterScoresActivity.java:142)

07-28 17:29:44.880: E/AndroidRuntime(518):  at com.Elson.ProjectVersion.EnterScoresActivity.onCreate(EnterScoresActivity.java:42)
07-28 17:29:44.880: E/AndroidRuntime(518):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)

07-28 17:29:44.880: E/AndroidRuntime(518):  at 

android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)

07-28 17:29:44.880: E/AndroidRuntime(518):  ... 11 more

.xml文件(enter_scores.xml)

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal"
android:gravity="center_horizontal"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".EnterScoresActivity" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingTop="10dp"
    android:text="Enter Bowling Scores:"
    android:textSize="25sp" />

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/DateTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="10dp"
        android:text="Date of Games"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <Button
        android:id="@+id/changeDateButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Change Date" />

</LinearLayout>

<LinearLayout
    android:id="@+id/SaveButton"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_gravity="center_horizontal"
    android:gravity="center_horizontal"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Game1:"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <EditText
            android:id="@+id/Game1EditText"
            android:layout_width="66dp"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="number"
            android:text="300" >

            <requestFocus />
        </EditText>
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/textView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Game2:"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <EditText
            android:id="@+id/Game2EditText"
            android:layout_width="66dp"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="number"
            android:text="300" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/textView4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Game3:"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <EditText
            android:id="@+id/Game3EditText"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ems="10"
            android:inputType="number"
            android:text="300" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/textView5"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Series Total:"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <TextView
            android:id="@+id/SeriesTotalTextView"
            android:layout_width="50dp"
            android:layout_height="wrap_content"
            android:ems="10"
            android:text="900" />

    </LinearLayout>

    <Button
        android:id="@+id/SaveButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Save"
        tools:ignore="DuplicateIds" />

    <Button
        android:id="@+id/ShowHistory"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ShowHistory" />

</LinearLayout>

EnterScoresActivity.java

package com.Elson.ProjectVersion;

import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;

public class EnterScoresActivity extends Activity {

private Button saveButton;
private Button historyButton;
private EditText game1ScoreEditText;
private EditText game2ScoreEditText;
private EditText game3ScoreEditText;
private TextView date;
private TextView seriesTotal;
private Button changeDateButton;


private int month;//private within class
private int day;
private int year;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.enter_scores);

    setUpViews();


    //put today's date on the screen
    Calendar calendar =Calendar.getInstance();
    year = calendar.get(Calendar.YEAR);
    month = calendar.get(Calendar.MONTH);
    day = calendar.get(Calendar.DAY_OF_MONTH);

    Date today = calendar.getTime();
    DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM);
    String cs = df.format(today);
    date.setText(cs);
}

/*
 * Get the 3 scores from the interface, validate the scores
 create an object to hold the scores.
 */

public void saveClickHandler(View v){
    String rawScore; 
    rawScore = game1ScoreEditText.getText().toString();
    int score1 = Integer.parseInt(rawScore);
    rawScore = game2ScoreEditText.getText().toString();
    int score2 = Integer.parseInt(rawScore);
    rawScore = game3ScoreEditText.getText().toString();
    int score3 = Integer.parseInt(rawScore);

    Log.d("EnterScores" , "I hear the Save Button");


    if( isValid(score1) && isValid(score2) && isValid(score3) ) {
        BowlingScores bowlingScores;
        Date dateofGames= new Date(year,month,day);
        bowlingScores= new BowlingScores(score1, score2, score3, dateofGames);

        seriesTotal.setText(bowlingScores.calculateSeriesScore() );

        MyBowlingScoresApplication app  = (MyBowlingScoresApplication) getApplication();
        app.addBowlingScores(bowlingScores);


    }else {
        //pop up a dialog that dad is invalid
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Invalid Scores")
               .setMessage("Bowling scores cannot be greater than 300")
               .setCancelable(false)
               .setPositiveButton("OK", 

                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        dialog.cancel(); 
                    }
                });

        AlertDialog alert = builder.create();
        alert.show();

    }
}

private boolean isValid(int score){
    if(score >=0 && score <=300)
        return true;
    return false;
}

public void changeDateClickHandler(View v){
    Log.d("Enter Scores", "I heear the Change Date Button");

    DatePickerDialog.OnDateSetListener datePickerListener;

    datePickerListener = new DatePickerDialog.OnDateSetListener(){

        @Override
        public void onDateSet(DatePicker view, int yearOfYear, int monthOfYear,
                int dayOfMonth) {
            // TODO Auto-generated method stub
            year=yearOfYear;
            month= monthOfYear;
            day=dayOfMonth;

            Calendar cal= new GregorianCalendar(year , month , day);
            Date dateofGames = cal.getTime();
            DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM);
            String cs= df.format(dateofGames);
            date.setText(cs);
        } 

    };

    DatePickerDialog dpd = new DatePickerDialog(this,datePickerListener,year,month,day);
    dpd.show();
}
private void setUpViews(){
    saveButton= (Button) findViewById(R.id.SaveButton);
    game1ScoreEditText =(EditText) findViewById(R.id.Game1EditText);
    game2ScoreEditText =(EditText) findViewById(R.id.Game2EditText);
    game3ScoreEditText =(EditText) findViewById(R.id.Game3EditText);
    date = (TextView) findViewById(R.id.DateTextView);
    seriesTotal = (TextView) findViewById(R.id.SeriesTotalTextView);

}

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

}

2 个答案:

答案 0 :(得分:2)

学习如何从Logcat中读取堆栈跟踪:

  • logcat中的这一行:

    Caused by: java.lang.ClassCastException: android.widget.LinearLayout`
    

    告诉您应用程序中的异常。

  • 另一行:

    at com.Elson.ProjectVersion.EnterScoresActivity.setUpViews(EnterScoresActivity.java:142)
    

    告诉您异常提升的位置以及应该修复的位置。

以此信息为背景,让我们在 EnterScoresActivity.java 中寻找第142行。由于您复制/粘贴了整个班级,因此很容易找到罪魁祸首,这导致了这一行:

saveButton= (Button) findViewById(R.id.SaveButton);

似乎ID为SaveButton的元素是LinearLayout,您尝试对Button进行投射。为了确保这一点,让我们检查您的视图xml并搜索标识为SaveButton的元素。根据问题中的XML,我们会发现:

<LinearLayout
    android:id="@+id/SaveButton"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_gravity="center_horizontal"
    android:gravity="center_horizontal"
    android:orientation="vertical" >

现在出现问题:此LinearLayout的ID为SaveButton,可能是您在编辑视图时犯的错误。

解决方案?

可能的解决方案是将SaveButton ID设置为相应的按钮而不是此LinearLayout

答案 1 :(得分:0)

代码

<LinearLayout
    android:id="@+id/SaveButton"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_gravity="center_horizontal"
    android:gravity="center_horizontal"
    android:orientation="vertical" >
....
<Button
    android:id="@+id/SaveButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Save"
    tools:ignore="DuplicateIds" />

你可以看到按钮和线性布局都具有相同的id值...只是尝试改变不同的id值并尝试一下