简体   繁体   English

使用Fragment和Volley时,自定义列表适配器上的Null异常

[英]Null Exception on Custom list adapter while using Fragment and Volley

Hi everyone I need a little help with his Exception I am taking while calling the Fragment. 大家好,我需要一些帮助来处理他在调用Fragment时遇到的Exception。 I have created a custom list adapter and I am assigning it to the listview of my fragment. 我已经创建了一个自定义列表适配器,并将其分配给片段的listview。 I think my network call using Volley might be a problem. 我认为使用Volley进行网络通话可能是个问题。 Where should we make Network Calls inside a fragments? 我们应该在哪里在片段内进行网络呼叫? I have tried in on OnResume,OnActivityCreated and OnCreateView. 我已经尝试过OnResume,OnActivityCreated和OnCreateView。 I have tested it and data is fetched correctly from web service but then I pass my ArrayList of data to Custom Adapter and I got an error on setAdapter method null exception. 我已经对其进行了测试,并且可以从Web服务正确获取数据,但是随后我将数据的ArrayList传递给了Custom Adapter,并且setAdapter方法null异常发生错误。 Below are my implementations 以下是我的实现

NewsFragment.java NewsFragment.java

public class NewsFragment extends Fragment {
    private ListView listView;
    private FeedListAdapter listAdapter;
    private List<News> feedItems;
    private String URL_FEED = "http://stajevi.com/api/Haber/Listele";

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



    }


    @Override
    public void onResume() {
        super.onResume();
        feedItems = new ArrayList<News>();
        // We first check for cached request
        Cache cache = AppController.getInstance().getRequestQueue().getCache();
        Cache.Entry entry = cache.get(URL_FEED);
        if (entry != null) {
            // fetch the data from cache
            try {
                String data = new String(entry.data, "UTF-8");
                try {
                    parseJsonFeed(new JSONArray(data));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

        } else {
            // making fresh volley request and getting json
            JsonArrayRequest jsonReq=new JsonArrayRequest(URL_FEED, new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray jsonArray) {
                    if (jsonArray != null)
                        parseJsonFeed(jsonArray);
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    volleyError.printStackTrace();
                }
            });
            jsonReq.setRetryPolicy(new DefaultRetryPolicy(
                    DefaultRetryPolicy.DEFAULT_TIMEOUT_MS*2,
                    DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                    DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

            // Adding request to volley request queue
            AppController.getInstance().addToRequestQueue(jsonReq);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_register, container, false);
        listView = (ListView) rootView.findViewById(R.id.list);
       if(feedItems==null)
           Toast.makeText(getContext(),"feed items is null",Toast.LENGTH_SHORT).show();

        listAdapter = new FeedListAdapter(getActivity(), feedItems);


        if(listAdapter==null)
            Toast.makeText(getContext(),"list adapter is null",Toast.LENGTH_SHORT).show();
        else
        listView.setAdapter(listAdapter);


        return rootView;
    }


    private  void  parseJsonFeed(JSONArray response) {


        try {
            Toast.makeText(getContext(),((JSONObject)response.get(0)).getString("NewsShortTitle"),Toast.LENGTH_LONG).show();

            for (int i = 0; i < response.length(); i++) {
                JSONObject feedObj = (JSONObject) response.get(i);

                News item = new News();
                // item.setNewsActive(feedObj.getBoolean("NewsActive"));
                //  item.setNewsCreateUserId(feedObj.getString("NewsCreateUserId"));
                item.setNewsDescription(feedObj.getString("NewsDescription"));
                // item.setNewsEndDate(feedObj.getString("NewsEndDate"));
                // item.setNewsID(feedObj.getInt("NewsID"));
                item.setNewsShortTitle(feedObj.getString("NewsShortTitle"));
                item.setNewsStartDate(feedObj.getString("NewsStartDate"));
                item.setNewsTitle(feedObj.getString("NewsTitle"));
                //  item.setNewsType(feedObj.getInt("NewsType"));
                item.setTitleSourceUrl(feedObj.getString("TitleSourceUrl"));
                // item.setTitleType(feedObj.getInt("TitleType"));



                feedItems.add(item);
            }

            // notify data changes to list adapater
            listAdapter.notifyDataSetChanged();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }



}

FeedListAdapter.java FeedListAdapter.java

public class FeedListAdapter extends BaseAdapter {
    private Activity activity;
    private LayoutInflater inflater;
    private List<News> feedItems;
    ImageLoader imageLoader;

    public FeedListAdapter(Activity activity, List<News> feedItems) {

        this.feedItems = feedItems;
        this.activity=activity;
       imageLoader = AppController.getInstance().getImageLoader();
    }

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

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

        if (imageLoader == null)
            imageLoader = AppController.getInstance().getImageLoader();

        TextView name = (TextView) convertView.findViewById(R.id.name);
        TextView timestamp = (TextView) convertView
                .findViewById(R.id.timestamp);


        FeedImageView feedImageView = (FeedImageView) convertView
                .findViewById(R.id.feedImage1);

        News item = feedItems.get(position);

        name.setText(item.getNewsShortTitle());

        String date=item.getNewsStartDate();
        date=date.substring(0,10);
        timestamp.setText(date);



        // Feed image
        if (item.getTitleSourceUrl() != null) {
            feedImageView.setImageUrl(item.getTitleSourceUrl(), imageLoader);
            feedImageView.setVisibility(View.VISIBLE);
            feedImageView
                    .setResponseObserver(new FeedImageView.ResponseObserver() {
                        @Override
                        public void onError() {
                        }

                        @Override
                        public void onSuccess() {
                        }
                    });
        } else {
            feedImageView.setVisibility(View.GONE);
        }

        return convertView;
    }

}

Stack Trace 堆栈跟踪

04-15 13:34:01.133 1921-1921/com.uygulama.stajevi E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
    at com.uygulama.stajevi.NewsFragment.onCreateView(NewsFragment.java:105)
    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$1.run(FragmentManager.java:517)
    at android.os.Handler.handleCallback(Handler.java:725)
    at android.os.Handler.dispatchMessage(Handler.java:92)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:5041)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
    at dalvik.system.NativeStart.main(Native Method)

