java.util.ArrayList 不能强制转换为

Posted

技术标签:

【中文标题】java.util.ArrayList 不能强制转换为【英文标题】:java.util.ArrayList cannot be cast to 【发布时间】:2015-09-03 07:04:39 【问题描述】:

我是 android 新手,在不同的测试应用程序中测试我的技能。现在我正在尝试从 Json url 获取数据并从 Json 的对象收藏列表中创建。 Gradle 完成后没有任何问题,但每次我的应用启动时,它都会崩溃并出现下一个错误:

尝试在空对象引用上调用接口方法“int java.util.List.size()”

我用作教程的下一个资源:

对于共享首选项:http://androidopentutorials.com/android-how-to-store-list-of-values-in-sharedpreferences/

对于 Json 解析器:http://www.androidhive.info/2014/09/android-json-parsing-using-volley/

这是我的代码错误和活动错误在哪里:

   06-17 17:05:14.124  10249-10249/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.boom.kayakapp, PID: 10249
    java.lang.ClassCastException: java.util.ArrayList cannot be cast to com.boom.kayakapp.model.Airlines
            at com.boom.kayakapp.adapters.AirlinesListAdapter.getView(AirlinesListAdapter.java:102)
            at android.widget.AbsListView.obtainView(AbsListView.java:2347)
            at android.widget.ListView.measureHeightOfChildren(ListView.java:1270)
            at android.widget.ListView.onMeasure(ListView.java:1182)
            at android.view.View.measure(View.java:17547)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
            at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
            at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
            at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
            at android.view.View.measure(View.java:17547)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
            at android.support.v7.internal.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:124)
            at android.view.View.measure(View.java:17547)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
            at android.support.v7.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:444)
            at android.view.View.measure(View.java:17547)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
            at android.view.View.measure(View.java:17547)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
            at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
            at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
            at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
            at android.view.View.measure(View.java:17547)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
            at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2615)
            at android.view.View.measure(View.java:17547)
            at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2015)
            at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1173)
            at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1379)
            at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1061)
            at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5885)
            at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
            at android.view.Choreographer.doCallbacks(Choreographer.java:580)
            at android.view.Choreographer.doFrame(Choreographer.java:550)
            at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5257)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
06-17 17:05:14.153      932-932/? E/EGL_emulation﹕ tid 932: eglCreateSyncKHR(1237): error 0x3004 (EGL_BAD_ATTRIBUTE)
06-17 17:05:16.543    1233-1266/system_process E/InputDispatcher﹕ channel '26e93136 com.boom.kayakapp/com.boom.kayakapp.activities.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
06-17 17:05:38.432  10506-10506/? E/memtrack﹕ Couldn't load memtrack module (No such file or directory)
06-17 17:05:38.432  10506-10506/? E/android.os.Debug﹕ failed to load memtrack module: -2
06-17 17:05:39.009  10523-10523/? E/memtrack﹕ Couldn't load memtrack module (No such file or directory)
06-17 17:05:39.009  10523-10523/? E/android.os.Debug﹕ failed to load memtrack module: -2
06-17 17:05:51.855  10533-10533/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.boom.kayakapp, PID: 10533
    java.lang.ClassCastException: java.util.ArrayList cannot be cast to com.boom.kayakapp.model.Airlines
            at com.boom.kayakapp.adapters.AirlinesListAdapter.getView(AirlinesListAdapter.java:102)
            at android.widget.AbsListView.obtainView(AbsListView.java:2347)
            at android.widget.ListView.measureHeightOfChildren(ListView.java:1270)
            at android.widget.ListView.onMeasure(ListView.java:1182)
            at android.view.View.measure(View.java:17547)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
            at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
            at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
            at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
            at android.view.View.measure(View.java:17547)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
            at android.support.v7.internal.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:124)
            at android.view.View.measure(View.java:17547)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
            at android.support.v7.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:444)
            at android.view.View.measure(View.java:17547)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
            at android.view.View.measure(View.java:17547)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
            at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
            at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
            at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
            at android.view.View.measure(View.java:17547)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
            at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2615)
            at android.view.View.measure(View.java:17547)
            at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2015)
            at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1173)
            at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1379)
            at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1061)
            at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5885)
            at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
            at android.view.Choreographer.doCallbacks(Choreographer.java:580)
            at android.view.Choreographer.doFrame(Choreographer.java:550)
            at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5257)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
