2017-02-20 3 views
0

Я пытаюсь использовать расширяемый список в своем приложении. Я следую за этими steps, но я застрял в том, как извлекать данные из Firebase, чтобы добавить их в Dummydata к моему коду.Загрузить данные из Firebase в ExpandableList

вот основная активность

public class MainActivity extends AppCompatActivity { 

ExpandableListAdapter myAdapter; 
ExpandableListView myList; 
List<String> listDataHeader; 
HashMap<String,List<String>> listDataChild; 

private FirebaseDatabase mFirebaseDatabase; 
private DatabaseReference mDatabaseReference; 
private ChildEventListener mChildEventListener; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    // get the listview 
    myList=(ExpandableListView)findViewById(R.id.Explist); 
    prepareListData(); 
    myAdapter= new ExpandableListAdapter(this,listDataHeader,listDataChild); 
    myList.setAdapter(myAdapter); 

} 
private void prepareListData(){ 
    mFirebaseDatabase= FirebaseDatabase.getInstance(); 
    mDatabaseReference = mFirebaseDatabase.getReference().child("category"); 
    //Read Data from Database 
    mChildEventListener = new ChildEventListener() { 
     @Override 
     public void onChildAdded(DataSnapshot dataSnapshot, String s) { 
      listDataHeader = new ArrayList<String>(); 
      listDataChild = new HashMap<String, List<String>>(); 
      listDataHeader=dataSnapshot.getValue(); 
      /* 
      * how to load data from firebase to the expandable 
      * 
      * 
      * */ 

     } 

     @Override 
     public void onChildChanged(DataSnapshot dataSnapshot, String s) { 

     } 

     @Override 
     public void onChildRemoved(DataSnapshot dataSnapshot) { 

     } 

     @Override 
     public void onChildMoved(DataSnapshot dataSnapshot, String s) { 

     } 

     @Override 
     public void onCancelled(DatabaseError databaseError) { 

     } 
    }; 
    mDatabaseReference.addChildEventListener(mChildEventListener); 

} 

вот код для адаптера

public class ExpandableListAdapter extends BaseExpandableListAdapter { 
private Context _context; 
private List<String> _listDataHeader; // header titles 
// child data in format of header title, child title 
private HashMap<String, List<String>> _listDataChild; 

public ExpandableListAdapter(Context context, List<String> listDataHeader, HashMap<String, List<String>> listDataChild) { 
    this._context = context; 
    this._listDataHeader = listDataHeader; 
    this._listDataChild = listDataChild; 

} 

@Override 
public int getGroupCount() { 
    return this._listDataHeader.size(); 
} 

@Override 
public int getChildrenCount(int groupPosition) { 
    return this._listDataChild.get(this._listDataHeader.get(groupPosition)).size(); 
} 

@Override 
public Object getGroup(int groupPosition) { 
    return this._listDataHeader.get(groupPosition); 
} 

@Override 
public Object getChild(int groupPosition, int childPosition) { 
    return this._listDataChild.get(this._listDataHeader.get(groupPosition)).get(childPosition) ; 
} 

@Override 
public long getGroupId(int groupPosition) { 
    return groupPosition; 
} 

@Override 
public long getChildId(int groupPosition, int childPosition) { 
    return childPosition; 
} 

@Override 
public boolean hasStableIds() { 
    return false; 
} 

@Override 
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { 
    String headerTitle = (String) getGroup(groupPosition); 
    if (convertView == null) { 
     LayoutInflater infalInflater = (LayoutInflater) this._context 
       .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     convertView = infalInflater.inflate(R.layout.list_gruop, null); 
    } 
    TextView lblListHeader = (TextView) convertView 
      .findViewById(R.id.lblListHeader); 
    lblListHeader.setTypeface(null, Typeface.BOLD); 
    lblListHeader.setText(headerTitle); 

    return convertView; 
} 

@Override 
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { 
    final String childText = (String) getChild(groupPosition, childPosition); 
    if(convertView == null){ 
     LayoutInflater infalInflater = (LayoutInflater) this._context 
       .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     convertView = infalInflater.inflate(R.layout.list_item, null); 
    } 
    TextView txtListChild = (TextView) convertView 
      .findViewById(R.id.lblListItem); 

    txtListChild.setText(childText); 
    return convertView;} 


@Override 
public boolean isChildSelectable(int groupPosition, int childPosition) { 
    return true; 
} 

Любая помощь приветствуется.

ответ

0

метод добавления в адаптер для обновления списка и добавление элемента в списке

 public class ExpandableListAdapter extends BaseExpandableListAdapter 
     { 
      private Context _context; 
      private List<String> _listDataHeader; // header titles 
      // child data in format of header title, child title 
      private HashMap<String, List<String>> _listDataChild; 

      public ExpandableListAdapter(Context context, List<String> listDataHeader, HashMap<String, List<String>> listDataChild) { 
       this._context = context; 
       this._listDataHeader = listDataHeader; 
       this._listDataChild = listDataChild; 

      } 

    public void addItemToList(String newItem){ 
     this._listDataChild.plus(newItem); 
     notifyDataSetChanged(); 
    } 

    public void setList(List<String> newList){ 
     this._listDataChild = listDataChild; 
     notifyDataSetChanged(); 

    } 
      ... 

И использовать эти функции в классе активность ,, (его в Котлин .. Преобразование его в Java в AS)

/* 
      * how to load data from firebase to the expandable 
      * 
      * 
      * */ 
      if (dataSnapshot != null) { 
        val newList = arrayListOf<String>() 

        for (listDataSnap in dataSnapshot.getChildren()) { 
         val newItem: String? = listDataSnap.getValue() 
         if (newItem != null) { 
           newList.add(newItem) 
         } 
        } 

        myAdapter?.setList(newList) 

       } 

* Цель состоит в том, чтобы получить представление об этом! Cheers

+0

спасибо .. но я не понимаю, что вы ссылаетесь на «DataListHeader» от newItem и «DataListChild» от newList. Я прав? @SijanGurung – labon

+0

да, вы правы! –

+0

Прошу прощения, но мне нужно определить заголовок для строки и потомка для списка строк вместо того, что я определяю правильно выше? @SijanGurung – labon