VideoListFragment中的ArrayIndexOutOfBoundException

时间:2014-08-25 09:14:23

标签: android stack-trace indexoutofboundsexception

我收到运行时异常:

  

java.lang.ArrayIndexOutOfBoundsException:length = 1; index = 4 at   com.sit.loco.frgment.VideoListFragment.onCreateView(VideoListFragment.java:110)

我在下面的编码中提到了第110行。

StackTrace:

08-25 04:55:10.808: E/AndroidRuntime(2402): FATAL EXCEPTION: main
08-25 04:55:10.808: E/AndroidRuntime(2402): Process: com.loco.android, PID: 2402
08-25 04:55:10.808: E/AndroidRuntime(2402): java.lang.ArrayIndexOutOfBoundsException: length=1; index=4
08-25 04:55:10.808: E/AndroidRuntime(2402):     at com.sit.loco.frgment.VideoListFragment.onCreateView(VideoListFragment.java:110)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.support.v4.app.Fragment.performCreateView(Fragment.java:1500)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:938)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1115)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1478)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:478)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.support.v4.view.ViewPager.populate(ViewPager.java:1068)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.support.v4.view.ViewPager.populate(ViewPager.java:914)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1436)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.view.View.measure(View.java:16497)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:719)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:455)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.view.View.measure(View.java:16497)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.view.View.measure(View.java:16497)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:327)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.view.View.measure(View.java:16497)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2291)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.view.View.measure(View.java:16497)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1916)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1113)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1295)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1000)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5670)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.view.Choreographer.doCallbacks(Choreographer.java:574)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.view.Choreographer.doFrame(Choreographer.java:544)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.os.Handler.handleCallback(Handler.java:733)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.os.Handler.dispatchMessage(Handler.java:95)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.os.Looper.loop(Looper.java:136)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at android.app.ActivityThread.main(ActivityThread.java:5017)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at java.lang.reflect.Method.invokeNative(Native Method)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at java.lang.reflect.Method.invoke(Method.java:515)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
08-25 04:55:10.808: E/AndroidRuntime(2402):     at dalvik.system.NativeStart.main(Native Method)

VideoListFragment.java:

package com.sit.loco.frgment;

import android.support.v4.app.Fragment;

public class VideoListFragment extends Fragment {

    OnVideoSelectedListener mCallback;
    boolean loadingMore = false;

    // create string variables
    String YOUTUBE_USERNAME = "";

    private String YOUTUBE_API = "http://gdata.youtube.com/feeds/api/users/"+YOUTUBE_USERNAME+"/uploads?alt=jsonc" +
            "&v=2"+
            "&start-index=1"+
            "&max-results=10";

    // create object of views
    ListView list;
    ProgressBar prgLoading;
    Button btnRefresh;
    Button btnLoadMore;

    // create variable to get position, connection status, resources, and channel username
    int position;
    boolean isConnect = true;
    Resources res;
    String[] ChannelUsername;

    // create object of custom adapter
    VideoListAdapter vla;

    // create arraylist variables
    ArrayList<HashMap<String, String>> menuItems;
    ProgressDialog pDialog;

    // flag for current page
    int current_page = 1;
    int previous_page;

    static final String KEY_ID = "id";
    static final String KEY_TITLE = "title";
    static final String KEY_THUMBNAIL = "thumbnail";
    static final String KEY_DURATION = "duration";

    // create interface listener
    public interface OnVideoSelectedListener{
        public void onVideoSelected(String ID);
    }

     @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            View view = inflater.inflate(R.layout.fragment_list, container, false);

            list = (ListView)view .findViewById(R.id.list);
            btnRefresh = (Button)view .findViewById(R.id.btnRefresh);

        menuItems = new ArrayList<HashMap<String, String>>();

        // get value that passed from previous page
        Bundle bundle = getArguments();
        position = bundle.getInt("position", 0);

        // get channel username and put selected channel to youtube api
        res = getActivity().getResources();
        ChannelUsername = res.getStringArray(R.array.channel_username);
        YOUTUBE_USERNAME = ChannelUsername[position];---->Error at Line 110

        YOUTUBE_API = "http://gdata.youtube.com/feeds/api/users/"+YOUTUBE_USERNAME+"/uploads?alt=jsonc" +
                "&v=2"+
                "&start-index=1"+
                "&max-results=10";

        // create LoadMore button
        btnLoadMore = new Button(getActivity());
        btnLoadMore.setBackgroundResource(R.drawable.btn_default_holo_light);
        btnLoadMore.setText(getString(R.string.load_more));

        // adding load more button to lisview at bottom
        list.addFooterView(btnLoadMore);

        new loadFirstListView().execute();

        // listener to handle load more buttton when clicked
        btnLoadMore.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // Starting a new async task
                isConnect = true;
                new loadMoreListView().execute();
            }
        });



        // listener to handle list when clicked
        list.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                    long arg3) {
                // TODO Auto-generated method stub
                HashMap<String, String> item = new HashMap<String, String>();
                item = menuItems.get(position);

                mCallback.onVideoSelected(item.get("id"));

                list.setItemChecked(position, true);
            }
        });

        // listener to handle refresh button when clicked
        btnRefresh.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                isConnect = true;
                new loadFirstListView().execute();
            }
        });
        return view;        
    }


@Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception.
        try {
            mCallback = (OnVideoSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnHeadlineSelectedListener");
        }
    }


    // load first 10 videos
    private class loadFirstListView extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            // Showing progress dialog before sending http request
            pDialog = new ProgressDialog(
                    getActivity());
            pDialog.setMessage("Please wait..");
            pDialog.setIndeterminate(true);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        protected Void doInBackground(Void... unused) {
            try {

                HttpClient client = new DefaultHttpClient();
                HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
                HttpConnectionParams.setSoTimeout(client.getParams(), 15000);

                // Perform a GET request to YouTube for a JSON list of all the videos by a specific user
                HttpUriRequest request = new HttpGet(YOUTUBE_API);
                // Get the response that YouTube sends back
                HttpResponse response = client.execute(request);
                // Convert this response into an inputstream for the parser to use
                InputStream atomInputStream = response.getEntity().getContent();


                 BufferedReader in = new BufferedReader(new InputStreamReader(atomInputStream));

                //BufferedReader in = new BufferedReader(new InputStreamReader(tc.getInputStream()));
                String line;
                String str = "";
                while ((line = in.readLine()) != null){
                    str += line;
                }


                    JSONObject json = new JSONObject(str);
                    JSONObject dataObject = json.getJSONObject("data"); // this is the "data": { } part
                    JSONArray items = dataObject.getJSONArray("items"); // this is the "items: [ ] part


                    for (int i = 0; i < items.length(); i++) {

                        HashMap<String, String> map = new HashMap<String, String>();
                        JSONObject youtubeObject = items.getJSONObject(i); 

                        map.put(KEY_ID, youtubeObject.getString("id")); // id not using any where
                        map.put(KEY_TITLE, youtubeObject.getString("title"));
                        map.put(KEY_THUMBNAIL, youtubeObject.getJSONObject("thumbnail").getString("hqDefault"));

                        String duration = secondToTime(youtubeObject.getInt("duration"));
                        map.put(KEY_DURATION, duration);

                        // adding HashList to ArrayList
                        menuItems.add(map);
                    }


            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                isConnect = false;
                e.printStackTrace();
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                    e.printStackTrace();
            }   

            return (null);
        }

        protected void onPostExecute(Void unused) {
            // closing progress dialog
            pDialog.dismiss();

            if(isAdded()){
                if(isConnect){
                    btnRefresh.setVisibility(View.GONE);
                    // Getting adapter
                    vla = new VideoListAdapter(getActivity(), menuItems);
                    list.setAdapter(vla);

                }else{
                    btnRefresh.setVisibility(View.VISIBLE);
                    Toast.makeText(getActivity(), getString(R.string.no_connection), Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    // load more videos
    private class loadMoreListView extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            // Showing progress dialog before sending http request
            pDialog = new ProgressDialog(
                    getActivity());
            pDialog.setMessage("Please wait..");
            pDialog.setIndeterminate(true);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        protected Void doInBackground(Void... unused) {

            // store previous value of current page
            previous_page = current_page;
            // increment current page
                    current_page += 10;

                    YOUTUBE_API = "http://gdata.youtube.com/feeds/api/users/"+YOUTUBE_USERNAME+"/uploads?alt=jsonc" +
                    "&v=2"+
                    "&start-index="+current_page+
                    "&max-results=10";

            try {

                HttpClient client = new DefaultHttpClient();
                HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
                HttpConnectionParams.setSoTimeout(client.getParams(), 15000);

                // Perform a GET request to YouTube for a JSON list of all the videos by a specific user
                HttpUriRequest request = new HttpGet(YOUTUBE_API);
                // Get the response that YouTube sends back
                HttpResponse response = client.execute(request);
                // Convert this response into an inputstream for the parser to use
                InputStream atomInputStream = response.getEntity().getContent();


                 BufferedReader in = new BufferedReader(new InputStreamReader(atomInputStream));

                //BufferedReader in = new BufferedReader(new InputStreamReader(tc.getInputStream()));
                String line;
                String str = "";
                while ((line = in.readLine()) != null){
                    str += line;
                }


                    JSONObject json = new JSONObject(str);
                    JSONObject dataObject = json.getJSONObject("data"); // this is the "data": { } part
                    JSONArray items = dataObject.getJSONArray("items"); // this is the "items: [ ] part


                    for (int i = 0; i < items.length(); i++) {

                        HashMap<String, String> map = new HashMap<String, String>();
                        JSONObject youtubeObject = items.getJSONObject(i); 

                        map.put(KEY_ID, youtubeObject.getString("id")); // id not using any where
                        map.put(KEY_TITLE, youtubeObject.getString("title"));
                        map.put(KEY_THUMBNAIL, youtubeObject.getJSONObject("thumbnail").getString("hqDefault"));

                        String duration = secondToTime(youtubeObject.getInt("duration"));
                        map.put(KEY_DURATION, duration);

                        // adding HashList to ArrayList
                        menuItems.add(map);
                    }


            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                isConnect = false;
                e.printStackTrace();
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }   



            return (null);
        }

        protected void onPostExecute(Void unused) {
            // closing progress dialog
            pDialog.dismiss();

            if(isConnect){
                // get listview current position - used to maintain scroll position
                int currentPosition = list.getFirstVisiblePosition();


                btnRefresh.setVisibility(View.GONE);
                // Appending new data to menuItems ArrayList
                vla = new VideoListAdapter(
                        getActivity(),
                        menuItems);
                list.setAdapter(vla);
                // Setting new scroll position
                list.setSelectionFromTop(currentPosition + 1, 0);

            }else{
                if(menuItems != null){
                    current_page = previous_page;
                    btnRefresh.setVisibility(View.GONE);
                }else{
                    btnRefresh.setVisibility(View.VISIBLE);
                }
                Toast.makeText(getActivity(), getString(R.string.no_connection), Toast.LENGTH_SHORT).show();
            }
        }
    }

    // method to convert second to hours, minutes, and seconds
    String secondToTime(int duration){

        String time = "";

        String Hours = "";
        String Minutes = "";
        String Seconds = "";

        double hours = 0.0;
        double minutes = 0.0;
        double seconds = 0.0;

        DecimalFormat df = new DecimalFormat("#.####");

        hours = duration / 3600;
        minutes = (duration % 3600) /60;
        seconds = duration % 60;

        if((hours < 10) && (hours > 0)){
            Hours = "0" + df.format(hours);
        }else if(hours == 0){
            Hours = "00";
        }else{
            Hours = df.format(hours);
        }

        if((minutes < 10) && (minutes > 0)){
            Minutes = "0" + df.format(minutes);
        }else if(minutes == 0){
            Minutes = "00";
        }else{
            Minutes = df.format(minutes);
        }

        if((seconds < 10) && (seconds > 0)){
            Seconds = "0" + df.format(seconds);
        }else if(seconds == 0){
            Seconds = "00";
        }else{
            Seconds = df.format(seconds);
        }

        time = Hours +":"+Minutes+":"+Seconds;
        return time;
    }

    @Override
    public void onDestroy() {

        super.onDestroy();
        vla.imageLoader.clearCache();
        Log.d("clear cache", "clear cache");

    }
}         

的strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">Loco</string>

    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string-array name="channel_name">
        <item >The Loco</item>

    </string-array>
    <string-array name="channel_username">
        <item >LOCOMEDIATVM</item>

    </string-array>
</resources>

编辑:

HomeActivity.java:

package com.sit.loco.activity;

import com.loco.android.R;
import com.sit.loco.frgment.VideoListFragment;

public class HomeActivity extends FragmentActivity 
implements ActionBar.OnNavigationListener, VideoListFragment.OnVideoSelectedListener{

// create object of ActionBar and VideoListFragment
ActionBar actionbar;
VideoListFragment videoListFrag;
int selectedItem;

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

    // add channel list array to actionbar spinner
    Context context = getSupportActionBar().getThemedContext();
    ArrayAdapter<CharSequence> list = ArrayAdapter.createFromResource(context, R.array.channel_name, R.layout.sherlock_spinner_item);
    list.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);

    // remove actionbar title and add spinner to actionbar
    getActionBar().setDisplayShowTitleEnabled(false);
    getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
    getActionBar().setListNavigationCallbacks(list, this);
}

@Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
    // TODO Auto-generated method stub

    selectedItem = itemPosition;

    // create object of VideoListFragment and send data position to that fragment
    videoListFrag = new VideoListFragment();
    Bundle bundle = new Bundle();
    bundle.putInt("position", itemPosition);
    videoListFrag.setArguments(bundle);

    // call video list fragment with new data
    getSupportFragmentManager()
    .beginTransaction()
    .replace(R.id.content_frame, videoListFrag, "VIDEO_LIST_FRAGMENT")
    .commit();
    return true;
}

@Override
public void onVideoSelected(String ID) {

    // call player page to play selected video
    Intent i = new Intent(this, PlayerActivity.class);
    i.putExtra("id", ID);
    startActivity(i);

}
}   

我不知道如何解决这个问题。任何人都可以帮助我。谢谢。

2 个答案:

答案 0 :(得分:1)

您的上一页错误排名:

Bundle bundle = getArguments();
position = bundle.getInt("position", 0);

虽然您可以添加支票

ChannelUsername = res.getStringArray(R.array.channel_username);
if (position > ChannelUsername.length()-1) {
    YOUTUBE_USERNAME = ChannelUsername[position];
}

你最好先弄清楚你为什么会在错误的位置发错。

答案 1 :(得分:0)

在VideoListFragment.java中:

我改变了这个

  

YOUTUBE_USERNAME = ChannelUsername [position]; ----&gt;第110行的错误

  

YOUTUBE_USERNAME = ChannelUsername [0];

为什么我将此位置设置为0表示我只有一个通道user_name。