06-17 17:05:51.887      932-932/? E/EGL_emulation﹕ tid 932: eglCreateSyncKHR(1237): error 0x3004 (EGL_BAD_ATTRIBUTE)
06-17 17:06:51.514  11046-11046/? E/memtrack﹕ Couldn't load memtrack module (No such file or directory)
06-17 17:06:51.514  11046-11046/? E/android.os.Debug﹕ failed to load memtrack module: -2
06-17 17:06:52.206  11063-11063/? E/memtrack﹕ Couldn't load memtrack module (No such file or directory)
06-17 17:06:52.207  11063-11063/? E/android.os.Debug﹕ failed to load memtrack module: -2
06-17 17:07:03.184      932-932/? E/EGL_emulation﹕ tid 932: eglCreateSyncKHR(1237): error 0x3004 (EGL_BAD_ATTRIBUTE)
06-17 17:07:06.919    1233-1266/system_process E/InputDispatcher﹕ channel '3bd6cfb7 com.boom.kayakapp/com.boom.kayakapp.activities.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!

AirlinesListAdapter:

    package com.boom.kayakapp.adapters;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.boom.kayakapp.R;
import com.boom.kayakapp.controllers.AppController;
import com.boom.kayakapp.model.Airlines;
import com.boom.kayakapp.util.SharedPreference;

import java.util.ArrayList;
import java.util.List;

public class AirlinesListAdapter extends ArrayAdapter<Airlines> 

    private Activity activity;
    private List<Airlines> favorites;

    private LayoutInflater inflater;
    SharedPreference sharedPreference;
    ImageLoader imageLoader = AppController.getInstance().getImageLoader();

    public AirlinesListAdapter(Activity activity, List<Airlines> favorites) 
        super(activity, R.layout.list_item, favorites);
        this.activity = activity;
        if(favorites == null)
            favorites = new ArrayList<>();
        else
            this.favorites = favorites;
        sharedPreference = new SharedPreference();

    

    private class ViewHolder 
        ImageView favoriteImg;
    

    @Override
    public int getCount() 
        return favorites.size();
    

    @Override
    public Airlines getItem(int location) 
        return favorites.get(location);
    

    @Override
    public long getItemId(int position) 
        return 0;
    

    @Override
    public View getView(int position, View convertView, ViewGroup parent) 

        ViewHolder holder = null;

        if (inflater == null)
            inflater = (LayoutInflater) activity
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (convertView == null)
            convertView = inflater.inflate(R.layout.list_item, null);

        holder = new ViewHolder();

        if (imageLoader == null)
            imageLoader = AppController.getInstance().getImageLoader();
        NetworkImageView logoURL = (NetworkImageView) convertView
                .findViewById(R.id.logoURL);

        TextView name = (TextView) convertView.findViewById(R.id.name);
        TextView phone = (TextView) convertView.findViewById(R.id.phone);
        TextView site = (TextView) convertView.findViewById(R.id.site);
        TextView code = (TextView) convertView.findViewById(R.id.code);

        holder.favoriteImg = (ImageView) convertView
                .findViewById(R.id.favorite_button);

        // getting airlines data for the row
        Airlines m = favorites.get(position);
        // thumbnail image
        logoURL.setImageUrl(m.getLogoURL(), imageLoader);
        // name
        name.setText(m.getName());
        // phone
        phone.setText("Phone: " + String.valueOf(m.getPhone()));
        // site
        site.setText("Web: " + String.valueOf(m.getSite()));
        // release code
        code.setText(String.valueOf(m.getCode()));

        /*If a product exists in shared preferences then set heart_red drawable
         * and set a tag*/
        if (checkFavoriteItem((Airlines) favorites)) 
            holder.favoriteImg.setImageResource(R.drawable.heart_red);
            holder.favoriteImg.setTag("red");
         else 
            holder.favoriteImg.setImageResource(R.drawable.heart_grey);
            holder.favoriteImg.setTag("grey");
        

        return convertView;
    
    /*Checks whether a particular product exists in SharedPreferences*/
    public boolean checkFavoriteItem(Airlines checkAirlines) 
        boolean check = false;
