如何在活动中初始化片段内的listview

时间:2016-03-13 14:30:00

标签: android listview fragment android-adapter

我是android新手。我正在尝试使用自定义适配器初始化片段中的listview,但我在使用自定义适配器构造函数时遇到问题。

这是我的自定义适配器代码。

public class CustomListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Movie> movieItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();

public CustomListAdapter(Activity activity, List<Movie> movieItems) {
    this.activity = activity;
    this.movieItems = movieItems;
}

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

@Override
public Object getItem(int location) {
    return movieItems.get(location);
}

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

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    if (inflater == null)
        inflater = (LayoutInflater) activity
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    if (convertView == null)
        convertView = inflater.inflate(R.layout.list_row, null);

    if (imageLoader == null)
        imageLoader = AppController.getInstance().getImageLoader();
    NetworkImageView thumbNail = (NetworkImageView) convertView
            .findViewById(R.id.thumbnail);
    TextView title = (TextView) convertView.findViewById(R.id.title);
    TextView rating = (TextView) convertView.findViewById(R.id.rating);
    TextView genre = (TextView) convertView.findViewById(R.id.genre);
    TextView year = (TextView) convertView.findViewById(R.id.releaseYear);

    // getting movie data for the row
    Movie m = movieItems.get(position);

    // thumbnail image
    thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);

    // title
    title.setText(m.getTitle());

    // rating
    rating.setText("Rating: " + String.valueOf(m.getRating()));

    // genre
    String genreStr = "";
    for (String str : m.getGenre())
    {
        genreStr += str + ", ";
    }
    genreStr = genreStr.length() > 0 ? genreStr.substring(0, genreStr.length() - 2) : genreStr;
    genre.setText(genreStr);

    // release year
    year.setText(String.valueOf(m.getYear()));

    return convertView;
}

}

这是我的片段激活码。

 private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
private Custom_Adapter_Fragment adapter2;


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


   // ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(), R.array.Planets, android.R.layout.simple_list_item_1);

  // adapter = new CustomListAdapter(this.getActivity(), movieList);
  //
   // adapter = new CustomListAdapter(this.getActivity(), movieList);
    adapter2 = new Custom_Adapter_Fragment(movieList,getContext());




}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.news,null);
    listView = (ListView)view.findViewById(android.R.id.list);
    listView.setAdapter(adapter);
    pDialog = new ProgressDialog(getContext());
    // Showing progress dialog before making http request
    pDialog.setMessage("Loading...");
    pDialog.show();

    JsonArrayRequest movieReq = new JsonArrayRequest(url,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    Log.d(TAG, response.toString());
                    hidePDialog();

                    // Parsing json
                    for (int i = 0; i < response.length(); i++) {
                        try {

                            JSONObject obj = response.getJSONObject(i);
                            Movie movie = new Movie();
                            movie.setTitle(obj.getString("title"));
                            movie.setThumbnailUrl(obj.getString("image"));
                            movie.setRating(((Number) obj.get("rating"))
                                    .doubleValue());
                            movie.setYear(obj.getInt("releaseYear"));

                            // Genre is json array
                            JSONArray genreArry = obj.getJSONArray("genre");
                            ArrayList<String> genre = new ArrayList<String>();
                            for (int j = 0; j < genreArry.length(); j++) {
                                genre.add((String) genreArry.get(j));
                            }
                            movie.setGenre(genre);

                            // adding movie to movies array
                            movieList.add(movie);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                    // notifying list adapter about data changes
                    // so that it renders the list view with updated data
                    adapter.notifyDataSetChanged();
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d(TAG, "Error: " + error.getMessage());
            hidePDialog();

        }
    });

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(movieReq);



    return view;
}
private void hidePDialog() {
    if (pDialog != null) {
        pDialog.dismiss();
        pDialog = null;
    }
}

}

这是我的logcat

03-13 19:56:16.036 17211-17211/com.example.krunal.anamika E/AndroidRuntime: FATAL EXCEPTION: main
                                                                        Process: com.example.krunal.anamika, PID: 17211
                                                                        java.lang.NullPointerException
                                                                            at com.example.krunal.anamika.fragments.News.onCreateView(News.java:125)
                                                                            at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)
                                                                            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
                                                                            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
                                                                            at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
                                                                            at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
                                                                            at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:570)
                                                                            at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
                                                                            at android.support.v4.view.ViewPager.populate(ViewPager.java:1177)
                                                                            at android.support.v4.view.ViewPager.populate(ViewPager.java:1025)
                                                                            at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1545)
                                                                            at android.view.View.measure(View.java:16660)
                                                                            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5150)
                                                                            at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
                                                                            at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
                                                                            at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
                                                                            at android.view.View.measure(View.java:16660)
                                                                            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5150)
                                                                            at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
                                                                            at android.view.View.measure(View.java:16660)
                                                                            at android.support.v4.widget.DrawerLayout.onMeasure(DrawerLayout.java:1075)
                                                                            at android.view.View.measure(View.java:16660)
                                                                            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5150)
                                                                            at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
                                                                            at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
                                                                            at android.view.View.measure(View.java:16660)
                                                                            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5150)
                                                                            at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
                                                                            at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
                                                                            at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
                                                                            at android.view.View.measure(View.java:16660)
                                                                            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5150)
                                                                            at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
                                                                            at android.view.View.measure(View.java:16660)
                                                                            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5150)
                                                                            at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
                                                                            at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
                                                                            at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
                                                                            at android.view.View.measure(View.java:16660)
                                                                            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5150)
                                                                            at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
                                                                            at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2421)
                                                                            at android.view.View.measure(View.java:16660)
                                                                            at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2058)
                                                                            at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1189)
                                                                            at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1374)
                                                                            at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1076)
                                                                            at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5905)
                                                                            at android.view.Choreographer$CallbackRecord.run(Choreographer.java:807)
                                                                            at android.view.Choreographer.doCallbacks(Choreographer.java:601)
                                                                            at android.view.Choreographer.doFrame(Choreographer.java:562)
                                                                            at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:791)
                                                                            at android.os.Handler.handleCallback(Handler.java:733)
                                                                            at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                            at android.os.Looper.loop(Looper.java:157)
                                                                            at android.app.ActivityThread.main(ActivityThread.java:5633)
                                                                            at java.lang.reflect.Method.invokeNative(Native Method)
                                                                            at java.lang.reflect.Method.invoke(Method.java:515)
                                                                            at com.android.i

我知道问题出在自定义适配器构造函数中。

先谢谢。

0 个答案:

没有答案