本篇文章为大家展示了在Android应用中读取SD卡文件时程序NullPointerException报错如何解决,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。Android 中读取SD卡文件时抛出
本篇文章为大家展示了在Android应用中读取SD卡文件时程序NullPointerException报错如何解决,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。
Android 中读取SD卡文件时抛出NullPointerException错误解决办法
相关源码:
package com.example.musicplayer;import java.io.File;import java.util.ArrayList;import java.util.List;import android.app.Activity;import android.os.Bundle;import android.os.Environment;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.view.ViewGroup;import android.widget.BaseAdapter;import android.widget.ListView;import android.widget.TextView;import android.widget.Toast;public class MainActivity extends Activity { private ListView listView; private final String path = "/storage/sdcard/mp3/"; private List<String> musicList; private ViewHolder viewHolder; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView = (ListView) findViewById(R.id.lv_music); Toast.makeText(getApplicationContext(), path, Toast.LENGTH_SHORT).show(); initMusic(); } private void initMusic() { File file = new File(path); File[] files = file.listFiles(); musicList = new ArrayList<String>(); for (File f : files) { if (f.getName().endsWith(".mp3")) { musicList.add(f.getAbsolutePath()); } } listView.setAdapter(new MusicListAdapter()); } private class MusicListAdapter extends BaseAdapter{ @Override public int getCount() { return musicList.size(); } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = null; if(convertView == null){ view = View.inflate(getApplicationContext(), R.layout.activity_music_item, null); viewHolder = new ViewHolder(); viewHolder.musicName = (TextView) view.findViewById(R.id.tv_music_name); } else { view = convertView; } String path = musicList.get(position); viewHolder.musicName.setText(path.substring(path.lastIndexOf("/") + 1)); return view; } @Override public Object getItem(int position) { // TODO Auto-generated method stub return null; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return 0; } }}
--结束END--
本文标题: 在Android应用中读取SD卡文件时程序NullPointerException报错如何解决
本文链接: https://lsjlt.com/news/223137.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0