fragment_register.xml fragment_register.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.uygulama.stajevi.RegisterFragment">

<!-- TODO: Update blank fragment layout -->
<include
    android:id="@+id/tool_bar"
    layout="@layout/tool_bar"
    />
<EditText android:textSize="20sp"
    android:textColorHint="@color/smoothGray"
    android:id="@+id/nameEditText"
    android:focusableInTouchMode="true"
    android:layout_width="wrap_content"
    android:layout_height="35dp"
    android:hint="@string/name"
    android:singleLine="true"
    android:layout_marginTop="25dp"
    android:background="@drawable/rounded_edittext"
    android:layout_below="@+id/tool_bar"
    android:layout_marginLeft="@dimen/margin_left_text_box"
    android:layout_marginRight="@dimen/margin_right_text_box"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true" />
<EditText android:textSize="20sp"
    android:textColorHint="@color/smoothGray"
    android:id="@+id/emailEditText"
    android:focusableInTouchMode="true"
    android:layout_width="wrap_content"
    android:layout_height="35dp"
    android:inputType="text"
    android:hint="@string/email"
    android:singleLine="true"
    android:layout_marginTop="25dp"
    android:background="@drawable/rounded_edittext"
    android:layout_below="@+id/nameEditText"
    android:layout_marginLeft="@dimen/margin_left_text_box"
    android:layout_marginRight="@dimen/margin_right_text_box"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true" />
<EditText android:textSize="18sp"
    android:textColorHint="@color/smoothGray"
    android:id="@+id/passwEditText"
    android:focusableInTouchMode="true"
    android:layout_width="wrap_content"
    android:layout_height="35dp"
    android:hint="@string/password"
    android:singleLine="true"
    android:inputType="textPassword"
    android:layout_marginTop="25dp"
    android:background="@drawable/rounded_edittext"
    android:layout_below="@+id/emailEditText"
    android:layout_marginLeft="@dimen/margin_left_text_box"
    android:layout_marginRight="@dimen/margin_right_text_box"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true" />
<EditText android:textSize="18sp"
    android:textColorHint="@color/smoothGray"
    android:id="@+id/repassEditText"
    android:focusableInTouchMode="true"
    android:layout_width="wrap_content"
    android:layout_height="35dp"
    android:hint="@string/repeat_password"
    android:singleLine="true"
    android:inputType="textPassword"
    android:layout_marginTop="25dp"
    android:background="@drawable/rounded_edittext"
    android:layout_below="@+id/passwEditText"
    android:layout_marginLeft="@dimen/margin_left_text_box"
    android:layout_marginRight="@dimen/margin_right_text_box"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true" />
<Button
    android:layout_width="wrap_content"
    android:layout_gravity="center"
    android:layout_height="wrap_content"
    android:text="Hemen Uye Ol"
    android:textColor="@color/backcolor"
    android:background="@drawable/turuncu_button_border"
    android:id="@+id/btnGiris"
    android:textAllCaps="false"
    android:layout_marginTop="36dp"
    android:layout_marginLeft="@dimen/margin_left_text_box"
    android:layout_marginRight="@dimen/margin_right_text_box"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"

    android:layout_below="@+id/repassEditText"
    />

Your problem is that your listView is null so basically check that R.id.list is inside R.layout.fragment_register , I guess that this R.id.list id is in another layout, and the one that you need have another name. 您的问题是您的listView为null,因此基本上检查R.id.list是否在R.layout.fragment_register ,我猜想此R.id.list id在另一种布局中,并且您需要的那个具有其他名称。

Hope this helps!! 希望这可以帮助!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM