Android 应用程序因切换活动而崩溃

Posted

技术标签:

【中文标题】Android 应用程序因切换活动而崩溃【英文标题】:Android app crashes by switching the activity 【发布时间】:2016-11-09 10:17:08 【问题描述】:

我的 android 应用程序有问题。当我按下按钮转到新活动时,它总是崩溃。

错误:

FATAL EXCEPTION: main
Process:  PID: 15534
java.lang.RuntimeException: Unable to start activity ComponentInfocom.realliferpgadac.thomas.adacapp/com.realliferpgadac.thomas.adacapp.Feed: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.view.ViewGroup
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.TextView cannot be cast to android.view.ViewGroup
at android.app.BackStackRecord.configureTransitions(BackStackRecord.java:1244)
at android.app.BackStackRecord.beginTransition(BackStackRecord.java:978)
at android.app.BackStackRecord.run(BackStackRecord.java:707)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1535)
at android.app.FragmentController.execPendingActions(FragmentController.java:325)
at android.app.Activity.performStart(Activity.java:6252)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
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) 

崩溃的activity的源代码:(应该是RSS Feed)

import android.os.AsyncTask;
import android.os.Bundle;


import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.ListFragment;

import android.view.MenuItem;
import android.widget.ArrayAdapter;

import java.io.StringReader;

public class Feed extends Activity 

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

        if (savedInstanceState == null) 
            getFragmentManager().beginTransaction()
                    .add(R.id.tvFeed, new PlaceholderFragment())
                    .commit();
        
    


    //@Override
   // public boolean onCreateOptionsMenu(Menu menu) 

        // Inflate the menu; this adds items to the action bar if it is present.
        //getMenuInflater().inflate(R.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();
        if (id == R.id.tvFeed) 
            return true;
        
        return super.onOptionsItemSelected(item);
    

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends ListFragment 

//        private TextView mRssFeed;

        public PlaceholderFragment() 
        

//        @Override
//        public View onCreateView(LayoutInflater inflater, ViewGroup container,
//                                 Bundle savedInstanceState) 
//            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
//            mRssFeed = (TextView) rootView.findViewById(R.id.rss_feed);
//            return rootView;
//        

        @Override
        public void onStart() 
            super.onStart();
            new GetAndroidPitRssFeedTask().execute();
        

        private String getAndroidPitRssFeed() throws IOException 
            InputStream in = null;
            String rssFeed = null;
            try 
                URL url = new URL("http://www.androidpit.com/feed/main.xml");
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                in = conn.getInputStream();
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                for (int count; (count = in.read(buffer)) != -1; ) 
                    out.write(buffer, 0, count);
                
                byte[] response = out.toByteArray();
                rssFeed = new String(response, "UTF-8");
             finally 
                if (in != null) 
                    in.close();
                
            
            return rssFeed;
        

        private class GetAndroidPitRssFeedTask extends AsyncTask<Void, Void, List<String>> 

            @Override
            protected List<String> doInBackground(Void... voids) 
                List<String> result = null;
                try 
                    String feed = getAndroidPitRssFeed();
                    result = parse(feed);
                 catch (XmlPullParserException e) 
                    e.printStackTrace();
                 catch (IOException e) 
                    e.printStackTrace();
                
                return result;
            

            private List<String> parse(String rssFeed) throws XmlPullParserException, IOException 
                XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
                XmlPullParser xpp = factory.newPullParser();
                xpp.setInput(new StringReader(rssFeed));
                xpp.nextTag();
                return readRss(xpp);
            

            private List<String> readRss(XmlPullParser parser)
                    throws XmlPullParserException, IOException 
                List<String> items = new ArrayList<>();
                parser.require(XmlPullParser.START_TAG, null, "rss");
                while (parser.next() != XmlPullParser.END_TAG) 
                    if (parser.getEventType() != XmlPullParser.START_TAG) 
                        continue;
                    
                    String name = parser.getName();
                    if (name.equals("channel")) 
                        items.addAll(readChannel(parser));
                     else 
                        skip(parser);
                    
                
                return items;
            

            private List<String> readChannel(XmlPullParser parser)
                    throws IOException, XmlPullParserException 
                List<String> items = new ArrayList<>();
                parser.require(XmlPullParser.START_TAG, null, "channel");
                while (parser.next() != XmlPullParser.END_TAG) 
                    if (parser.getEventType() != XmlPullParser.START_TAG) 
                        continue;
                    
                    String name = parser.getName();
                    if (name.equals("item")) 
                        items.add(readItem(parser));
                     else 
                        skip(parser);
                    
                
                return items;
            

            private String readItem(XmlPullParser parser) throws XmlPullParserException, IOException 
                String result = null;
                parser.require(XmlPullParser.START_TAG, null, "item");
                while (parser.next() != XmlPullParser.END_TAG) 
                    if (parser.getEventType() != XmlPullParser.START_TAG) 
                        continue;
                    
                    String name = parser.getName();
                    if (name.equals("title")) 
                        result = readTitle(parser);
                     else 
                        skip(parser);
                    
                
                return result;
            

            // Processes title tags in the feed.
            private String readTitle(XmlPullParser parser)
                    throws IOException, XmlPullParserException 
                parser.require(XmlPullParser.START_TAG, null, "title");
                String title = readText(parser);
                parser.require(XmlPullParser.END_TAG, null, "title");
                return title;
            

            private String readText(XmlPullParser parser)
                    throws IOException, XmlPullParserException 
                String result = "";
                if (parser.next() == XmlPullParser.TEXT) 
                    result = parser.getText();
                    parser.nextTag();
                
                return result;
            

            private void skip(XmlPullParser parser) throws XmlPullParserException, IOException 
                if (parser.getEventType() != XmlPullParser.START_TAG) 
                    throw new IllegalStateException();
                
                int depth = 1;
                while (depth != 0) 
                    switch (parser.next()) 
                        case XmlPullParser.END_TAG:
                            depth--;
                            break;
                        case XmlPullParser.START_TAG:
                            depth++;
                            break;
                    
                
            

            @Override
            protected void onPostExecute(List<String> rssFeed) 
                if (rssFeed != null) 
                    setListAdapter(new ArrayAdapter<>(
                            getActivity(),
                            android.R.layout.simple_list_item_1,
                            android.R.id.text1,
                            rssFeed));
                
            
        
    

