类转换异常错误片段

时间:2015-08-12 20:43:19

标签: java android exception casting

我在eclipse中做了这个教程http://javapapers.com/android/android-twitter-feed-reader/并将我的项目移到了工作室。有人可以帮助解决这些错误的含义以及如何解决这些错误吗?我的logcat如下:

java.lang.RuntimeException: An error occured while executing doInBackground()
            at android.os.AsyncTask$3.done(AsyncTask.java:300)
            at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
            at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
            at java.util.concurrent.FutureTask.run(FutureTask.java:242)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:841)
     Caused by: java.lang.ClassCastException: com.example.ishonours.witsbusapp.TwitterFragment cannot be cast to android.app.ListActivity
            at com.example.ishonours.witsbusapp.TwitterAsyncTask.doInBackground(TwitterAsyncTask.java:24)
            at com.example.ishonours.witsbusapp.TwitterAsyncTask.doInBackground(TwitterAsyncTask.java:15)
            at android.os.AsyncTask$2.call(AsyncTask.java:288)
            at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:841)

这是我的TwitterAsyncTask类:

import android.app.ListActivity;
import android.text.method.LinkMovementMethod;
import android.widget.ArrayAdapter;
import android.os.AsyncTask;
import android.widget.ListView;
import android.widget.TextView;

import com.example.ishonours.witsbusapp.TwitterAPI;
import com.example.ishonours.witsbusapp.TwitterTweet;

import java.util.ArrayList;

public class TwitterAsyncTask extends AsyncTask<Object, Void, ArrayList<TwitterTweet>> {
    ListActivity callerActivity;

    final static String TWITTER_API_KEY = "xxx";
    final static String TWITTER_API_SECRET = "xxx";

    @Override
    protected ArrayList<TwitterTweet> doInBackground(Object... params) {
        ArrayList<TwitterTweet> twitterTweets = null;
        callerActivity = (ListActivity) params[1];
        if (params.length > 0) {
            TwitterAPI twitterAPI = new TwitterAPI(TWITTER_API_KEY,TWITTER_API_SECRET);
            twitterTweets = twitterAPI.getTwitterTweets(params[0].toString());
        }
        return twitterTweets;
    }

    @Override
    protected void onPostExecute(ArrayList<TwitterTweet> twitterTweets) {
        ArrayAdapter<TwitterTweet> adapter =
                new ArrayAdapter<TwitterTweet>(callerActivity, R.layout.twitter_tweets_list,
                        R.id.listTextView, twitterTweets);
        callerActivity.setListAdapter(adapter);
        ListView lv = callerActivity.getListView();
        lv.setDividerHeight(0);
        //lv.setDivider(this.getResources().getDrawable(android.R.color.transparent));
        //lv.setBackgroundColor(callerActivity.getResources().getColor(R.color.Twitter_blue));
    }
}

我应该提到我对此非常陌生。评论给了我一些错误的观点。我仍然不太确定如何解决它。还有其他建议吗?

这是另一个类,TwitterFragment:

public class TwitterFragment extends ListFragment {

    private static final String ARG_SECTION_NUMBER = "4";

    private OnFragmentInteractionListener mListener;

    public static TwitterFragment newInstance(int menuNumber) {
        TwitterFragment fragment = new TwitterFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, menuNumber);
        fragment.setArguments(args);
        return fragment;
    }

    public TwitterFragment() {
    }

    //i added
    final static String twitterScreenName = "WitsServices";
    final static String TAG = "MainActivity";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //i added
        AndroidNetworkUtility androidNetworkUtility = new AndroidNetworkUtility();
        if (androidNetworkUtility.isConnected(this)) {
            new TwitterAsyncTask().execute(twitterScreenName,this);
        } else {
            Log.v(TAG, "Network not Available!");
        }


        //setListAdapter(new ArrayAdapter<DummyContent.DummyItem>(getActivity(),
        //        android.R.layout.simple_list_item_1, android.R.id.text1, DummyContent.ITEMS));
    }


    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        ((MainActivity) activity).onSectionAttached(
                getArguments().getInt(ARG_SECTION_NUMBER));
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);

        if (null != mListener) {
            // Notify the active callbacks interface (the activity, if the
            // fragment is attached to one) that an item has been selected.
            //mListener.onFragmentInteraction(DummyContent.ITEMS.get(position).id);
        }
    }

    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        public void onFragmentInteraction(String id);
    }

}

2 个答案:

答案 0 :(得分:1)

此行开始时,

callerActivity = (ListActivity) params[1];

代码假定params数组中索引1处的Object可以转换为ListActivity类型。但相反,它发现类型是TwitterFragment - 一个不兼容的强制转换,因此您收到此错误。

鉴于您正在使用任意Object数组作为输入,可能导致崩溃的原因是当您创建并调用AsyncTask时,您必须传入TwitterFragment而不是传递ListActivity类型的类。

答案 1 :(得分:0)

Gogeta的anwer是正确的,因为错误意味着您获得了一个类TwitterFragment的实例,并尝试将其用作ListActivity;由于TwitterFragment既未扩展也未实现ListActivity,因此抛出了ClassCastException。

检查android javadoc(提示:总是读取你使用的类的javadoc),它解释了

  

指定的参数是传递给执行的参数(Params ...)

所以,在你的另一个班级的某个地方,你正在做类似的事情:

TwitterAsyncTask myAsyncTask = new TwitterAsyncTask();
myAsyncTask.execute(obj1, obj2);

其中obj2应该是ListActivity个实例(可能是当前活动的参考)。

在您的链接代码中:

new TwitterAsyncTask().execute(twitterScreenName,this);

注意:此代码位于您的帖子和链接中:

  callerActivity = (ListActivity) params[1];
  if (params.length > 0) {

如果您的代码调用execute方法传递0或1个参数,则第一行会抛出IndexOutOfBoundsException,因此第二行的检查没有意义(如果执行该行代码,我们确信至少传递了2个参数)。也许你应该寻找质量更好的教程。