Java 如何将数据发送到自定义适配器

Java 如何将数据发送到自定义适配器,java,android,Java,Android,经过几次尝试,让一个自定义适配器工作,我几乎做到了。现在我还有一个问题:在适配器中获取数据。我就是这么做的 我有一个用于适配器的CustomListAdapter类,一个用于CRUD数据的sqLiteHelper类和一个mainActivity类。在mainActivity中,我按如下方式加载customlist: ListView list; CustomListAdapter adapter; public MainActivity CustomListView = null; publi

经过几次尝试,让一个自定义适配器工作,我几乎做到了。现在我还有一个问题:在适配器中获取数据。我就是这么做的

我有一个用于适配器的
CustomListAdapter
类,一个用于CRUD数据的
sqLiteHelper
类和一个
mainActivity
类。在mainActivity中,我按如下方式加载customlist:

ListView list;
CustomListAdapter adapter;
public  MainActivity CustomListView = null;
public  ArrayList<Players> CustomListViewValuesArr = new ArrayList<Players>();

//button handlers newmatch_players_home
public void addSpelerNu(View button) {

    Log.d("WedstrijdID buiten de create", ""+wedstrijdId);
    Log.d("id return team thuis", ""+thuisTeamId);
    //thuisteam
    final EditText shirtNummer = (EditText) findViewById(R.id.shirtThuis);
    String nummerShirt = shirtNummer.getText().toString();
    int shirtSpeler = Integer.parseInt(nummerShirt);
    final EditText spelerNaam = (EditText) findViewById(R.id.naamThuis);
    String naamSpeler = spelerNaam.getText().toString();

    Integer wedstrijdSpelerId = (int) (long) wedstrijdId;
    SqLiteHelper db = new SqLiteHelper(this);
    db.addSpeler(new Players(shirtSpeler, naamSpeler, thuisTeamId, wedstrijdSpelerId));
    Log.d("Toevoegen speler THUIS", ">> BEGIN");
    Log.d("Toevoegen speler", "Shirt = "+nummerShirt+" Naam = "+naamSpeler +" Team ="+thuisTeamId+" Wedstrijd ="+wedstrijdSpelerId);
     Log.d("Toevoegen speler", ">> EIND");

     shirtNummer.setText(null);
     spelerNaam.setText(null);


     CustomListView = this;

     /******** Take some data in Arraylist ( CustomListViewValuesArr ) ***********/

     ArrayList <Players> CustomListViewValuesArr = new ArrayList<Players>();    

    Resources res =getResources();
     list=  ( ListView )findViewById( R.id.listHome );  

     /**************** Create Custom Adapter *********/
     adapter=new CustomListAdapter( CustomListView, CustomListViewValuesArr);
     list.setAdapter( adapter );



}
如果我像这样加载这些数据

List <Players> list = new ArrayList<Players>(); 
list=db.getPlayersForTeam(thuisTeamId,wedstrijdSpelerId);    

通常,在构建自定义适配器时,您希望将ArrayList传递到CustomListAdapter的构造函数中。这是比较直截了当的

 // Create a reference to your custom adapter as a Class Member and arraylist
 CustomListAdapter mAdapter = null;
 ArrayList<MyObjects> mArrayList = null;


 // Initialize the adapter somewhere in onCreate 
 // After you have retrieved the data out of sql and created your custom object


 mArrayList = new ArrayList<MyObjects>();
 // Fill your array list with data

 // ******* THIS IS WHERE YOU WANT TO RETRIEVE THE ITEM FROM SQLITE

 // Then Each time your get a new cursor object
 // You should create a new MyObject object and add it to the ArrayList

 // Intialize the custom list adapter using the context, and your array list
 mAdpater = new CustomListAdapter(getBaseContext(), mArrayList);


 // Set ListView adapter
 listView.setAdapter(mAdapter);
