我遇到问题,因为我使用自定义适配器。我总是得到空适配器。似乎我为他们添加了错误的上下文,但我尝试在onActivityCreated中初始化我的适配器,因为它在工作示例中具有几乎相同的功能,具有不同的上下文,只有可用,并且我得到“没有封闭的类型实例.... ”。那么我应该在哪里以及如何初始化我的适配器。
那是我的VideoList代码:
private static final String TAG = VideoListLoader.class.getName();
VideoListFragment list;
VideoListAdapter mAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FragmentManager fm = getSupportFragmentManager();
// Create the list fragment and add it as our sole content.
if (fm.findFragmentById(android.R.id.content) == null) {
list = new VideoListFragment();
fm.beginTransaction().add(android.R.id.content, list).commit();
}
}
public static class VideoEntry {
private final JSONObject mItem;
private String mTitle, mThumbURL, mVideoID;
public VideoEntry(JSONObject item) {
mItem = item;
}
public String getVideoID() {
return mThumbURL;
}
public String getTitle() {
return mTitle;
}
public String getThumbURL() {
return mVideoID;
}
void wrapID(Context context) throws JSONException {
if (mVideoID == null) {
mVideoID = mItem.getJSONObject("video").getString("id");
}
}
void wrapTitle(Context context) throws JSONException {
if (mTitle == null) {
mTitle = mItem.getJSONObject("video").getString("title");
}
}
void wrapThumbURL(Context context) throws JSONException {
if (mThumbURL == null) {
mThumbURL = mItem.getJSONObject("video").getJSONObject("thumbnail").getString("sqDefault");
}
}
}
public static class VideoListFragment extends SherlockListFragment implements LoaderCallbacks<RESTLoader.RESTResponse> {
private static final int LOADER_YOUTUBE_SEARCH = 0x1;
VideoListAdapter mAdapter;
private static final String ARGS_URI = "net.neilgoodman.android.restloadertutorial.ARGS_URI";
private static final String ARGS_PARAMS = "net.neilgoodman.android.restloadertutorial.ARGS_PARAMS";
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Let's set our list adapter to a simple ArrayAdapter.
mAdapter = VideoListLoader.new VideoListAdapter(getSherlockActivity());
setListAdapter(mAdapter);
setListShown(false);
// This is our REST action.
Uri youtubeSearchUri = Uri.parse("https://gdata.youtube.com/feeds/api/playlists/EC6gx4Cwl9DGAdmjrf1RaZIJe2_3fGbhbu");
// Here we are going to place our REST call parameters. Note that
// we could have just used Uri.Builder and appendQueryParameter()
// here, but I wanted to illustrate how to use the Bundle params.
Bundle params = new Bundle();
params.putString("max-result", "20");
params.putString("alt", "jsonc");
params.putString("v", "2");
// These are the loader arguments. They are stored in a Bundle
// because
// LoaderManager will maintain the state of our Loaders for us and
// reload the Loader if necessary. This is the whole reason why
// we have even bothered to implement RESTLoader.
Bundle args = new Bundle();
args.putParcelable(ARGS_URI, youtubeSearchUri);
args.putParcelable(ARGS_PARAMS, params);
// Initialize the Loader.
getLoaderManager().initLoader(LOADER_YOUTUBE_SEARCH, args, this);
}
@Override
public Loader<RESTLoader.RESTResponse> onCreateLoader(int id, Bundle args) {
if (args != null && args.containsKey(ARGS_URI) && args.containsKey(ARGS_PARAMS)) {
Uri action = args.getParcelable(ARGS_URI);
Bundle params = args.getParcelable(ARGS_PARAMS);
return new RESTLoader(getSherlockActivity(), RESTLoader.HTTPVerb.GET, action, params);
}
return null;
}
@Override
public void onLoadFinished(Loader<RESTLoader.RESTResponse> loader, RESTLoader.RESTResponse data) {
int code = data.getCode();
String json = data.getData();
Log.e("JSON: ", json);
// Check to see if we got an HTTP 200 code and have some data.
if (code == 200 && !json.equals("")) {
List<VideoEntry> playlists = getPlaylistsFromJson(getSherlockActivity(), json);
Log.e("Full Playlists: ", playlists.get(3).getTitle().toString());
mAdapter.setData(playlists);
Log.e("Lo: ", "Lolo");
if (isResumed()) {
setListShown(true);
} else {
setListShownNoAnimation(true);
}
} else {
Toast.makeText(getSherlockActivity(), "Failed to load data. Check your internet settings.", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onLoaderReset(Loader<RESTLoader.RESTResponse> loader) {
mAdapter.setData(null);
}
private static List<VideoEntry> getPlaylistsFromJson(FragmentActivity fragmentActivity, String json) {
List<VideoEntry> playlistsList = new ArrayList<VideoEntry>();
final Context context = fragmentActivity.getApplicationContext();
try {
JSONObject playlistsWrapper = (JSONObject) new JSONTokener(json).nextValue();
JSONArray playlists = playlistsWrapper.getJSONObject("data").getJSONArray("items");
for (int i = 0; i < playlists.length(); i++) {
JSONObject playlist = playlists.getJSONObject(i);
VideoEntry entry = new VideoEntry(playlist);
entry.wrapID(context);
entry.wrapTitle(context);
entry.wrapThumbURL(context);
playlistsList.add(entry);
Log.e("PlaylistsList: ", playlistsList.get(i).getTitle().toString());
}
} catch (JSONException e) {
Log.e(TAG, "Failed to parse JSON.", e);
}
return playlistsList;
}
}
}
我的适配器(数据发送到setData()时出现异常,然后一切正常):
public class VideoListAdapter extends ArrayAdapter<VideoEntry> {
public ViewHolder holder;
ImageLoader imageLoader = ImageLoader.getInstance();
private final LayoutInflater mInflater;
public VideoListAdapter(Context context) {
super(context, android.R.layout.simple_list_item_2);
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
File cacheDir = StorageUtils.getOwnCacheDirectory(context, "StrongRunner/Cache");
DisplayImageOptions options = new DisplayImageOptions.Builder().showStubImage(R.drawable.btn_start).showImageForEmptyUri(R.drawable.ic_launcher)
.resetViewBeforeLoading().cacheInMemory().cacheOnDisc().build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context).threadPoolSize(5).threadPriority(Thread.MIN_PRIORITY + 2)
.denyCacheImageMultipleSizesInMemory().offOutOfMemoryHandling().discCache(new UnlimitedDiscCache(cacheDir)).defaultDisplayImageOptions(options).build();
ImageLoader.getInstance().init(config);
}
public void setData(List<VideoEntry> data) {
Log.e("Log", data.get(3).getTitle().toString());
clear();
if (data != null) {
Log.e("Data: ", data.get(5).getTitle().toString());
for (VideoEntry videoEntry : data) {
add(videoEntry);
}
}
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.video_custom_view, parent, false);
holder = new ViewHolder();
holder.title = (TextView) convertView.findViewById(R.id.tv_VideoTitle);
holder.ivThumb = (ImageView) convertView.findViewById(R.id.im_vThumb);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
VideoEntry video = getItem(position);
Log.e("LogView: ", video.getVideoID().toString());
holder.id = video.getVideoID().toString();
holder.title.setText(video.getTitle().toString());
imageLoader.displayImage(video.getThumbURL().toString(), holder.ivThumb);
return convertView;
}
public class ViewHolder {
public String id;
public ImageView ivThumb;
public TextView title;
}
}
日志:
10-10 15:00:29.143: E/JSON:(18761): {"apiVersion":"2.1","data":{"id":"PL6gx4Cwl9DGAdmjrf1RaZIJe2_3fGbhbu","author":"thenewboston","title":"Biology Lecture Playlist","description":"Official Playlist for thenewboston Biology Lecture videos!","thumbnail":{"sqDefault":"http://i.ytimg.com/vi/3w1fY67dnFI/default.jpg","hqDefault":"http://i.ytimg.com/vi/3w1fY67dnFI/hqdefault.jpg"},"content":{"5":"http://www.youtube.com/p/PL6gx4Cwl9DGAdmjrf1RaZIJe2_3fGbhbu"},"totalItems":60,"startIndex":1,"itemsPerPage":25,"items":[{"id":"ECjsdPXfMXpAvLTnVs3EOXH-eAiWdD3arb","position":1,"author":"thenewboston","video":{"id":"3w1fY67dnFI","uploaded":"2012-09-05T01:45:45.000Z","updated":"2012-10-09T15:17:17.000Z","uploader":"thenewboston","category":"Education","title":"Biology Lecture - 1 - Introduction to Biology","description":"Visit my website at http://thenewboston.com for all of my videos! \n\nMy Google+ - https://plus.google.com/108291790892450338168/posts\nMy Facebook - http://www.facebook.com/pages/TheNewBoston/464114846956315\nMy Twitter - http://twitter.com/#!/bucky_roberts\nMy Other YouTube Channel - http://www.youtube.com/thenewbostontv\nDonate - https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=5K9RJVCAKWZKS","thumbnail":{"sqDefault":"http://i.ytimg.com/vi/3w1fY67dnFI/default.jpg","hqDefault":"http://i.ytimg.com/vi/3w1fY67dnFI/hqdefault.jpg"},"player":{"default":"https://www.youtube.com/watch?v=3w1fY67dnFI&feature=youtube_gdata_player","mobile":"https://m.youtube.com/details?v=3w1fY67dnFI"},"content":{"5":"https://www.youtube.com/v/3w1fY67dnFI?version=3&f=playlists&app=youtube_gdata","1":"rtsp://v5.cache8.c.youtube.com/CiULENy73wIaHAlSnN2uY18N3xMYDSANFEgGUglwbGF5bGlzdHMM/0/0/0/video.3gp","6":"rtsp://v7.cache6.c.youtube.com/CiULENy73wIaHAlSnN2uY18N3xMYESARFEgGUglwbGF5bGlzdHMM/0/0/0/video.3gp"},"duration":261,"aspectRatio":"widescreen","rating":4.849624,"likeCount":"128","ratingCount":133,"viewCount":16663,"favoriteCount":0,"commentCount":88,"accessControl":{"comment":"allowed","commentVote":"allowed","videoRespond":"moderated","rate":"allowed","embed":"allowed","list":"allowed","autoPlay":"allowed","syndicate":"allowed"}}},{"id":"ECjsdPXfMXpAvvWbBWfRAyDxBDOzpN-q9O","position":2,"author":"thenewboston","video":{"id":"zcHBT6QFIqk","uploaded":"2012-09-05T01:45:56.000Z","updated":"2012-10-08T02:49:52.000Z","uploader":"thenewboston","category":"Education","title":"Biology Lecture - 2 - What is Life?","description":"Visit my website at http://thenewboston.com for all of my videos! \n\nMy Google+ - https://plus.google.com/108291790892450338168/posts\nMy Facebook - http://www.facebook.com/pages/TheNewBoston/464114846956315\nMy Twitter - http://twitter.com/#!/bucky_roberts\nMy Other YouTube Channel - http://www.youtube.com/thenewbostontv\nDonate - https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=5K9RJVCAKWZKS","thumbnail":{"sqDefault":"http://i.ytimg.com/vi/zcHBT6QFIqk/default.jpg","hqDefault":"http://i.ytimg.com/vi/zcHBT6QFIqk/hqdefault.jpg"},"player":{"default":"https://www.youtube.com/watch?v=zcHBT6QFIqk&feature=youtube_gdata_player","mobile":"https://m.youtube.com/details?v=zcHBT6QFIqk"},"content":{"5":"https://www.youtube.com/v/zcHBT6QFIqk?version=3&f=playlists&app=youtube_gdata","1":"rtsp://v7.cache1.c.youtube.com/CiULENy73wIaHAmpIgWkT8HBzRMYDSANFEgGUglwbGF5bGlzdHMM/0/0/0/video.3gp","6":"rtsp://v1.cache8.c.youtube.com/CiULENy73wIaHAmpIgWkT8HBzRMYESARFEgGUglwbGF5bGlzdHMM/0/0/0/video.3gp"},"duration":343,"aspectRatio":"widescreen","rating":4.7362638,"likeCount":"85","ratingCount":91,"viewCount":3279,"favoriteCount":0,"commentCount":43,"accessControl":{"comment":"allowed","commentVote":"allowed","videoRespond":"moderated","rate":"allowed","embed":"allowed","list":"allowed","autoPlay":"allowed","syndicate":"allowed"}}},{"id":"ECjsdPXfMXpAv6yB_jzc9KzhvXyS-xnL4b","position":3,"author":"thenewboston","video":{"id":"1tWuDkrvJ6k","uploaded":"2012-09-05T01:45:36.000Z","updated":"2012-10-10T08:49:32.000Z","uploader":"thenewboston","category":"Education","title":"Biology Lecture - 3 - Properties of Life","description":
10-10 15:00:29.268: E/PlaylistsList:(18761): Biology Lecture - 1 - Introduction to Biology
10-10 15:00:29.268: E/PlaylistsList:(18761): Biology Lecture - 2 - What is Life?
10-10 15:00:29.268: E/PlaylistsList:(18761): Biology Lecture - 3 - Properties of Life
10-10 15:00:29.273: E/PlaylistsList:(18761): Biology Lecture - 4 - Acids and Bases
10-10 15:00:29.273: E/PlaylistsList:(18761): Biology Lecture - 5 - Why are Acids and Bases Important?
10-10 15:00:29.273: E/PlaylistsList:(18761): Biology Lecture - 6 - pH Scale
10-10 15:00:29.273: E/PlaylistsList:(18761): Biology Lecture - 7 - Carbohydrates
10-10 15:00:29.278: E/PlaylistsList:(18761): Biology Lecture - 8 - Classifying Carbohydrates
10-10 15:00:29.278: E/PlaylistsList:(18761): Biology Lecture - 9 - Sugars
10-10 15:00:29.278: E/PlaylistsList:(18761): Biology Lecture - 10 - Why does your body need Carbohydrates?
10-10 15:00:29.278: E/PlaylistsList:(18761): Biology Lecture - 11 - Proteins
10-10 15:00:29.278: E/PlaylistsList:(18761): Biology Lecture - 12 - Nucleic Acids
10-10 15:00:29.278: E/PlaylistsList:(18761): Biology Lecture - 13 - DNA
10-10 15:00:29.278: E/PlaylistsList:(18761): Biology Lecture - 14 - Lipids
10-10 15:00:29.278: E/PlaylistsList:(18761): Biology Lecture - 15 - The Cell
10-10 15:00:29.283: E/PlaylistsList:(18761): Biology Lecture - 16 - Plasma Membrane
10-10 15:00:29.283: E/PlaylistsList:(18761): Biology Lecture - 17 - Transporting Materials Through the Cell Membrane
10-10 15:00:29.283: E/PlaylistsList:(18761): Biology Lecture - 18 - Diffusion
10-10 15:00:29.288: E/PlaylistsList:(18761): Biology Lecture - 19 - Osmosis
10-10 15:00:29.288: E/PlaylistsList:(18761): Biology Lecture - 20 - Nucleus
10-10 15:00:29.288: E/PlaylistsList:(18761): Biology Lecture - 21 - Ribosomes
10-10 15:00:29.288: E/PlaylistsList:(18761): Biology Lecture - 22 - Endoplasmic Reticulum
10-10 15:00:29.288: E/PlaylistsList:(18761): Biology Lecture - 23 - Golgi Apparatus
10-10 15:00:29.288: E/PlaylistsList:(18761): Biology Lecture - 24 - Lysosome
10-10 15:00:29.288: E/PlaylistsList:(18761): Biology Lecture - 25 - Peroxisome
10-10 15:00:29.288: E/Full Playlists:(18761): Biology Lecture - 4 - Acids and Bases
10-10 15:00:29.293: D/AndroidRuntime(18761): Shutting down VM
10-10 15:00:29.293: W/dalvikvm(18761): threadid=1: thread exiting with uncaught exception (group=0x4001d7d0)
10-10 15:00:29.303: E/AndroidRuntime(18761): FATAL EXCEPTION: main
10-10 15:00:29.303: E/AndroidRuntime(18761): java.lang.NullPointerException
10-10 15:00:29.303: E/AndroidRuntime(18761): at apps.beneficial.strongrunner.VideoListLoader$VideoListFragment.onLoadFinished(VideoListLoader.java:157)
10-10 15:00:29.303: E/AndroidRuntime(18761): at apps.beneficial.strongrunner.VideoListLoader$VideoListFragment.onLoadFinished(VideoListLoader.java:1)
10-10 15:00:29.303: E/AndroidRuntime(18761): at android.support.v4.app.LoaderManagerImpl$LoaderInfo.callOnLoadFinished(LoaderManager.java:425)
10-10 15:00:29.303: E/AndroidRuntime(18761): at android.support.v4.app.LoaderManagerImpl$LoaderInfo.onLoadComplete(LoaderManager.java:393)
10-10 15:00:29.303: E/AndroidRuntime(18761): at android.support.v4.content.Loader.deliverResult(Loader.java:103)
10-10 15:00:29.303: E/AndroidRuntime(18761): at apps.beneficial.strongrunner.RESTLoader.deliverResult(RESTLoader.java:200)
10-10 15:00:29.303: E/AndroidRuntime(18761): at apps.beneficial.strongrunner.RESTLoader.deliverResult(RESTLoader.java:1)
10-10 15:00:29.303: E/AndroidRuntime(18761): at android.support.v4.content.AsyncTaskLoader.dispatchOnLoadComplete(AsyncTaskLoader.java:221)
10-10 15:00:29.303: E/AndroidRuntime(18761): at android.support.v4.content.AsyncTaskLoader$LoadTask.onPostExecute(AsyncTaskLoader.java:61)
10-10 15:00:29.303: E/AndroidRuntime(18761): at android.support.v4.content.ModernAsyncTask.finish(ModernAsyncTask.java:461)
10-10 15:00:29.303: E/AndroidRuntime(18761): at android.support.v4.content.ModernAsyncTask.access$500(ModernAsyncTask.java:47)
10-10 15:00:29.303: E/AndroidRuntime(18761): at android.support.v4.content.ModernAsyncTask$InternalHandler.handleMessage(ModernAsyncTask.java:474)
10-10 15:00:29.303: E/AndroidRuntime(18761): at android.os.Handler.dispatchMessage(Handler.java:99)
10-10 15:00:29.303: E/AndroidRuntime(18761): at android.os.Looper.loop(Looper.java:123)
10-10 15:00:29.303: E/AndroidRuntime(18761): at android.app.ActivityThread.main(ActivityThread.java:4627)
10-10 15:00:29.303: E/AndroidRuntime(18761): at java.lang.reflect.Method.invokeNative(Native Method)
10-10 15:00:29.303: E/AndroidRuntime(18761): at java.lang.reflect.Method.invoke(Method.java:521)
10-10 15:00:29.303: E/AndroidRuntime(18761): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
10-10 15:00:29.303: E/AndroidRuntime(18761): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
10-10 15:00:29.303: E/AndroidRuntime(18761): at dalvik.system.NativeStart.main(Native Method)
10-10 15:00:29.368: D/dalvikvm(18761): GC_FOR_MALLOC freed 7808 objects / 672848 bytes in 60ms
我的解决方案: 我忘记将静态参数添加到VideoListAdapter,这就是我的适配器没有调用的原因。