在Fragment中刷新listView - NullPointerException

时间:2015-02-15 14:03:02

标签: listview android-fragments

在我的应用程序中,我有MainActivity(扩展Fragment活动),topButtons独立于mPagerView(例如:AddButton),内部有碎片的PagerView。我想做的是:

1)下载一些内容(新活动开始,然后在activityResult上完成获取信息)

2)创建新对象并将其添加到ViewPager中Fragment内的listView。

3)在向列表添加新元素后,在PagerView中的Fragment内刷新listView。

我得到了什么:

1)成功下载文件并创建对象并将其添加到列表

问题:

1)当我想刷新listview时,我得到的错误如下:......中的NullPointerException

代码在这里:

在PagerView中找到我的目标片段:

Fragment frag = mAdapter.getItem(position);

                       if(position == 1)
                       {
                           ((KwejkFragment) frag).notifyNewInsertedData();
                       }

尝试在目标片段(我的方法)中使用此方法刷新lisview:

public void notifyNewInsertedData()
    {
        this.adapter.notifyDataSetChanged(); //App crashes here telling me that I have a null pointerException. List is created on activityStarted and is not null.
    }

在这里我得到了一个错误:

02-15 15:02:27.833: E/AndroidRuntime(31310): Caused by: java.lang.NullPointerException
02-15 15:02:27.833: E/AndroidRuntime(31310):    at pl.app.fragments.KwejkFragment.notifyNewInsertedData(KwejkFragment.java:340)
02-15 15:02:27.833: E/AndroidRuntime(31310):    at pl.engine.main.MainActivity.onActivityResult(MainActivity.java:630)
02-15 15:02:27.833: E/AndroidRuntime(31310):    at android.app.Activity.dispatchActivityResult(Activity.java:3908)
02-15 15:02:27.833: E/AndroidRuntime(31310):    at android.app.ActivityThread.deliverResults(ActivityThread.java:2549)
02-15 15:02:27.833: E/AndroidRuntime(31310):    ... 11 more

有什么问题?如何解决这个问题?我究竟做错了什么?所有列表都存储在GlobalApplication类中。我在创建片段时指向它们并获取此列表。

更新:

public class KwejkFragment extends Fragment{

    private static ArrayList<GifModel> list = null;     //BASIC PROGRAM LIST
    private static ListView listView;
    private static List<GifModel> sortingList;
    private AlertDialog.Builder dialog;
    private DataBaseManager dataBaseManager;
    private Handler handler;
    private ListAdapter adapter;
    private String sprawdzenie;

    ///////// VARIABLES HERE////////
    private boolean useAnimations = false;
    private int animationSpinnerPosition;
    private String fragmentTag;


    public KwejkFragment(String tagName,String sprawdzenie)
    {
        this.fragmentTag = tagName;
        this.sprawdzenie = sprawdzenie;
    }
    public String sprawdzenie()
    {
        return sprawdzenie;
    }
    public String getTagName()
    {
        return this.fragmentTag;
    }

    public void refresh(){};

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);


        getSharedPreferences();
        //setHandler();

        GlobalApplication globalApp = (GlobalApplication) getActivity().getApplication();
        list = globalApp.getKwejkList();

        adapter = new ListAdapter(getActivity(), R.id.list_item, list, useAnimations, animationSpinnerPosition);

    }



    @Override
    public String toString() {
        // TODO Auto-generated method stub
        return fragmentTag;
    }
    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();

        //dataBaseManager.close();

    }



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.kwejkpl_layout, container, false);
        listView = (ListView) view.findViewById(R.id.listViewKwejk);