崩溃活动的 XML 文件:

<?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_
        android:layout_
        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="com.realliferpgadac.thomas.adacapp.Feed">
        <ScrollView
            android:layout_
            android:layout_>
        <TextView
            android:layout_
            android:layout_
            android:text="New Text"
            android:id="@+id/tvFeed"
            android:layout_alignParentTop="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true" />
        </ScrollView>
</RelativeLayout>

问题出在哪里,我该如何解决?

我希望你能帮助我。

谢谢,

emt

【问题讨论】:

ClassCastException: android.widget.TextView cannot be cast to android.view.ViewGroup 您应该查看 logcat 的输出,因为它会告诉您应用程序崩溃的原因。 Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.view.ViewGroup ... cast it as Textview and try @IntelliJAmiya 感谢您的回答。我是 Java 开发的新手,所以我很抱歉这个问题,但我没有在我的源代码中找到错误。它在哪里,我该如何解决?谢谢! if (savedInstanceState == null) getFragmentManager().beginTransaction() .add(R.id.tvFeed, new PlaceholderFragment()) .commit(); 【参考方案1】:

R.id.tvFeed 替换为 Framelayout 的 id 或默认 id android.R.id.content

if (savedInstanceState == null) 
            getFragmentManager().beginTransaction()
                    .add(android.R.id.content, new PlaceholderFragment())
                    .commit();
        

并从 onOptionsItemSelected() 方法中删除代码。

if (id == R.id.tvFeed) 
            return true;
        

【讨论】:

以上是关于Android 应用程序因切换活动而崩溃的主要内容,如果未能解决你的问题,请参考以下文章

Android 因 minifyEnabled 和 AWS 调用而崩溃

Android 应用程序不断因空指针异常而崩溃

带有 ADT 的 Eclipse 因“import android”而崩溃。编辑器中的声明

Xamarin Android 应用程序因“意图必须包含显式包名称来构建 android-app”而崩溃

启用 Proguard 时,Xamarin Android 应用程序因缺少 google play 服务类而崩溃

为什么此应用程序因运行时错误而崩溃?