//创建对自定义适配器的引用作为类成员和arraylist
CustomListAdapter mAdapter=null;
ArrayList mArrayList=null;
//在onCreate中的某个地方初始化适配器
//从sql中检索数据并创建自定义对象后
mArrayList=newarraylist();
//用数据填充数组列表
//*******这是您希望从SQLITE检索项的位置
//然后每次你得到一个新的游标对象
//您应该创建一个新的MyObject对象并将其添加到ArrayList中
//使用上下文和数组列表初始化自定义列表适配器
mAdpater=新的CustomListAdapter(getBaseContext(),mArrayList);
//设置ListView适配器
setAdapter(mAdapter);
然后创建自定义适配器并使用构造函数传递数据

 // Custom Adapter Class

public class CustomListAdapter extends BaseAdapter {


private ArrayList<MyObjects> mObjects = null;
private LayoutInflater mInflater = null;

    // Private class to hold information about the row content UI Items
private class RowContent{
    // Reference the UI Widgets for each row
        TextView mTextView;
        // etc.
}

// Constructor
public CustomListAdapter(Context context, ArrayList<MyObject> objects){
    this.mInflater = LayoutInflater.from(context);
    this.mObjects = objects;

}


// --------------------------------------------------
// BaseAdapter Overrides
// --------------------------------------------------
    // Returns the count of your arrayList
@Override
public int getCount() {
    int count = 0;

    if(mObjects!=null && mObjects.length() >= 1){

        count = mObjects.length();

    }

    return count;
}
    // Returns object at position
@Override
public Object getItem(int position) {
    // TODO Auto-generated method stub
    return mOjbects[position];
}
    // returns position
@Override
public long getItemId(int position) {
    // TODO Auto-generated method stub
    return position;
}
    // This is where all the magic happens
    // Creates a new row for each item in your arraylist
@Override
public View getView(int position, View convertView, ViewGroup parent) {

    RowContent theRow;

    // If ConvertVIew is null
    if(convertView == null){
        // Create a reference to the class holding the UI Elements
        theRow= new RowContent ();
        // set the view using your XML layout for a custom list item
        convertView = mInflater.inflate(R.layout.custom_list_item, null);
        // reference the UI widgets in the XML by their ID's            
        theRow.mTextView = (TextView) convertView.findViewById(R.id.textView);
        // set the Tag for the View         
        convertView.setTag(theRow);

    }else{
                  // If there is already an item, recycle it
        theRow= (RowContent) convertView.getTag();
    }

    // Set the Text or arrays For UI Widgets
    theRow.mtextView.setText(mObjects.get(position).text);

            // return the view
    return convertView;
}
//自定义适配器类
公共类CustomListAdapter扩展了BaseAdapter{
private ArrayList mObjects=null;
私有LayoutInflater mInflater=null;
//用于保存有关行内容UI项的信息的私有类
私有类行内容{
//参考每行的UI小部件
文本视图mTextView;
//等等。
}
//建造师
公共CustomListAdapter(上下文、ArrayList对象){
this.mInflater=LayoutInflater.from(上下文);
this.mObjects=对象;
}
// --------------------------------------------------
//BaseAdapter覆盖
// --------------------------------------------------
//返回arrayList的计数
@凌驾
public int getCount(){
整数计数=0;
if(mObjects!=null&&mObjects.length()>=1){
count=mObjects.length();
}
返回计数;
}
//返回位置处的对象
@凌驾
公共对象getItem(int位置){
//TODO自动生成的方法存根
返回mOjbects[位置];
}
//返回位置
@凌驾
公共长getItemId(int位置){
//TODO自动生成的方法存根
返回位置;
}
//这就是所有魔法发生的地方
//为arraylist中的每个项目创建新行
@凌驾
公共视图getView(int位置、视图转换视图、视图组父视图){
Rowtherow;
//如果ConvertVIew为空
if(convertView==null){
//创建对包含UI元素的类的引用
theRow=新行内容();
//使用自定义列表项的XML布局设置视图
convertView=mInflater.充气(R.layout.custom\u list\u项,空);
//通过ID引用XML中的UI小部件
theRow.mTextView=(TextView)convertView.findViewById(R.id.TextView);
//设置视图的标记
convertView.setTag(theRow);
}否则{
//如果已经有项目,请将其回收
theRow=(RowContent)convertView.getTag();
}
//设置UI小部件的文本或数组
theRow.mtextView.setText(mObjects.get(position.text));
//返回视图
返回视图;
}
}

onCreate()中执行以下操作:

ArrayList <Players> CustomListViewValuesArr = new ArrayList<Players>();
...
adapter=new CustomListAdapter( CustomListView, CustomListViewValuesArr);
ArrayList CustomListViewValuesAR=new ArrayList();
...
适配器=新的CustomListAdapter(CustomListView、CustomListViewValuesR);
您正在使用空的项目列表初始化适配器(
CustomListViewValuesR
为空)

您有两种选择:

