列表中的列表视图空指针异常

时间:2015-06-14 07:22:32

标签: java android android-fragments android-listview swiperefreshlayout

我正在尝试在我的片段中设置刷卡以刷新,该片段从解析中获取对象。但每次,我似乎在setadapter和列表视图上得到一个空指针异常。虽然它们都正确初始化都不是null。

我的最近的适应者:

package com.astuetz.viewpager.extensions.sample;

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 java.util.ArrayList;
import java.util.HashMap;

public class RecentsAdapter extends BaseAdapter
{

        LayoutInflater inflater;
        Context context;
        ArrayList<HashMap<String,String>> items = null;

        public RecentsAdapter(Context context,ArrayList<HashMap<String,String>> items)
        {
            super();
            this.context = context;
            this.items = items;
            inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        }

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

        @Override
        public Object getItem(int position)
        {
            return items.get(position);
        }

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

        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        {
            View v = convertView;
            MyHolder holder = null;
            if(v == null)
            {
                v = inflater.inflate(R.layout.recents_list_item,parent,false);
                holder = new MyHolder(v);
                v.setTag(holder);
            }

            else
            {
                holder = (MyHolder) v.getTag();
            }

            holder.title.setText(items.get(position).get("title"));
            holder.author.setText(items.get(position).get("author"));
            holder.dept.setText(items.get(position).get("dept"));
            holder.price.setText(items.get(position).get("price"));
    //        holder.place.setText(items.get(position).get("place"));


            return v;
        }

        class MyHolder
        {

            TextView dept,title,author,price,place;

            public MyHolder(View view)
            {
                title = (TextView) view.findViewById(R.id.book_title);
                dept = (TextView)view.findViewById(R.id.dept_name);
                author = (TextView) view.findViewById(R.id.author_name);
                price = (TextView)view.findViewById(R.id.price_list);
    //            place = (TextView)view.findViewById(R.id.place_list);
            }

        }
    }

我的 recent_card.xml ,它定义了我的列表视图并滑动以刷新:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             xmlns:card_view="http://schemas.android.com/apk/res-auto"
             android:layout_width="match_parent"
             android:layout_height="match_parent">

    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <android.support.v7.widget.CardView
        android:id="@+id/recents_card"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="8dp"
        card_view:cardBackgroundColor="@android:color/white"
        card_view:cardCornerRadius="8dp"
        android:padding="8dp">

        <ListView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/recents_list"
            android:divider="@color/dividerColor"
            android:dividerHeight="1dp"/>

    </android.support.v7.widget.CardView>
    </android.support.v4.widget.SwipeRefreshLayout>
</FrameLayout>

以及实现它们的 RecentsCardFragment.java

