Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting java.lang.ArrayIndexOutOfBoundsException in android

I am using pinned-section-listview from here and getting following error after scrolling,

07-31 17:52:46.640: E/InputEventReceiver(25288): Exception dispatching input event.
07-31 17:52:46.657: E/AndroidRuntime(25288): FATAL EXCEPTION: main
07-31 17:52:46.657: E/AndroidRuntime(25288): java.lang.ArrayIndexOutOfBoundsException: length=2; index=2
07-31 17:52:46.657: E/AndroidRuntime(25288):    at android.widget.AbsListView$RecycleBin.addScrapView(AbsListView.java:6916)
07-31 17:52:46.657: E/AndroidRuntime(25288):    at android.widget.AbsListView.trackMotionScroll(AbsListView.java:5442)
07-31 17:52:46.657: E/AndroidRuntime(25288):    at android.widget.AbsListView.scrollIfNeeded(AbsListView.java:3310)
07-31 17:52:46.657: E/AndroidRuntime(25288):    at android.widget.AbsListView.onTouchEvent(AbsListView.java:3654)
07-31 17:52:46.657: E/AndroidRuntime(25288):    at android.view.View.dispatchTouchEvent(View.java:7143)
07-31 17:52:46.657: E/AndroidRuntime(25288):    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2238)
07-31 17:52:46.657: E/AndroidRuntime(25288):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1935)
07-31 17:52:46.657: E/AndroidRuntime(25288):    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2244)
07-31 17:52:46.657: E/AndroidRuntime(25288):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1949)
07-31 17:52:46.657: E/AndroidRuntime(25288):    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2244)
07-31 17:52:46.657: E/AndroidRuntime(25288):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1949)
07-31 17:52:46.657: E/AndroidRuntime(25288):    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2244)
07-31 17:52:46.657: E/AndroidRuntime(25288):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1949)
07-31 17:52:46.657: E/AndroidRuntime(25288):    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2244)
07-31 17:52:46.657: E/AndroidRuntime(25288):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1949)
07-31 17:52:46.657: E/AndroidRuntime(25288):    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2244)
07-31 17:52:46.657: E/AndroidRuntime(25288):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1949)
07-31 17:52:46.657: E/AndroidRuntime(25288):    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2244)
07-31 17:52:46.657: E/AndroidRuntime(25288):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1949)
07-31 17:52:46.657: E/AndroidRuntime(25288):    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2244)
07-31 17:52:46.657: E/AndroidRuntime(25288):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1949)
07-31 17:52:46.657: E/AndroidRuntime(25288):    at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2244)
07-31 17:52:46.657: E/AndroidRuntime(25288):    at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1949)
07-31 17:52:46.657: E/AndroidRuntime(25288):    at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1938)
07-31 17:52:46.657: E/AndroidRuntime(25288):    at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1392)
07-31 17:52:46.657: E/AndroidRuntime(25288):    at android.app.Activity.dispatchTouchEvent(Activity.java:2408)
07-31 17:52:46.657: E/AndroidRuntime(25288):    at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1886)
07-31 17:52:46.657: E/AndroidRuntime(25288):    at android.view.View.dispatchPointerEvent(View.java:7323)
07-31 17:52:46.657: E/AndroidRuntime(25288):    at android.view.ViewRootImpl.deliverPointerEvent(ViewRootImpl.java:3560)
07-31 17:52:46.657: E/AndroidRuntime(25288):    at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:3490)
07-31 17:52:46.657: E/AndroidRuntime(25288):    at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:4637)
07-31 17:52:46.657: E/AndroidRuntime(25288):    at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:4597)
07-31 17:52:46.657: E/AndroidRuntime(25288):    at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:4749)
07-31 17:52:46.657: E/AndroidRuntime(25288):    at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:171)
07-31 17:52:46.657: E/AndroidRuntime(25288):    at android.view.InputEventReceiver.nativeConsumeBatchedInputEvents(Native Method)
07-31 17:52:46.657: E/AndroidRuntime(25288):    at android.view.InputEventReceiver.consumeBatchedInputEvents(InputEventReceiver.java:163)
07-31 17:52:46.657: E/AndroidRuntime(25288):    at android.view.ViewRootImpl.doConsumeBatchedInput(ViewRootImpl.java:4717)
07-31 17:52:46.657: E/AndroidRuntime(25288):    at android.view.ViewRootImpl$ConsumeBatchedInputRunnable.run(ViewRootImpl.java:4771)
07-31 17:52:46.657: E/AndroidRuntime(25288):    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:747)
07-31 17:52:46.657: E/AndroidRuntime(25288):    at android.view.Choreographer.doCallbacks(Choreographer.java:567)
07-31 17:52:46.657: E/AndroidRuntime(25288):    at android.view.Choreographer.doFrame(Choreographer.java:534)
07-31 17:52:46.657: E/AndroidRuntime(25288):    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:733)
07-31 17:52:46.657: E/AndroidRuntime(25288):    at android.os.Handler.handleCallback(Handler.java:615)
07-31 17:52:46.657: E/AndroidRuntime(25288):    at android.os.Handler.dispatchMessage(Handler.java:92)
07-31 17:52:46.657: E/AndroidRuntime(25288):    at android.os.Looper.loop(Looper.java:153)
07-31 17:52:46.657: E/AndroidRuntime(25288):    at android.app.ActivityThread.main(ActivityThread.java:5034)
07-31 17:52:46.657: E/AndroidRuntime(25288):    at java.lang.reflect.Method.invokeNative(Native Method)
07-31 17:52:46.657: E/AndroidRuntime(25288):    at java.lang.reflect.Method.invoke(Method.java:511)
07-31 17:52:46.657: E/AndroidRuntime(25288):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:821)
07-31 17:52:46.657: E/AndroidRuntime(25288):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
07-31 17:52:46.657: E/AndroidRuntime(25288):    at dalvik.system.NativeStart.main(Native Method)