  • 您可以从数据库中获取数据,并在初始化时将其传递给适配器

  • 您可以使用空数组初始化适配器,然后稍后将数据传递给适配器。为此,您需要在适配器中提供一个setter方法,如下所示:

    ListView list;
    CustomListAdapter adapter;
    public  MainActivity CustomListView = null;
    public  ArrayList<Players> CustomListViewValuesArr = new ArrayList<Players>();
    
    //button handlers newmatch_players_home
    public void addSpelerNu(View button) {
    
        Log.d("WedstrijdID buiten de create", ""+wedstrijdId);
        Log.d("id return team thuis", ""+thuisTeamId);
        //thuisteam
        final EditText shirtNummer = (EditText) findViewById(R.id.shirtThuis);
        String nummerShirt = shirtNummer.getText().toString();
        int shirtSpeler = Integer.parseInt(nummerShirt);
        final EditText spelerNaam = (EditText) findViewById(R.id.naamThuis);
        String naamSpeler = spelerNaam.getText().toString();
    
        Integer wedstrijdSpelerId = (int) (long) wedstrijdId;
        SqLiteHelper db = new SqLiteHelper(this);
        db.addSpeler(new Players(shirtSpeler, naamSpeler, thuisTeamId, wedstrijdSpelerId));
        Log.d("Toevoegen speler THUIS", ">> BEGIN");
        Log.d("Toevoegen speler", "Shirt = "+nummerShirt+" Naam = "+naamSpeler +" Team ="+thuisTeamId+" Wedstrijd ="+wedstrijdSpelerId);
         Log.d("Toevoegen speler", ">> EIND");
    
         shirtNummer.setText(null);
         spelerNaam.setText(null);
    
    
         CustomListView = this;
    
         /******** Take some data in Arraylist ( CustomListViewValuesArr ) ***********/
    
         ArrayList <Players> CustomListViewValuesArr = new ArrayList<Players>();    
    
        Resources res =getResources();
         list=  ( ListView )findViewById( R.id.listHome );  
    
         /**************** Create Custom Adapter *********/
         adapter=new CustomListAdapter( CustomListView, CustomListViewValuesArr);
         list.setAdapter( adapter );
    
    
    
    }
    
    public void setData(ArrayList d){ 数据=d; //告诉视图数据已更改,以便它们可以刷新 notifyDataSetChanged(); }


  • 这是完全错误的。在这里,您应该在ArrayList中的指定位置返回对象。

    您可以发布完整的addSpelerNu方法或更好的完整活动类Done吗。我使用addSpelerNu作为按钮的onClick事件,我可以看到您只需在适配器的构造函数中传递空数组,这解释了为什么它在listview中总是说“无数据”:(您在哪里看到数组是空的?
    ArrayList <Players> CustomListViewValuesArr = new ArrayList<Players>();
    ...
    adapter=new CustomListAdapter( CustomListView, CustomListViewValuesArr);
    
    public Object getItem(int position) {
                 return position;
             }
    
             public long getItemId(int position) {
                 return position;
             }