片段内的自定义列表不起作用

Posted

技术标签:

【中文标题】片段内的自定义列表不起作用【英文标题】:Custom list inside Fragment not working 【发布时间】:2017-04-11 02:19:06 【问题描述】:

我只是在片段中使用了一个自定义列表。我使用 volley 从 api 检索了这些数据。它显示以下错误。我想解决这个问题,有人可以帮助我。

java.lang.NullPointerException: Attempt to invoke virtual method 'com.android.volley.toolbox.ImageLoader com.example.user.ekta.AppController.getImageLoader()' on a null object reference
                                                                           at com.example.user.ekta.MyBookAdapter.<init>(MyBookAdapter.java:25)
                                                                           at com.example.user.ekta.FullInfoTabFragment.onCreateView(FullInfoTabFragment.java:85).

这是我的片段类

package com.example.user.ekta;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


public class FullInfoTabFragment extends Fragment 

    private static final String EXTRA_SRORT_CARD_MODEL = "EXTRA_SRORT_CARD_MODEL";
    //    String transitionTag;
    private SportCardModel sportCardModel;
    private Toolbar toolbar;
    private ImageView ivPhoto;

    private static final String TAG = FullInfoTabFragment.class.getSimpleName();

    private static final String url = "http://myeducationhunt.com/public/schools";

    private ProgressDialog pDialog;
    private List<MyBook> ourBooksListItems = new ArrayList<MyBook>();
    private ListView listView;
    private MyBookAdapter adapter;


    public static FullInfoTabFragment newInstance(SportCardModel sportCardModel) 
        FullInfoTabFragment fragment = new FullInfoTabFragment();
        Bundle args = new Bundle();
        args.putParcelable(EXTRA_SRORT_CARD_MODEL, sportCardModel);
        fragment.setArguments(args);
        return fragment;
    

    @Override
    public void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        if (getArguments() != null) 
            sportCardModel = getArguments().getParcelable(EXTRA_SRORT_CARD_MODEL);
        
        if (savedInstanceState != null) 
            sportCardModel = savedInstanceState.getParcelable(EXTRA_SRORT_CARD_MODEL);
        
    

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) 
        View view = inflater.inflate(R.layout.fragment_full_info, container, false);
        toolbar = (Toolbar) view.findViewById(R.id.toolbar);
        ivPhoto = (ImageView) view.findViewById(R.id.ivPhoto);

        listView = (ListView) view.findViewById(R.id.list);
        adapter = new MyBookAdapter(getActivity(), ourBooksListItems);
        listView.setAdapter(adapter);
        listView.setTextFilterEnabled(true);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() 
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) 

//                OurSchool ourSchool = new OurSchool();
//                Intent i = new Intent(getContext(), SchoolDetails.class);

//                i.putExtra("id", ourSchoolsListItems.get(position).schoolId);
//                i.putExtra("name", ourSchoolsListItems.get(position).schoolName);
//                i.putExtra("location", ourSchoolsListItems.get(position).schoolLocation);
//                i.putExtra("logo", ourSchoolsListItems.get(position).schoolLogo);
//                i.putExtra("email", ourSchoolsListItems.get(position).schoolEmail);
//                i.putExtra("website", ourSchoolsListItems.get(position).schoolWebsite);
//                i.putExtra("created_at", ourSchoolsListItems.get(position).createdAt);
//                i.putExtra("updated_at", ourSchoolsListItems.get(position).updatedAt);

//                startActivity(i);

            
        );
        pDialog = new ProgressDialog(getActivity());
// Showing progress dialog before making http request
        pDialog.setMessage("Loading…");
        pDialog.show();

// Creating volley request obj
        JsonArrayRequest schoolRequest = new JsonArrayRequest(url,
                new Response.Listener<JSONArray>() 
                    @Override
                    public void onResponse(JSONArray response) 
                        Log.d(TAG, response.toString());
                        pDialog.hide();

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

                                JSONObject obj = response.getJSONObject(i);
                                MyBook myBook = new MyBook();

                                myBook.bookName = obj.getString("name");
                                myBook.bookAuthor = obj.getString("location");
                                myBook.bookCover= obj.getString("logo");
                                // adding schools to ourSchool list
                                ourBooksListItems.add(myBook);

                             catch (JSONException e) 
                                e.printStackTrace();
                            
                        

                        adapter.notifyDataSetChanged();
                    
                , new Response.ErrorListener() 
            @Override
            public void onErrorResponse(VolleyError error) 
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                pDialog.hide();
            
        );

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(schoolRequest);
        return view;
    

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) 
        super.onViewCreated(view, savedInstanceState);

        toolbar.setTitle(sportCardModel.getSportTitle());
        toolbar.setNavigationIcon(R.drawable.ic_back);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View view) 
                getActivity().onBackPressed();
            
        );
        toolbar.setBackgroundColor(ContextCompat.getColor(getContext(), sportCardModel.getBackgroundColorResId()));
        ivPhoto.setImageResource(sportCardModel.getImageResId());
    

    @Override
    public void onSaveInstanceState(Bundle outState) 
        outState.putParcelable(EXTRA_SRORT_CARD_MODEL, sportCardModel);
        super.onSaveInstanceState(outState);
    

    static class DividerItemDecoration extends RecyclerView.ItemDecoration 

        private static final int[] ATTRS = new int[]android.R.attr.listDivider;

        private Drawable mDivider;

        /**
         * Default divider will be used
         */
        public DividerItemDecoration(Context context) 
            final TypedArray styledAttributes = context.obtainStyledAttributes(ATTRS);
            mDivider = styledAttributes.getDrawable(0);
            styledAttributes.recycle();
        

        /**
         * Custom divider will be used
         */
        public DividerItemDecoration(Context context, int resId) 
            mDivider = ContextCompat.getDrawable(context, resId);
        

        @Override
        public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) 
            int left = parent.getPaddingLeft();
            int right = parent.getWidth() - parent.getPaddingRight();

            int childCount = parent.getChildCount();
            for (int i = 0; i < childCount; i++) 
                View child = parent.getChildAt(i);

                RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();

                int top = child.getBottom() + params.bottomMargin;
                int bottom = top + mDivider.getIntrinsicHeight();

                mDivider.setBounds(left, top, right, bottom);
                mDivider.draw(c);
            
        
    

这是我的适配器类

package com.example.user.ekta;

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


import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;

import java.util.List;

/**
 * Created by user on 11/27/2016.
 */
public class MyBookAdapter extends BaseAdapter 

    private Activity activity;
    private LayoutInflater inflater;
    private List<MyBook> ourbooksList;
    ImageLoader imageLoader = AppController.getInstance().getImageLoader();

    public MyBookAdapter(Activity activity, List<MyBook> ourbooksListsList) 
        this.activity = activity;
        this.ourbooksList = ourbooksListsList;
    


    @Override
    public int getCount() 
        return ourbooksList.size();
    

    @Override
    public Object getItem(int location) 
        return ourbooksList.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_books, null);

        if (imageLoader == null)
            imageLoader = AppController.getInstance().getImageLoader();
        NetworkImageView bookCover = (NetworkImageView) convertView
                .findViewById(R.id.bookCover);
        TextView bookName = (TextView) convertView.findViewById(R.id.bookName);
        TextView boookAuthor = (TextView) convertView.findViewById(R.id.bookAuthor);
        MyBook m = ourbooksList.get(position);

        bookCover.setImageUrl(m.getBookCover(), imageLoader);

        bookName.setText("Name: " + m.getBookName());

        boookAuthor.setText("Address: " + String.valueOf(m.getBookAuthor()));


        return convertView;
    

【问题讨论】:

显示你的 AppController 代码 根据错误,您的单例正在引起问题。它为空,您在 AppController.getInstance() 上调用 getImageLoader() 时会崩溃 谢谢 rahul。我的错误已修复 【参考方案1】:

AppController.getInstance() 返回 null,你还没有初始化你的 Appcontroller。

如果 AppController 扩展了您的应用程序,那么您必须更改清单

android:name=“appController 的路径”在应用部分。

【讨论】:

哦我忘了。我犯了一个愚蠢的错误。非常感谢你提醒我

以上是关于片段内的自定义列表不起作用的主要内容,如果未能解决你的问题,请参考以下文章

svg 图像内的自定义区域中的链接不起作用

Visual Studio 自定义代码片段在方法定义的参数列表中不起作用

getView() 在我的自定义列表视图中不起作用

Onclicklistener 在片段列表视图中不起作用

片段内的网格适配器不起作用

为啥软键盘在对话框片段内的 Web 视图中不起作用?