//      List<Airlines> favorites = sharedPreference.getFavorites(activity);
        if (favorites != null) 
            for (Airlines product : favorites) 
                if (product.equals(checkAirlines)) 
                    check = true;
                    break;
                
            
        
        return check;
    

    @Override
    public void add(Airlines airlines) 
        super.add(airlines);
        favorites.add(airlines);
        notifyDataSetChanged();
    

    @Override
    public void remove(Airlines airlines) 
        super.remove(airlines);
        favorites.remove(airlines);
        notifyDataSetChanged();
    


AirlineListFragment:

    package com.boom.kayakapp.fragment;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.boom.kayakapp.R;
import com.boom.kayakapp.adapters.AirlinesListAdapter;
import com.boom.kayakapp.model.Airlines;
import com.boom.kayakapp.util.SharedPreference;

import java.util.ArrayList;
import java.util.List;

public class AirlinesListFragment extends Fragment implements OnItemLongClickListener, AdapterView.OnItemClickListener 

    public static final String ARG_ITEM_ID = "airlines_list";

    Activity activity;
    ListView airlinesListView;
    List<Airlines> airlines;
    AirlinesListAdapter airlinesListAdapter;

    public AirlinesListFragment() 
        airlines = new ArrayList<>();

    

    SharedPreference sharedPreference;

    @Override
    public void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        activity = getActivity();
        sharedPreference = new SharedPreference();

    

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) 
        View view = inflater.inflate(R.layout.fragment_airlines_list, container,
                false);
        findViewsById(view);

        airlinesListAdapter = new AirlinesListAdapter(activity, airlines);
        airlinesListView.setAdapter(airlinesListAdapter);
        airlinesListView.setOnItemClickListener(this);
        airlinesListView.setOnItemLongClickListener(this);
        return view;
    

    private void findViewsById(View view) 
        airlinesListView = (ListView) view.findViewById(R.id.list_airlines);
    

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) 
        Airlines airlines = (Airlines) parent.getItemAtPosition(position);
        Toast.makeText(activity, airlines.toString(), Toast.LENGTH_LONG).show();
    

    @Override
    public boolean onItemLongClick(AdapterView<?> arg0, View view,
            int position, long arg3) 
        ImageView button = (ImageView) view.findViewById(R.id.favorite_button);

        String tag = button.getTag().toString();
        if (tag.equalsIgnoreCase("grey")) 
            sharedPreference.addFavorite(activity, airlines.get(position));
            Toast.makeText(activity,
                    activity.getResources().getString(R.string.add_favr),
                    Toast.LENGTH_SHORT).show();

            button.setTag("red");
            button.setImageResource(R.drawable.heart_red);
         else 
            sharedPreference.removeFavorite(activity, airlines.get(position));
            button.setTag("grey");
            button.setImageResource(R.drawable.heart_grey);
            Toast.makeText(activity,
                    activity.getResources().getString(R.string.remove_favr),
                    Toast.LENGTH_SHORT).show();
        

        return true;
    

    @Override
    public void onResume() 
        getActivity().setTitle(R.string.app_name);
        getActivity().getActionBar().setTitle(R.string.app_name);
        super.onResume();
    

主活动:

