0

我正在製作一個帶有多個片段的選項卡式活動,這些片段使用RecyclerView填充自己,並且將從Firebase實時數據庫和存儲中檢索數據作爲後端。Android-Firebase- recyclerView中的java.lang.NullPointerException

錯誤:

E/AndroidRuntime: FATAL EXCEPTION: main 
       Process: com.example.visan.peds, PID: 1522 
       java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setAdapter(android.support.v7.widget.RecyclerView$Adapter)' on a null object reference 
        at com.example.visan.peds.Landing_mother.getData(Landing_mother.java:76) 
        at com.example.visan.peds.Landing_mother.onCreateView(Landing_mother.java:43) 
        at android.support.v4.app.Fragment.performCreateView(Fragment.java:2087) 
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1113) 
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1295) 
        at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:801) 
        at android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:1643) 
        at android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:679) 
        at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:143) 
        at android.support.v4.view.ViewPager.populate(ViewPager.java:1272) 
        at android.support.v4.view.ViewPager.populate(ViewPager.java:1120) 
        at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1646) 
        at android.view.View.measure(View.java:18991) 
        at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:716) 
        at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:462) 
        at android.view.View.measure(View.java:18991) 
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5952) 
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:194) 
        at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139) 
        at android.view.View.measure(View.java:18991) 
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5952) 
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465) 
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:748) 
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:630) 
        at android.view.View.measure(View.java:18991) 
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5952) 
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:194) 
        at android.view.View.measure(View.java:18991) 
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5952) 
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465) 
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:748) 
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:630) 
        at android.view.View.measure(View.java:18991) 
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5952) 
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:194) 
        at com.android.internal.policy.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2645) 
        at android.view.View.measure(View.java:18991) 
        at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2403) 
        at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1342) 
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1591) 
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1233) 
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6552) 
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:919) 
        at android.view.Choreographer.doCallbacks(Choreographer.java:710) 
        at android.view.Choreographer.doFrame(Choreographer.java:645) 
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:905) 
        at android.os.Handler.handleCallback(Handler.java:739) 
        at android.os.Handler.dispatchMessage(Handler.java:95) 
        at android.os.Looper.loop(Looper.java:148) 
        at android.app.ActivityThread.main(ActivityThread.java:5582) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

我的主要活動,Landing.java

package com.example.visan.peds; 

import android.os.Bundle; 
import android.support.design.widget.TabLayout; 
import android.support.v4.view.ViewPager; 
import android.support.v7.app.AppCompatActivity; 
import android.support.v7.widget.Toolbar; 

public class Landing extends AppCompatActivity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_landing); 

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
    setSupportActionBar(toolbar); 

    TabLayout tabLayout=(TabLayout)findViewById(R.id.tab_layout); 
    tabLayout.addTab(tabLayout.newTab().setText("CHILD")); 
    tabLayout.addTab(tabLayout.newTab().setText("MOTHER")); 
    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL); 

    final ViewPager viewPager=(ViewPager) findViewById(R.id.pager); 
    final Landing_frag_manager frag_manager=new Landing_frag_manager(getSupportFragmentManager(),tabLayout.getTabCount(),Landing.this); 

    viewPager.setAdapter(frag_manager); 
    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout)); 

    tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener(){ 
     @Override 
     public void onTabReselected(TabLayout.Tab tab) { 
      viewPager.setCurrentItem(tab.getPosition()); 
     } 

     @Override 
     public void onTabSelected(TabLayout.Tab tab) { 

     } 

     @Override 
     public void onTabUnselected(TabLayout.Tab tab) { 

     } 
    }); 
} 

}

它的佈局文件,activity_landing.xml

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout 
android:id="@+id/main_layout" 
xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:app="http://schemas.android.com/apk/res-auto" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
tools:context=".MainActivity"> 

<android.support.v7.widget.Toolbar 
    android:id="@+id/toolbar" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_alignParentTop="true" 
    android:background="?attr/colorPrimary" 
    android:elevation="6dp" 
    android:minHeight="?attr/actionBarSize" 
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" 
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/> 

<android.support.design.widget.TabLayout 
    android:id="@+id/tab_layout" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_below="@+id/toolbar" 
    android:background="?attr/colorPrimary" 
    android:elevation="6dp" 
    android:minHeight="?attr/actionBarSize" 
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/> 

<android.support.v4.view.ViewPager 
    android:id="@+id/pager" 
    android:layout_width="match_parent" 
    android:layout_height="fill_parent" 
    android:layout_below="@id/tab_layout"/> 

</RelativeLayout> 

片段適配器,Landing_f rag_manager.java

package com.example.visan.peds; 

import android.content.Context; 
import android.support.v4.app.Fragment; 
import android.support.v4.app.FragmentManager; 
import android.support.v4.app.FragmentPagerAdapter; 

public class Landing_frag_manager extends FragmentPagerAdapter { 
    private int num_of_tabs; 
    Context context; 

    public Landing_frag_manager(FragmentManager fm, int numOfTabs, Context context){ 
     super(fm); 
     this.num_of_tabs=numOfTabs; 
     this.context=context; 
    } 

    @Override 
    public Fragment getItem(int position) { 
     switch (position){ 
      case 0: 
       Landing_child child=new Landing_child(); 
       return child; 
      case 1: 
       Landing_mother mother=new Landing_mother(); 
       return mother; 
      default: 
       return null; 
     } 
    } 

