简体   繁体   English

添加列表<String>朋友 = 新的 ArrayList&lt;&gt;(); 自定义列表视图

[英]adding List<String> friends = new ArrayList<>(); to customlistview

Cannot add List to custom list view.无法将列表添加到自定义列表视图。 im having trouble with String[] , i was trying to get my users from firebase database and stores it to my private ArrayList<UserInfo> userInfos;我在使用 String[] 时遇到问题,我试图从 firebase 数据库中获取我的用户并将其存储到我的private ArrayList<UserInfo> userInfos; userInfos=new ArrayList<>(); but when running it to emulator my listview is showing blank,i've tried checking the List<String> friends = new ArrayList<>();但是当运行它到模拟器时,我的列表视图显示为空白,我尝试检查List<String> friends = new ArrayList<>(); and my users are available., Could anyone please help me with this?并且我的用户可用。,有人可以帮我吗?

My MainActivityCustonlistViewnew.java我的 MainActivityCustonlistViewnew.java

import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

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.Arrays;
import java.util.List;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.appcompat.widget.Toolbar;



public class MainActivityCustonlistViewnew extends AppCompatActivity {



    private ArrayList<UserInfo> userInfos;
    private CustomListAdapter customListAdapter;
    private ListView customListView;



    private FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
    private DatabaseReference databaseReference = firebaseDatabase.getReference();

    private  DatabaseReference UserData = databaseReference.child("Users");


    private List<String> friends = new ArrayList<>();

    private String[] names ;


    private String[] professions={
            "Rank 1",
            "Rank 2",
            "Rank 3"

    };
    private int[] photos={
            R.drawable.sample_5,
            R.drawable.sample_1,
            R.drawable.sample_6

    };



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maincustomlistview);
        setSupportActionBar((Toolbar)findViewById(R.id.toolbar));


       // ArrayList arrayList = new ArrayList(friends);

        ValueEventListener eventListener = new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                for(DataSnapshot ds : dataSnapshot.getChildren()) {
                    String friend = ds.getKey();

                    friends.add(friend);



                }

        }

            @Override
            public void onCancelled(DatabaseError databaseError) {}
        };
        UserData.addListenerForSingleValueEvent(eventListener);




        customListView=(ListView)findViewById(R.id.custom_list_view);
        userInfos=new ArrayList<>();
        Arrays.sort(names, String.CASE_INSENSITIVE_ORDER);
        customListAdapter=new CustomListAdapter(userInfos,MainActivityCustonlistViewnew.this);
        customListView.setAdapter(customListAdapter);
        getDatas();
        customListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Toast.makeText(MainActivityCustonlistViewnew.this, "Name : " + names[i] + "\n Profession : " + professions[i], Toast.LENGTH_SHORT).show();
            }
        });



//sample-----












    }

    // getting all the datas
    private void getDatas(){




        for(int count=0;count<names.length;count++){

            userInfos.add(new UserInfo(names[count],professions[count],photos[count]));

        }
    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.search_option,menu);
        MenuItem menuItem=menu.findItem(R.id.search);
        SearchView searchView=(SearchView)menuItem.getActionView();
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                newText=newText.toString();
                ArrayList<UserInfo> newUserInfos=new ArrayList<>();

                for(UserInfo userInfo:userInfos){
                    String name=userInfo.getName().toLowerCase();
                    String profession=userInfo.getProfession().toLowerCase();
                    if(name.contains(newText) || profession.contains(newText)){
                        newUserInfos.add(userInfo);
                    }
                }
                customListAdapter.filterResult(newUserInfos);
                customListAdapter.notifyDataSetChanged();
                return false;
            }
        });
        return super.onCreateOptionsMenu(menu);
    }
}

my Userinfo.java我的用户信息.java

public class UserInfo {
    private String name,profession;
    private int photo;

    public UserInfo(){}

    public UserInfo(String name, String profession, int photo) {
        this.name = name;
        this.profession = profession;
        this.photo = photo;
    }

    public String getName() {
        return name;
    }

    public String getProfession() {
        return profession;
    }

    public int getPhoto() {
        return photo;
    }
}

my customlistAdapter我的自定义列表适配器

import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

public class CustomListAdapter extends BaseAdapter implements View.OnClickListener{
    private ArrayList<UserInfo> userInfos;
    private Context context;

    public CustomListAdapter(ArrayList<UserInfo> userInfos, Context context) {
        this.userInfos = userInfos;
        this.context = context;
    }

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