/*
 * Copyright (C) 2013 Andreas Stuetz <andreas.stuetz@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.astuetz.viewpager.extensions.sample;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.ListView;
import android.widget.Toast;


import com.parse.FindCallback;
import com.parse.GetCallback;
import com.parse.Parse;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;



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



public class RecentsCardFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener
{
   ListView  recentsList = (ListView)getActivity().findViewById(R.id.recents_list);

    private SwipeRefreshLayout refreshBooks;

     ArrayList<HashMap<String,String>> items = new ArrayList<>();





    //private  ProgressDialog progress;


    public static RecentsCardFragment newInstance() {
        RecentsCardFragment f = new RecentsCardFragment();
            return f;
        }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.recents_card,container,false);
        ViewCompat.setElevation(rootView,50);
        refreshBooks = (SwipeRefreshLayout) rootView.findViewById(R.id.container);
        refreshBooks.setOnRefreshListener(this);


        getBooks();


        RecentsAdapter  adapter = new RecentsAdapter(getActivity().getApplicationContext(), items);

        recentsList.setAdapter(adapter);


        return rootView;
    }


    private ArrayList<HashMap<String,String>> getBooks(){

        final ParseQuery<ParseObject> query = ParseQuery.getQuery("Posted");
        query.orderByDescending("createdAt");

        query.findInBackground(new FindCallback<ParseObject>() {


            @Override
            public void done(List<ParseObject> parseObjects, ParseException e) {


                if (e == null){

                    Log.w("Parse","Inside getbooks()");
                    for (ParseObject book : parseObjects) {

                        HashMap<String, String> test = new HashMap<>();

                        String dept = book.getString("Department");
                        String title = book.getString("Title");
                        String author = book.getString("Author");
                        Number price_num = book.getNumber("Price");
                        String price = String.valueOf(price_num);
                        String place = book.getString("Place");
                        String desp = book.getString("Description");

                        test.put("dept", dept);
                        test.put("title", title);
                        test.put("author", author);
                        test.put("price", price);
                        test.put("place", place);
                        test.put("description", desp);

                        items.add(test);




                    }


                } else {

                    Log.d("Books", "Error: " + e.getMessage());

                }

            }

        });

        return items;
    }


    @Override
    public void onRefresh(){

        refreshBooks.setRefreshing(true);
        updateBooks();



}

    private void updateBooks(){

        Toast.makeText(getActivity(),"Refresh", Toast.LENGTH_SHORT).show();

        items.addAll(getBooks());

      refreshBooks.setRefreshing(false);
    }

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

   }


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

    }


 }

这是我的logcat:

06-14 02:44:52.485    2373-2373/com.astuetz.viewpager.extensions.sample I/Process﹕ Sending signal. PID: 2373 SIG: 9
06-14 02:58:26.624    2502-2524/com.astuetz.viewpager.extensions.sample D/OpenGLRenderer﹕ Render dirty regions requested: true
06-14 02:58:26.644    2502-2502/com.astuetz.viewpager.extensions.sample D/﹕ HostConnection::get() New Host Connection established 0xabb86710, tid 2502
06-14 02:58:27.720    2502-2502/com.astuetz.viewpager.extensions.sample D/Atlas﹕ Validating map...
06-14 02:58:28.692    2502-2502/com.astuetz.viewpager.extensions.sample I/Choreographer﹕ Skipped 57 frames!  The application may be doing too much work on its main thread.
06-14 02:58:28.716    2502-2502/com.astuetz.viewpager.extensions.sample D/AndroidRuntime﹕ Shutting down VM
06-14 02:58:28.720    2502-2502/com.astuetz.viewpager.extensions.sample E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.astuetz.viewpager.extensions.sample, PID: 2502
    java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.support.v4.app.FragmentActivity.findViewById(int)' on a null object reference
            at com.astuetz.viewpager.extensions.sample.RecentsCardFragment.<init>(RecentsCardFragment.java:54)
            at com.astuetz.viewpager.extensions.sample.RecentsCardFragment.newInstance(RecentsCardFragment.java:68)
            at com.astuetz.viewpager.extensions.sample.MainActivity$MyPagerAdapter.getItem(MainActivity.java:133)
            at android.support.v4.app.FragmentPagerAdapter.instantiateItem(FragmentPagerAdapter.java:97)
            at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:837)
            at android.support.v4.view.ViewPager.populate(ViewPager.java:987)
            at android.support.v4.view.ViewPager.populate(ViewPager.java:919)
            at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1441)
            at android.view.View.measure(View.java:17430)
            at android.widget.LinearLayout.measureVertical(LinearLayout.java:875)
            at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
            at android.view.View.measure(View.java:17430)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
            at android.view.View.measure(View.java:17430)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
            at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
            at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
            at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
            at android.view.View.measure(View.java:17430)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
            at android.view.View.measure(View.java:17430)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
            at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
            at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
            at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
            at android.view.View.measure(View.java:17430)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
            at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2560)
            at android.view.View.measure(View.java:17430)
            at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2001)
            at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1166)
            at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1372)
            at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1054)
            at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5779)
            at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
            at android.view.Choreographer.doCallbacks(Choreographer.java:580)
            at android.view.Choreographer.doFrame(Choreographer.java:550)
            at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
06-14 02:58:32.992    2502-2502/com.astuetz.viewpager.extensions.sample I/Process﹕ Sending signal. PID: 2502 SIG: 9

我继续在我的列表视图最近列表或行,recentslist.ssetadapter(适配器)中获取空指针异常。

虽然,对于同一主题有几个已回答的问题,但无法解决我的使用问题。

请帮帮我! 提前谢谢!

1 个答案:

答案 0 :(得分:2)

您的recent_list为空,并且您在onCreateView内的RecentsCardFragment之外引用它,这就是NullPointerException发生的原因。将您的recent_list声明移到onCreateView方法中,如下所示:

public class RecentsCardFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener
{
   ListView  recentsList;

    private SwipeRefreshLayout refreshBooks;

     ArrayList<HashMap<String,String>> items = new ArrayList<>();

    //private  ProgressDialog progress;

    public static RecentsCardFragment newInstance() {
        RecentsCardFragment f = new RecentsCardFragment();
            return f;
        }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.recents_card,container,false);
        recentsList = (ListView)rootView.findViewById(R.id.recents_list);
        ViewCompat.setElevation(rootView,50);
        refreshBooks = (SwipeRefreshLayout) rootView.findViewById(R.id.container);
        refreshBooks.setOnRefreshListener(this);


        getBooks();


        RecentsAdapter  adapter = new RecentsAdapter(getActivity().getApplicationContext(), items);

        recentsList.setAdapter(adapter);


        return rootView;
    }