package com.benego.Fragment;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import android.content.Context;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.AndroidCharacter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.benego.AppCache;
import com.benego.MainActivity;
import com.benego.PinnedSectionListView.PinnedSectionListAdapter;
import com.benego.R;
import com.benego.Entity.LocalPhraseInfo;
import com.benego.Model.LocalPhraseModel;

public class PhraseResultFragment extends BaseFragment {
    private String CategoryID = null;
    //private String CategoryName = null;

    public final String SOURCE_HOME = "home";
    public final String SOURCE_NEARBY_VENUE = "nbv";
    public final String SOURCE_NEARBY_SUB_CATEGORY = "nbsc";

    private LocalPhraseResultAdapter adapter = null;
    private List<LocalPhraseInfo> phrases = null;

    public String getBundleString(String key, String defaultValue) {
        if (getArguments().containsKey(key))
            return getArguments().getString(key);
        else
            return defaultValue;
    }

    /**
     * When creating, retrieve this instance's number from its arguments.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.phraseresult_fragment, container,
                false);

        //View v = super.onCreateView(inflater, container, savedInstanceState);

        SearchFragment search_fragment = (SearchFragment)getActivity().getSupportFragmentManager().findFragmentById(R.id.phraseresultsearchfragment);
        search_fragment.resultFragmemt = this;

        LocalPhraseModel model = new LocalPhraseModel();
        phrases = null;

        String fromPage = getBundleString("from", SOURCE_HOME);

        if (fromPage == SOURCE_HOME)
        {
            CategoryID = getBundleString("CategoryID", "all");
            //CategoryName = getArguments().getString("CategoryName", "All");
            search_fragment.categoryId = CategoryID;
            phrases = model.GetPhrases(CategoryID, null);
        }
        else if (fromPage == SOURCE_NEARBY_SUB_CATEGORY)
        {
            String fsSubCategoryID = getBundleString("SubCategoryID", "all");
            search_fragment.subCategoryId = fsSubCategoryID;
            phrases = model.GetPhrasesBySubCategoryID(fsSubCategoryID, null);
        }
        else if (fromPage == SOURCE_NEARBY_VENUE)
        {
            String[] subCategoryIds = getArguments().getStringArray("SubCategoryIDs");
            search_fragment.subCategoryIds = subCategoryIds;
            phrases = model.GetPhrasesBySubCategoryIDs(subCategoryIds, null);
        }

        ListView listView = (ListView) v.findViewById(android.R.id.list);
        adapter = new LocalPhraseResultAdapter(getActivity().getApplicationContext(), phrases);
        listView.setAdapter(adapter);

        return v;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
      super.onActivityCreated(savedInstanceState);
    }   

    @Override
    public void onDestroyView() {
        super.onDestroyView(); 

        try {
            Fragment fragment = getActivity().getSupportFragmentManager().findFragmentById(R.id.phraseresultsearchfragment);
            FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
            ft.remove(fragment);
            ft.commit();
        }
        catch (Exception e) {
        }
    }   


    public void PlayAudio(int phraseID){
        //set up MediaPlayer    
        try {
            LocalPhraseModel model = new LocalPhraseModel(); 
            byte[] audio = model.GetAudio(phraseID);
            if (audio != null)
            {
                File tempMp3 = File.createTempFile(String.valueOf(phraseID), ".mp3", getActivity().getCacheDir());
                tempMp3.deleteOnExit();
                FileOutputStream fos = new FileOutputStream(tempMp3);
                fos.write(audio);
                fos.close();

                final FileInputStream fs = new FileInputStream(tempMp3);
                FileDescriptor fd = fs.getFD();

                MediaPlayer mp = new MediaPlayer();
                mp.setDataSource(fd);
                mp.prepare();
                mp.start();
                mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        try {
                            fs.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void RefreshView(List<LocalPhraseInfo> results)
    {
        this.adapter.setListData(results);
    }

    public class LocalPhraseResultAdapter extends BaseAdapter implements PinnedSectionListAdapter {
        private Context mContext;
        private List<LocalPhraseInfo> _results = null;

        public LocalPhraseResultAdapter(Context c, List<LocalPhraseInfo> phrases) {
            mContext = c;
            this.setResults(phrases);       
        }

        public int getCount() {
            int size = this._results.size();
            return size;
        }

        public Object getItem(int position) {
            return _results.get(position);
        }

        public long getItemId(int position) {
            return position;
        }

        private void setListData( List<LocalPhraseInfo> newListData ) {
            this.setResults(newListData);
            notifyDataSetChanged();
        }//met

        public View getView(int position, View convertView, ViewGroup parent) {
            View cView;
            if (convertView == null) { // if it's not recycled, initialize some
                                        // attributes
                cView = LayoutInflater.from(mContext).inflate(
                        R.layout.phraseresult_item, null);
            } else {
                cView = convertView;
            }

            LocalPhraseInfo pInfo = _results.get(position);
            cView.setTag(pInfo);

            if (pInfo.getPhraseID() > 0)
            {
                cView.findViewById(R.id.phraseresult_row).setVisibility(View.VISIBLE);
                cView.findViewById(R.id.phraseresult_section).setVisibility(View.GONE);

                cView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        LocalPhraseInfo pInfo = (LocalPhraseInfo)v.getTag();
                        PlayAudio(pInfo.getPhraseID());
                    }
                });

                TextView txtNativeView = (TextView) cView.findViewById(R.id.nativePhraseView);
                TextView txtTranslationView = (TextView) cView.findViewById(R.id.translationPhraseView);

                txtNativeView.setText(pInfo.getNativePhrase());
                txtTranslationView.setText(pInfo.getTranslationPhrase());

                ImageView sv = (ImageView)cView.findViewById(R.id.phraseSoundIcon);
                if (pInfo.getIsSoundClipExists())
                    sv.setVisibility(View.VISIBLE);

                ImageButton detailBtn = (ImageButton)cView.findViewById(R.id.btnphraseDetail);
                if (pInfo.getHasRelatedPhrases() || pInfo.getIsRootPhrase())
                {
                    detailBtn.setVisibility(View.VISIBLE);
                    detailBtn.setTag(pInfo);

                    detailBtn.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            LocalPhraseInfo pInfo = (LocalPhraseInfo)v.getTag();

                            Bundle args = new Bundle();
                            args.putString("from", "home");
                            args.putSerializable("Phrase", pInfo);

                            MainActivity mainActivity = (MainActivity)getActivity();
                            mainActivity.addFragment(mainActivity.LOCAL_TAB, PhraseDetailFragment.class, args);
                        }
                    });
                }
            }
            else
            {
                cView.findViewById(R.id.phraseresult_row).setVisibility(View.GONE);
                cView.findViewById(R.id.phraseresult_section).setVisibility(View.VISIBLE);
                TextView txtSectionView = (TextView)cView.findViewById(R.id.phraseresult_section_text);
                txtSectionView.setText(pInfo.getSubCategoryName());
            }

            return cView;
        }

        @Override public int getViewTypeCount() {
            return 2;
        }

        @Override public int getItemViewType(int position) {
            LocalPhraseInfo info = (LocalPhraseInfo)getItem(position);
            if (info.getPhraseID() > 0)
                return 2;
            else
                return 1;
        }

        @Override public boolean isItemViewTypePinned(int viewType) {
            return viewType == 1;
        }

        private void setResults(List<LocalPhraseInfo> results)
        {
            List<LocalPhraseInfo> sectioned = new ArrayList<LocalPhraseInfo>();

            String key = null; 
            Iterator<LocalPhraseInfo> localIterator = results.iterator();
            while (localIterator.hasNext()) {
                LocalPhraseInfo info = localIterator.next();
                if (key == null || !key.endsWith(info.getSubCategoryName()))
                {
                    key = info.getSubCategoryName();
                    sectioned.add(this.getSectionPhraseInfo(info));
                }

                sectioned.add(info);
            }

            this._results = sectioned;
        }

        private LocalPhraseInfo getSectionPhraseInfo(LocalPhraseInfo phrase)
        {
            LocalPhraseInfo info = new LocalPhraseInfo();
            info.setSubCategoryID(phrase.getSubCategoryID());
            info.setSubCategoryName(phrase.getSubCategoryName());
            return info;
        }
    }
}

Please help me. I am struggling from last two days.

like image 979
Pravin Patil Avatar asked Jul 31 '13 12:07

Pravin Patil


People also ask

How do I get rid of java Lang ArrayIndexOutOfBoundsException?

In order to avoid the java. lang. ArrayIndexOutOfBoundsException, you should always do the bound check before accessing array element e.g. Always remember that the array index starts at 0 and not 1 and an empty array has no element in it.

What is java Lang ArrayIndexOutOfBoundsException?

java.lang.ArrayIndexOutOfBoundsException. Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.

What type of error is ArrayIndexOutOfBoundsException?

The ArrayIndexOutOfBoundsException is a Runtime Exception thrown only at runtime. The Java Compiler does not check for this error during the compilation of a program.

At which point of execution does the ArrayIndexOutOfBoundsException occur?

The java. lang. ArrayIndexOutOfBoundsException is a runtime exception and thrown only at the execution state of the program.


2 Answers

If you read closely the getItemViewType method documentation, it says :

Integers must be in the range 0 to getViewTypeCount() - 1

In your case, in the range [0, 1]

like image 200
njzk2 Avatar answered Nov 15 '22 10:11

njzk2


You have-

if (info.getPhraseID() > 0)
  return 2;
else
  return 1;

Shouldn't it be-

if (info.getPhraseID() > 0)
  return 1;
else
  return 0;
like image 32
Sajal Dutta Avatar answered Nov 15 '22 12:11

Sajal Dutta