//      list = new ArrayList<GifModel>();
//      list.add(new GifModel());
//      adapter = new ListAdapter(getActivity(), R.id.list_item,list, useAnimations, animationSpinnerPosition);
//      if(adapter == null)
//          System.out.println("ADAPTER YEST NULL");
        listView.setAdapter(adapter);
        // TODO Auto-generated method stubl
        //prepareDataBase();
        //list = dataBaseManager.getAllGifs();
        //Log.i("!!!!!!!",""+ list.size());

        setUpView();

        //adapter.notifyDataSetChanged();

        return view;
    }


    public void createNewItems(String name,int rating)
    {
        GifModel gif = new GifModel();
        gif.setNameOfItem(name);
        gif.setRating(rating);
        list.add(gif);
        System.out.println(list.size());
        //System.out.println("Is adapter null:"+ adapter.isEmpty());
        adapter = new ListAdapter(getActivity(), R.id.list_item, list, useAnimations, animationSpinnerPosition);
        listView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onResume() {
        // TODO Auto-generated method stub
//      Thread a = new Thread(new Runnable() {
//          
//          @Override
//          public void run() {
//              list = dataBaseManager.getAllGifs();
//              handler.sendEmptyMessage(1);
//              //System.out.println(list.size());
//          }
//      });
//      a.start();

        super.onResume();
        adapter.notifyDataSetChanged();
    }


    @Override
    public void onDestroyView() {
        // TODO Auto-generated method stub
        //dataBaseManager.close();
        super.onDestroyView();
    }


    public void prepareDataBase()
    {
//      if(ifAppWorks)
//      {
//          dataBaseManager.close();
//      }
        dataBaseManager = new DataBaseManager(getActivity());
        dataBaseManager.open(); 
        System.out.println("has connection?:" + dataBaseManager.isOpen());

    }

    private void setHandler()
    {
        handler = new Handler() {

               @Override
               public void handleMessage(Message msg) {

                   if(msg.what == 1)
                   {
                       adapter = new ListAdapter(getActivity(), R.layout.list_item, list, useAnimations, animationSpinnerPosition);

                        listView.setAdapter(adapter);
                        adapter.notifyDataSetChanged();
                   }

               }

           };
    }


    private void getSharedPreferences()
    {
        SharedPreferences preferences = getActivity().getSharedPreferences(Tools.PREFS_NAME,Activity.MODE_PRIVATE);

        useAnimations = preferences.getBoolean("animation", false);

        animationSpinnerPosition = preferences.getInt("animationPosition", 0);


    }   

    private void setUpView(){

        dialog = new AlertDialog.Builder(getActivity());

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

          @Override
          public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
              System.out.println(list.get(position).getCoverUrl());
           System.out.println("link pozycji");

                  //GlobalApplication app = (GlobalApplication) getApplication();
                  if(list.get(position).getCoverUrl().contains("http://i1.ytimg") || list.get(position).getCoverUrl().contains("http://www.youtube.com/embed"))
                  {
                      Intent intent = new Intent(getActivity(), MovieShow.class);


                      //System.out.println(list.get(position).getUrl());
                      intent.putExtra("youtubeLink", list.get(position).getUrl());
                      System.out.println(list.get(position).getUrl());
                      intent.putExtra("header", list.get(position).getNameOfIteme());

                      intent.putExtra("contentlink", list.get(position).getMainLinkToTheContent());
                      System.out.println(list.get(position).getUrl());

                      //overridePendingTransition(R.anim.trans_left_in,R.anim.trans_left_out);
                      System.out.println(list.get(position).getUrl());
                      startActivity(intent);
//                    if(app.getIfAnimationsOrNot())
//                      overridePendingTransition(R.anim.trans_left_in,R.anim.trans_left_out);

                  }
                  else if((list.get(position).getCoverUrl().contains("jpg")) || (list.get(position).getCoverUrl().contains("png")) || 
                          (list.get(position).getCoverUrl().contains("jpeg")))
                  {
                      Intent intent = new Intent(getActivity(), ImageShow.class);
                      intent.putExtra("imageUrl", list.get(position).getUrl());
                      intent.putExtra("header", list.get(position).getNameOfIteme());
                      intent.putExtra("contentlink", list.get(position).getMainLinkToTheContent());

                      startActivity(intent);
//                    if(app.getIfAnimationsOrNot())
//                      overridePendingTransition(R.anim.trans_left_in,R.anim.trans_left_out);
                  }

                  else
                  {
//                    Intent intent = new Intent(MainActivity.this, GifAnimationClass.class);
//                    intent.putExtra("gifAdress", list.get(position).getUrl());
//                    System.out.println(list.get(position).getUrl());
//                    startActivity(intent);
                      Intent intent = new Intent(getActivity(), GifPlay.class);
                      intent.putExtra("webUrl", list.get(position).getUrl());
                      intent.putExtra("header", list.get(position).getNameOfIteme());
                      intent.putExtra("contentlink", list.get(position).getMainLinkToTheContent());
                      //overridePendingTransition(R.anim.trans_left_in,R.anim.trans_left_out);
                      startActivity(intent);
//                    if(app.getIfAnimationsOrNot())
//                          overridePendingTransition(R.anim.trans_left_in,R.anim.trans_left_out);
//                      //overridePendingTransition(R.anim.trans_left_in,R.anim.trans_left_out);
                  }
              }
        });
    }


    public void notifyNewInsertedData()
    {
        this.adapter.notifyDataSetChanged();
    }

}

1 个答案:

答案 0 :(得分:1)

我认为您的适配器为null。尝试在片段的onStart方法中初始化它。

@Override
public void onStart() {

    adapter = new ListAdapter(getActivity(), R.id.list_item, list, useAnimations, animationSpinnerPosition);
}