数组适配器未在onDataChange()方法

时间:2018-04-06 06:12:34

标签: java android arrays firebase android-arrayadapter

这是我的ArrayAdapter:

public class SackViewAdapter extends ArrayAdapter<PostInfo> {
    private ArrayList<PostInfo> postInfo;
    private Context context;
    private LayoutInflater inflater;

    public SackViewAdapter(@NonNull Context context, int resource,ArrayList<PostInfo> postInfo) {
        super (context, resource);
        this.context = context;
        this.postInfo = postInfo;
        inflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        Log.e ("Size", String.valueOf (postInfo.size ()));
        return postInfo.size ();
    }

    @Nullable
    @Override
    public PostInfo getItem(int i) {
        return postInfo.get (i);
    }

    @NonNull
    @Override
    public View getView(int i, View view, @NonNull ViewGroup parent) {
        view  = inflater.inflate (R.layout.card_sack_view, parent,false);
        SelectableRoundedImageView imageView = view.findViewById (R.id.image_view);
        TextView name = view.findViewById (R.id.nameCards);
        TextView username = view.findViewById (R.id.usernameCards);
        imageView.setDrawingCacheEnabled (true);
        name.setText (postInfo.get (i).name);
        username.setText (postInfo.get (i).username);
        try{
            Glide.with (context).load (postInfo.get (i).Url).into (imageView);
        }catch (Exception e){
            Toast.makeText (context, e.getMessage (), Toast.LENGTH_SHORT).show ();
        }
        Log.e ("i", String.valueOf (i));
        return view;
    }
}

这是我的主要活动:

public class WallActivity extends AppCompatActivity {

    FloatingActionButton newFloatingButton;
    SackViewAdapter baseAdapter;
    ArrayList<PostInfo> postInfos;
    DatabaseReference reference = FirebaseDatabase.getInstance ().getReference ();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        setContentView (R.layout.activity_wall);
        postInfos = new ArrayList<PostInfo> ();
        String isDirectly = getIntent ().getStringExtra ("directly");
        if(isDirectly.equals ("yes")){
            AuthAsyncTask authAsyncTask = new AuthAsyncTask (WallActivity.this);
            authAsyncTask.execute ();
        }
        getData ();
        CardStackView cardStackView = findViewById(R.id.cardView);
        newFloatingButton = findViewById(R.id.newFloatingButton);
        newFloatingButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(WallActivity.this, NewItemActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.slide_up, R.anim.slide_down);
            }
        });
        cardStackView.setCardEventListener(new CardStackView.CardEventListener() {
            @Override
            public void onCardDragging(float percentX, float percentY) {

            }

            @Override
            public void onCardSwiped(SwipeDirection direction) {

            }

            @Override
            public void onCardReversed() {

            }

            @Override
            public void onCardMovedToOrigin() {

            }

            @Override
            public void onCardClicked(int index) {
                Toast.makeText(WallActivity.this, "Clicked", Toast.LENGTH_SHORT).show();
            }
        });
        baseAdapter = new SackViewAdapter (WallActivity.this,android.R.layout.simple_list_item_1, postInfos);
        cardStackView.setAdapter(baseAdapter);
    }

    public void getData(){
        reference.addValueEventListener (new ValueEventListener () {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                DataSnapshot posts = dataSnapshot.child ("Posts");
                for (DataSnapshot time: posts.getChildren ()){
                    DataSnapshot url = time.child ("Url");
                    DataSnapshot name = time.child ("Name");
                    DataSnapshot username = time.child ("Username");
                    DataSnapshot date = time.child ("Date");
                    PostInfo postInfo = new PostInfo (String.valueOf (url.getValue ()), String.valueOf (name.getValue ()), String.valueOf (username.getValue ()), String.valueOf (date.getValue ()));
                    postInfos.add (postInfo);
                }
                baseAdapter.notifyDataSetChanged ();
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                Toast.makeText (WallActivity.this, "Error 411: " + databaseError.getMessage (), Toast.LENGTH_SHORT).show ();
            }
        });
    }
}

当我从getData()函数获取所有数据时,我更新了我的数组适配器,但在更新数组列表的实际大小后,结果为7,但getView函数的值为{{1仅从0到2。它没有添加i中的所有值,而是一次又一次地显示相同的值而不是显示不同的值。这是屏幕加载时的日志,因为我在ArrayList中添加了Log.e :

getView

它没有超过2.但是当我登录 04-06 13:04:26.797 10246-10246/lifeline.learn.com.hotornot E/Value of i: 0 04-06 13:04:26.804 10246-10246/lifeline.learn.com.hotornot E/Value of i: 1 04-06 13:04:26.814 10246-10246/lifeline.learn.com.hotornot E/Value of i: 2 时,它返回7.

3 个答案:

答案 0 :(得分:1)

目前,您的getCount() urls.size ();会返回urls的大小,但您也会传递其他2个arraylists,其大小仅为{{1} arraylist。

如果您传递Arraylist<UserObject>,则可以将所有数据添加到此对象,然后将大小返回为userObjects.size();

所以更好的方法是创建一个对象,比如说UserObject并使用这个对象创建一个arraylist,如Arraylist<UserObject>

<强> UserObject.java

public class UserObject {
String urls;
String names;
String usernames;
String dates;

public UserObject(String urls, String names, String usernames, String dates) {
    this.urls = urls;
    this.names = names;
    this.usernames = usernames;
    this.dates = dates;
}
}

宣布一个arraylist

ArrayList<UserObject> userData=new ArrayList<>();

现在,像这样改变

public void onDataChange(DataSnapshot dataSnapshot) {
            DataSnapshot posts = dataSnapshot.child ("Posts");
            for (DataSnapshot time: posts.getChildren ()){
                DataSnapshot url = time.child ("Url");
                DataSnapshot name = time.child ("Name");
                DataSnapshot username = time.child ("Username");
                DataSnapshot date = time.child ("Date");
                UserObject user=new UserObject(String.valueOf (url.getValue ()),String.valueOf (name.getValue ()),String.valueOf (username.getValue ()),String.valueOf (date.getValue ()));
                userData.add(user);
            }
            baseAdapter.notifyDataSetChanged ();
        }

你的适配器构造函数将是这样的

public SackViewAdapter(@NonNull Context context, int resource,ArrayList<UserObject> userObjects)

答案 1 :(得分:0)

请不要在getData()中拨打这些电话 您已经在onCreate()上初始化它,并且每次有更改时都会调用addValueEventListener

urls.clear ();
        usernames.clear ();
        dates.clear ();
        times.clear ();

如果您使用自定义对象arraylist而不是使用三个单独的string类型列表并管理它们,那么它会更好

答案 2 :(得分:0)

检查您的网址大小,如果他们的大小为2,则只需0到2。 因为您在大小中添加适配器..

@Override
public int getCount() {
    return urls.size (); // in that provide large size of your data.
}

然后在绑定适配器之后再使用..

notifyDataSetChanged ();