    @Override 
    public int getCount() { 
     return num_of_tabs; 
    } 
} 

代碼片段,Landing_mother.java

package com.example.visan.peds; 

import android.os.Bundle; 
import android.support.v4.app.Fragment; 
import android.support.v7.widget.LinearLayoutManager; 
import android.support.v7.widget.RecyclerView; 
import android.util.Log; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 

import com.google.firebase.database.DataSnapshot; 
import com.google.firebase.database.DatabaseError; 
import com.google.firebase.database.DatabaseReference; 
import com.google.firebase.database.FirebaseDatabase; 
import com.google.firebase.database.ValueEventListener; 

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


public class Landing_mother extends Fragment { 

    private List<Ailment> ailments; 

    private RecyclerView recyclerView; 
    LinearLayoutManager layoutManager; 
    private RecyclerView.Adapter adapter; 

    public Landing_mother(){} 

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

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 
     final View view=inflater.inflate(R.layout.fragment_landing_mother,container,false); 

     ailments=new ArrayList<>(); 
     getData(); 

     recyclerView =(RecyclerView)view.findViewById(R.id.recyclerView1); 
     recyclerView.setHasFixedSize(true); 

     layoutManager=new LinearLayoutManager(getActivity()); 
     layoutManager.setOrientation(LinearLayoutManager.VERTICAL); 
     recyclerView.setLayoutManager(layoutManager); 
     return view; 
    } 

    private void getData(){ 
     FirebaseDatabase db=FirebaseDatabase.getInstance(); 
     DatabaseReference ref=db.getReference().child("Mother").child("0"); 

     ref.addListenerForSingleValueEvent(new ValueEventListener() { 
      @Override 
      public void onDataChange(DataSnapshot dataSnapshot) { 
       if (dataSnapshot.exists()){ 
        Log.v("SNAPSHOT::",dataSnapshot.toString()); 
        for (DataSnapshot snapshot:dataSnapshot.getChildren()){ 
         Ailment ailment=snapshot.getValue(Ailment.class); 
         ailments.add(ailment); 
        } 
       } 
      } 

      @Override 
      public void onCancelled(DatabaseError databaseError) { 

      } 
     }); 
     adapter=new LandingAdapter(ailments,getActivity()); 
     recyclerView.setAdapter(adapter); 
    } 
} 

它的佈局文件,fragment_landing_mother.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" 
    android:orientation="vertical" 
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> 

    <android.support.v7.widget.RecyclerView 
     android:id="@+id/recyclerView1" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content"> 
    </android.support.v7.widget.RecyclerView> 


</LinearLayout> 

病痛的對象類,Ailment.java

package com.example.visan.peds; 

public class Ailment { 
    private String name, image_url; 

    public void setName(String name){ 
     this.name=name; 
    } 
    public String getName(){ 
     return name; 
    } 

    public void setImage_url(String image_url){ 
     this.image_url=image_url; 
    } 

    public String getImage_url(){ 
     return image_url; 
    } 
} 

Adap terfor RecyclerView,LandingAdapter.java

爲recyclerView單列
package com.example.visan.peds; 

import android.content.Context; 
import android.support.v7.widget.RecyclerView; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.ImageView; 
import android.widget.TextView; 

import com.bumptech.glide.Glide; 
import com.firebase.ui.storage.images.FirebaseImageLoader; 
import com.google.firebase.storage.FirebaseStorage; 
import com.google.firebase.storage.StorageReference; 

import java.util.List; 

public class LandingAdapter extends RecyclerView.Adapter<LandingAdapter.ViewHolder>{ 

    private List<Ailment> list; 
    private Context context; 
    FirebaseStorage storage; 
    LayoutInflater inflater; 

    public LandingAdapter(List<Ailment> list, Context context){ 
     super(); 
     this.list=list; 
     this.context=context; 
     inflater=LayoutInflater.from(context); 
    } 

    @Override 
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { 
     View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.landing_list_row,parent,false); 
     ViewHolder viewHolder=new ViewHolder(itemView); 
     return viewHolder; 
    } 

    @Override 
    public void onBindViewHolder(ViewHolder holder, int position) { 
     Ailment ailment=list.get(position); 

     StorageReference storageReference=storage.getReferenceFromUrl(ailment.getImage_url()); 
     Glide.with(context).using(new FirebaseImageLoader()).load(storageReference).into(holder.imageView); 

     holder.textView.setText(ailment.getName()); 
    } 

    @Override 
    public int getItemCount() { 
     return list.size(); 
    } 

    class ViewHolder extends RecyclerView.ViewHolder{ 
     public ImageView imageView; 
     public TextView textView; 

     public ViewHolder(View view){ 
      super(view); 
      imageView=(ImageView)view.findViewById(R.id.row_image); 
      textView=(TextView)view.findViewById(R.id.row_name); 
     } 
    } 
} 

佈局文件,landing_list_row.xml

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" android:layout_width="match_parent" 
    android:layout_height="match_parent"> 
    <ImageView 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:id="@+id/row_image"/> 
    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/row_name" 
     android:layout_below="@+id/row_image"/> 

</RelativeLayout> 

回答

1

你正在呼籲getData();這是試圖它已被初始化之前訪問RecyclerView。在完成回收器視圖初始化後調用它。例如在recyclerView.setLayoutManager(layoutManager);

相關問題