package com.boom.kayakapp.activities;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.boom.kayakapp.R;
import com.boom.kayakapp.adapters.AirlinesListAdapter;
import com.boom.kayakapp.controllers.AppController;
import com.boom.kayakapp.fragment.AirlinesListFragment;
import com.boom.kayakapp.fragment.FavoriteListFragment;
import com.boom.kayakapp.model.Airlines;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends ActionBarActivity 

    private Fragment contentFragment;
    AirlinesListFragment airlinesListFragment;
    FavoriteListFragment favoriteListFragment;

    // JSON Node names
    public static final String TAG_NAME = "name";
    public static final String TAG_PHONE = "phone";
    public static final String TAG_SITE = "site";
    public static final String TAG_LOGO = "logoURL";
    public static final String TAG_CODE = "code";

    // Log tag
    private static final String TAG = MainActivity.class.getSimpleName();

    // Airlines json url
    private static final String url = "https://www.kayak.com/h/mobileapis/directory/airlines";

    public ProgressDialog pDialog;
    public List<Airlines> airlinesList = new ArrayList<Airlines>();
    public ListView listView;
    public AirlinesListAdapter adapter;

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

        listView = (ListView) findViewById(R.id.list);
        adapter = new AirlinesListAdapter(this, airlinesList);
        listView.setAdapter(adapter);

        pDialog = new ProgressDialog(this);
        // Showing progress dialog before making http request
        pDialog.setMessage("Loading...");
        pDialog.show();

        // Listview on item click listener
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() 

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) 
                // getting values from selected ListItem
                String name = ((TextView) view.findViewById(R.id.name))
                        .getText().toString();
                String phone = ((TextView) view.findViewById(R.id.phone))
                        .getText().toString();
                String site = ((TextView) view.findViewById(R.id.site))
                        .getText().toString();
                String logoURL = String.valueOf(((ImageView) view.findViewById(R.id.logoURL)));

                // Starting single contact activity
                Intent in = new Intent(getApplicationContext(),
                        SingleContactActivity.class);
                in.putExtra(TAG_NAME, name);
                in.putExtra(TAG_PHONE, phone);
                in.putExtra(TAG_SITE, site);
                in.putExtra(TAG_LOGO, logoURL);
                startActivity(in);

            
        );

        // changing action bar color
        getSupportActionBar().setBackgroundDrawable(
                new ColorDrawable(Color.parseColor("#1b1b1b")));

        // Creating volley request obj
        JsonArrayRequest airlinesReq = new JsonArrayRequest(url,
                new Response.Listener<JSONArray>() 
                    @Override
                    public void onResponse(JSONArray response) 
                        Log.d(TAG, response.toString());
                        hidePDialog();

                        // Parsing json
                        for (int i = 0; i < response.length(); i++) 
                            try 

                                JSONObject obj = response.getJSONObject(i);
                                Airlines airlines = new Airlines();
                                airlines.setName(obj.getString("name"));
                                airlines.setLogoURL(obj.getString("logoURL"));
                                airlines.setPhone(obj.getString("phone"));
                                airlines.setCode(obj.getInt("code"));
                                airlines.setSite(obj.getString("site"));

                                // adding airlines to movies array
                                airlinesList.add(airlines);

                             catch (JSONException e) 
                                e.printStackTrace();
                            

                        

                        // notifying list adapter about data changes
                        // so that it renders the list view with updated data
                        adapter.notifyDataSetChanged();
                    
                , new Response.ErrorListener() 
            @Override
            public void onErrorResponse(VolleyError error) 
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                hidePDialog();

            
        );

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(airlinesReq);

        FragmentManager fragmentManager = getSupportFragmentManager();

        /*
         * This is called when orientation is changed.
         */
        if (savedInstanceState != null) 
            if (savedInstanceState.containsKey("content")) 
                String content = savedInstanceState.getString("content");
                if (content.equals(FavoriteListFragment.ARG_ITEM_ID)) 
                    if (fragmentManager.findFragmentByTag(FavoriteListFragment.ARG_ITEM_ID) != null) 
                        setFragmentTitle(R.string.favorites);
                        contentFragment = fragmentManager
                                .findFragmentByTag(FavoriteListFragment.ARG_ITEM_ID);
                    
                
            
            if (fragmentManager.findFragmentByTag(AirlinesListFragment.ARG_ITEM_ID) != null) 
                airlinesListFragment = (AirlinesListFragment) fragmentManager
                        .findFragmentByTag(AirlinesListFragment.ARG_ITEM_ID);
                contentFragment = airlinesListFragment;
            
         else 
            airlinesListFragment = new AirlinesListFragment();
//          setFragmentTitle(R.string.app_name);
            switchContent(airlinesListFragment, AirlinesListFragment.ARG_ITEM_ID);
        
    

    @Override
    public void onDestroy() 
        super.onDestroy();
        hidePDialog();
    

    private void hidePDialog() 
        if (pDialog != null) 
            pDialog.dismiss();
            pDialog = null;
        
    

    @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
    protected void onSaveInstanceState(Bundle outState) 
        if (contentFragment instanceof FavoriteListFragment) 
            outState.putString("content", FavoriteListFragment.ARG_ITEM_ID);
         else 
            outState.putString("content", AirlinesListFragment.ARG_ITEM_ID);
        
        super.onSaveInstanceState(outState);
    


//  @Override
//  public boolean onCreateOptionsMenu(Menu menu) 
//      getMenuInflater().inflate(R.menu.main, menu);
//      return true;
//  

    @Override
    public boolean onOptionsItemSelected(MenuItem item) 
        switch (item.getItemId()) 
            case R.id.menu_favorites:
                setFragmentTitle(R.string.favorites);
                favoriteListFragment = new FavoriteListFragment();
                switchContent(favoriteListFragment, FavoriteListFragment.ARG_ITEM_ID);

                return true;
        
        return super.onOptionsItemSelected(item);
    

    public void switchContent(Fragment fragment, String tag) 
        FragmentManager fragmentManager = getSupportFragmentManager();
        while (fragmentManager.popBackStackImmediate());

        if (fragment != null) 
            FragmentTransaction transaction = fragmentManager
                    .beginTransaction();
            transaction.replace(R.id.content_frame, fragment, tag);
            //Only FavoriteListFragment is added to the back stack.
            if (!(fragment instanceof AirlinesListFragment)) 
                transaction.addToBackStack(tag);
            
            transaction.commit();
            contentFragment = fragment;
        
    

    protected void setFragmentTitle(int resourseId) 
        setTitle(resourseId);
        getSupportActionBar().setTitle(resourseId);

    

    /*
     * We call super.onBackPressed(); when the stack entry count is > 0. if it
     * is instanceof ProductListFragment or if the stack entry count is == 0, then
     * we finish the activity.
     * In other words, from ProductListFragment on back press it quits the app.
     */
    @Override
    public void onBackPressed() 
        FragmentManager fm = getSupportFragmentManager();
        if (fm.getBackStackEntryCount() > 0) 
            super.onBackPressed();
         else if (contentFragment instanceof AirlinesListFragment
                || fm.getBackStackEntryCount() == 0) 
            finish();
        
    

型号:

package com.boom.kayakapp.model;

public class Airlines 
    private String name, logoURL, phone, site;
    private int code;

    public Airlines() 
    

    public Airlines
            (String name, String logoURL, int code, String phone, String site) 
        this.name = name;
        this.logoURL = logoURL;
        this.code = code;
        this.phone = phone;
        this.site = site;

    

    public String getName() return name;
    public void setName(String name) this.name = name;

    public String getLogoURL() return logoURL;
    public void setLogoURL(String logoURL) this.logoURL = logoURL;

    public int getCode() return code;
    public void setCode(Integer code) this.code = code;

    public String getPhone() return phone;
    public void setPhone(String phone) this.phone = phone;

    public String getSite() return site;
    public void setSite(String site) this.site = site;


【问题讨论】:

【参考方案1】:

setAdapter 调用 getCount 但列表为空,所以只需像这样初始化航空公司列表

    public AirlinesListAdapter(Activity activity, List<Airlines> favorites) 
    super(activity, R.layout.list_item, favorites);
    this.activity = activity;
    if(favorites == null)
        favorites = new ArrayList<>();
   else 
        this.favorites = favorites;
    sharedPreference = new SharedPreference();


第二种解决方案: 在片段中初始化数组

 public AirlinesListFragment() 
    airlines = new ArrayList<>();

   

这应该可以解决您的问题

查看此页面以获取解决方案:Can't get Action Bar in fragment class

【讨论】:

第二种方式对我有帮助,非常感谢!但不幸的是它显示了另一个错误,但我继续前进,感谢帮助!!! 好的,用新的错误更新你的问题,我会尽力帮助你 Itzik Samara,谢谢你的帮助,但我只是在 AirlinesListFragment 中评论 getActivity().getActionBar().setTitle(R.string.app_name); b> 因为它与第一个字符串 getActivity().setTitle(R.string.app_name); 重复,然后应用程序向我显示了下一个错误(听起来像诅咒)错误我与新模型活动一起更新 你的问题在这里 checkFavoriteItem((Airlines) favorites) 最喜欢的是 List 并且你只需要 Airlines

以上是关于java.util.ArrayList 不能强制转换为的主要内容,如果未能解决你的问题,请参考以下文章

java.lang.ClassCastException:java.util.ArrayList无法强制转换为java.lang.String,array [[file-1519428262786.p

java.util.HashMap 不能转换为 java.util.ArrayList

java.lang.ClassCastException:java.util.ArrayList 不能使用 cassandra 转换为 java.util.UUID 异常?

对象到 ArrayList<String> 未经检查的强制转换

Java程序员容易犯的常见十大错误转)

数组转成集合的误区