    @Override
    public Object getItem(int i) {
        return null;
    }

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

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        LayoutInflater layoutInflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view=layoutInflater.inflate(R.layout.custom_list_view_layout,null);
        ImageView photo,option;
        if(view==null){
            photo=new ImageView(context);
        }
        UserInfo userInfo=userInfos.get(i);
        photo=(ImageView)view.findViewById(R.id.photo);
        option=(ImageView)view.findViewById(R.id.option);
        TextView name=(TextView)view.findViewById(R.id.name);
        TextView profession=(TextView)view.findViewById(R.id.profession);
        photo.setImageResource(userInfo.getPhoto());
        name.setText(userInfo.getName());
        profession.setText(userInfo.getProfession());
        option.setOnClickListener(this);
        return view;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
           case R.id.option:
               showPopupMenu(view);
                break;
        }
    }

    // getting the popup menu
    private void showPopupMenu(View view){
        PopupMenu popupMenu=new PopupMenu(context,view);
        popupMenu.getMenuInflater().inflate(R.menu.option_menu,popupMenu.getMenu());
        popupMenu.show();
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem menuItem) {
                switch (menuItem.getItemId()){
                    case R.id.edit:
                        Toast.makeText(context, "Edit !", Toast.LENGTH_SHORT).show();
                        return true;
                    case R.id.remove:
                        Toast.makeText(context, "Remove !", Toast.LENGTH_SHORT).show();
                        return true;
                    default:
                        return false;
                }
            }
        });
    }

    //file search result
    public void filterResult(ArrayList<UserInfo> newUserInfos){
        userInfos=new ArrayList<>();
        userInfos.addAll(newUserInfos);
        notifyDataSetChanged();
    }
}
  customListAdapter=new CustomListAdapter(userInfos,MainActivityCustonlistViewnew.this);
        customListView.setAdapter(customListAdapter);
        getDatas();

You are doing wrong here.你在这里做错了。 you are calling customListAdapter and setting cusrom data(userInfos) empty here.您正在调用 customListAdapter 并将 cusrom data(userInfos) 设置为空。 Because getDatas() method called after customListAdapter .因为在 customListAdapter 之后调用了 getDatas() 方法。 Hence list will be empty.因此列表将为空。 Just interchange the positron.只需交换正电子。

getDatas();
customListAdapter=new CustomListAdapter(userInfos,MainActivityCustonlistViewnew.this);
customListView.setAdapter(customListAdapter);

Hope It helps.希望能帮助到你。

Thanks Saurabh Happy Coding !!!感谢 Saurabh 快乐编码!!!

You're adding data from getDatas() but your adapter is already being initialized with empty data.您正在从getDatas()添加数据,但您的适配器已使用空数据进行初始化。 So there are 2 ways :所以有两种方法:

1 : Initialize and Set adapter after getDatas() call 1 : getDatas()调用后初始化和设置适配器

    getDatas();
    customListAdapter=new CustomListAdapter(userInfos,MainActivityCustonlistViewnew.this);
    customListView.setAdapter(customListAdapter);

2 : Inform adapter about dataset changes using notifyDataSetChanged() method 2 : 使用notifyDataSetChanged()方法通知适配器数据集更改

    customListView.setAdapter(customListAdapter);
    getDatas();
    customListAdapter.notifyDataSetChanged();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Java:清单 <List<String> &gt; list = new ArrayList &lt;&gt;(); - Java: List<List<String>> list = new ArrayList<>(); 清单之间有区别吗 <String> A =新的ArrayList <String> ()和ArrayList <String> A =新的ArrayList <String> ()? - Is there a difference between List<String> A = new ArrayList<String> ( ) and ArrayList<String> A = new ArrayList<String>()? 将String,ArrayList等对象添加到List <Object> - Adding String,ArrayList, etc objects to List<Object> 列表<?>列表 = 新的 ArrayList<String> (); 列表<? extends Object>列表 = 新的 ArrayList<String> (); - List<?> list = new ArrayList<String>(); List<? extends Object> list = new ArrayList<String>(); 将字符串添加到ArrayList <ArrayList<String[]> &gt; - Adding string to ArrayList<ArrayList<String[]>> List 和 List 有什么区别<String> stringList = 新的 ArrayList<String> () 和列表<String> stringList = new ArrayList()? - Whats the difference between List<String> stringList = new ArrayList<String>() and List<String> stringList = new ArrayList()? 向数组列表添加一个字符串<String> - adding a string to an arraylist<String> 向数组列表添加新对象 - Adding a new object to an arraylist 为什么列出 <Object> list =新的ArrayList <String> ()这会导致TypeMismatch错误 - Why List<Object> list = new ArrayList<String>() this give TypeMismatch error 将String对象添加到ArrayList - Adding String object to ArrayList
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM