在使用ListViews和Custom ArrayAdapter实现Fragment后,应用程序不断崩溃

时间:2017-10-18 07:42:36

标签: android listview android-fragments android-arrayadapter android-contentresolver

我正在制作一个带有三个TabLayouts(使用片段)的MusicPlayer应用程序和一个带有从基本适配器扩展的自定义阵列适配器的Listview。

在内容解析器和Uris的帮助下显示歌曲。

但是每当我尝试运行应用程序时,应用程序都会崩溃。 我不知道是什么问题。

这是我的SongAdapter(ArrayAdapter).java

    import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;

public class SongAdapter extends BaseAdapter {

    private ArrayList<Song> songs;
    private LayoutInflater songInf;

    public SongAdapter(Context c, ArrayList<Song> theSongs){
        songs=theSongs;
        songInf=LayoutInflater.from(c);
    }

    @Override
    public int getCount() {
        return songs.size();
    }

    @Override
    public Object getItem(int i) {
        return null;
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }


    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        //map to song layout
        LinearLayout songLay = (LinearLayout)songInf.inflate
                (R.layout.songviewer, parent, false);
        //get title and artist views
        TextView songView = (TextView)songLay.findViewById(R.id.song_title);
        TextView artistView = (TextView)songLay.findViewById(R.id.song_artist);
        //get song using position
        Song currSong = songs.get(position);
        //get title and artist strings
        songView.setText(currSong.getTitle());
        artistView.setText(currSong.getArtist());
        //set position as tag
        songLay.setTag(position);
        return songLay;
    }
}

MainActivity.java

MainActivity.java要求从设备外部存储设备中获取歌曲的权限。

public class MainActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;

    // a static variable to get a reference of our application context
    public static Context contextOfApplication;
    public static Context getContextOfApplication()
    {
        return contextOfApplication;
    }

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

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {

                requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},1);

                // MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE is an
                // app-defined int constant

                return;
            }}

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        viewPager = (ViewPager) findViewById(R.id.container);
        setupViewPager(viewPager);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);

        contextOfApplication = getApplicationContext();

    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new ListSong(), "SONGS");
        adapter.addFragment(new GridAlbum(), "ALBUMS");
        viewPager.setAdapter(adapter);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }
}

ListSong.java 它是具有列表视图并显示歌曲的三个片段之一。

public class ListSong extends Fragment {

    private ArrayList<Song> songList;
    private ListView songView;

    Context applicationContext = MainActivity.getContextOfApplication();

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

        songView = (ListView)rootView.findViewById(R.id.songsList);
        songList = new ArrayList<Song>();

        getSongList();

        SongAdapter songAdt = new SongAdapter(getActivity(), songList);
        songView.setAdapter(songAdt);

        return rootView;

    }

    public void getSongList(){
        ContentResolver musicResolver = applicationContext.getContentResolver();
        Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);
        if(musicCursor!=null && musicCursor.moveToFirst()){
            //get columns
            int titleColumn = musicCursor.getColumnIndex
                    (android.provider.MediaStore.Audio.Media.TITLE);
            int idColumn = musicCursor.getColumnIndex
                    (android.provider.MediaStore.Audio.Media._ID);
            int artistColumn = musicCursor.getColumnIndex
                    (android.provider.MediaStore.Audio.Media.ARTIST);
            //add songs to list
            do {
                long thisId = musicCursor.getLong(idColumn);
                String thisTitle = musicCursor.getString(titleColumn);
                String thisArtist = musicCursor.getString(artistColumn);
                songList.add(new Song(thisId, thisTitle, thisArtist));
            }
            while (musicCursor.moveToNext());
        }
    }

}

这是我的错误日志。

1/data/app/com.example.adityaverma.practicemusic-2/split_lib_slice_9_apk.apk
10-18 13:18:41.254 22970-22970/com.example.adityaverma.practicemusic I/art: jiangtaottt OpenDexFilesFromOat open_oat_file.get() == nullptr 3  /data/dalvik-cache/arm64/data@app@com.example.adityaverma.practicemusic-2@split_lib_slice_9_apk.apk@classes.dex   /data/app/com.example.adityaverma.practicemusic-2/split_lib_slice_9_apk.apk
10-18 13:18:41.254 22970-22970/com.example.adityaverma.practicemusic E/System: elements.add : /data/app/com.example.adityaverma.practicemusic-2/split_lib_slice_9_apk.apk  /data/app/com.example.adityaverma.practicemusic-2/split_lib_slice_9_apk.apk   /data/app/com.example.adityaverma.practicemusic-2/split_lib_slice_9_apk.apk
10-18 13:18:41.263 22970-22970/com.example.adityaverma.practicemusic I/InstantRun: starting instant run server: is main process
10-18 13:18:41.452 22970-22970/com.example.adityaverma.practicemusic W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
10-18 13:18:41.472 22970-22989/com.example.adityaverma.practicemusic W/art: Suspending all threads took: 9.127ms
10-18 13:18:41.476 22970-22989/com.example.adityaverma.practicemusic I/art: Background sticky concurrent mark sweep GC freed 2354(280KB) AllocSpace objects, 0(0B) LOS objects, 17% free, 951KB/1154KB, paused 10.617ms total 58.260ms
10-18 13:18:41.483 22970-22989/com.example.adityaverma.practicemusic W/art: Suspending all threads took: 6.912ms
10-18 13:18:41.520 22970-22970/com.example.adityaverma.practicemusic D/wangcy9: setStatusIcon occur wrong theme!
10-18 13:18:41.568 22970-22989/com.example.adityaverma.practicemusic W/art: Suspending all threads took: 6.977ms
10-18 13:18:41.572 22970-22989/com.example.adityaverma.practicemusic I/art: Background partial concurrent mark sweep GC freed 875(282KB) AllocSpace objects, 0(0B) LOS objects, 47% free, 1149KB/2MB, paused 8.290ms total 47.849ms
10-18 13:18:41.826 22970-22970/com.example.adityaverma.practicemusic I/ViewRootImpl: CPU Rendering VSync enable = true
10-18 13:18:41.829 22970-23142/com.example.adityaverma.practicemusic D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
10-18 13:18:41.837 22970-22970/com.example.adityaverma.practicemusic D/Atlas: Validating map...
10-18 13:18:41.909 22970-22970/com.example.adityaverma.practicemusic D/AndroidRuntime: Shutting down VM
10-18 13:18:41.913 22970-22970/com.example.adityaverma.practicemusic E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                       Process: com.example.adityaverma.practicemusic, PID: 22970
                                                                                       java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.ContentResolver android.content.Context.getContentResolver()' on a null object reference
                                                                                           at com.example.adityaverma.practicemusic.ListSong.getSongList(ListSong.java:44)
                                                                                           at com.example.adityaverma.practicemusic.ListSong.onCreateView(ListSong.java:34)
                                                                                           at android.support.v4.app.Fragment.performCreateView(Fragment.java:2239)
                                                                                           at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1332)
                                                                                           at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1574)
                                                                                           at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1641)
                                                                                           at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:794)
                                                                                           at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2415)
                                                                                           at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2200)
                                                                                           at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2153)
                                                                                           at android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:2034)
                                                                                           at android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:651)
                                                                                           at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:143)
                                                                                           at android.support.v4.view.ViewPager.populate(ViewPager.java:1239)
                                                                                           at android.support.v4.view.ViewPager.populate(ViewPager.java:1087)
                                                                                           at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1613)
                                                                                           at android.view.View.measure(View.java:17565)
                                                                                           at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5545)
                                                                                           at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:713)
                                                                                           at android.support.design.widget.HeaderScrollingViewBehavior.onMeasureChild(HeaderScrollingViewBehavior.java:90)
                                                                                           at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onMeasureChild(AppBarLayout.java:1389)
                                                                                           at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:783)
                                                                                           at android.view.View.measure(View.java:17565)
                                                                                           at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5545)
                                                                                           at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
                                                                                           at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)
                                                                                           at android.view.View.measure(View.java:17565)
                                                                                           at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5545)
                                                                                           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:17565)
                                                                                           at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5545)
                                                                                           at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
                                                                                           at android.view.View.measure(View.java:17565)
                                                                                           at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5545)
                                                                                           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:17565)
                                                                                           at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5545)
                                                                                           at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
                                                                                           at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2652)
                                                                                           at android.view.View.measure(View.java:17565)
                                                                                           at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2030)
                                                                                           at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1185)
                                                                                           at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1392)
                                                                                           at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1073)
                                                                                           at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5906)
                                                                                           at android.view.Choreographer$CallbackRecord.run(Choreographer.java:828)
                                                                                        at android.view.Choreographer.doCallbacks(Choreographer.ja
10-18 13:19:00.841 22970-22970/? I/Process: Sending signal. PID: 22970 SIG: 9

1 个答案:

答案 0 :(得分:0)

ListSong课程中 - &gt; getSongList()方法,请指定以下代码行:

ContentResolver musicResolver = getActivity().getContentResolver();

而不是

ContentResolver musicResolver = applicationContext.getContentResolver();