无法为BaseAdapter创建新的类实例

时间:2016-06-29 15:56:43

标签: java android class instance baseadapter

我有两个Classes,一个创建人的新实例的Person Class,以及一个创建秒表新实例的秒表类(它包含变量Button,Button,TextView和Person)。

在我的主要功能中,我有两个编辑文本框,一个按钮,然后是一个列表视图。我想要做的是用First和Last名称填写EditText,然后点击保存。保存后,我想将该数据保存到我的人的特定实例。然后使用该人更新秒表实例中按钮的文本。每个秒表实例应分配一个不同的人物实例,以便每个秒表具有不同的名称。截至目前,我的保存按钮的onclick监听器没有做任何事情,我不知道为什么。现在我将getCount硬编码为一个,直到我只能将一个人分配给秒表。

很抱歉,如果这是一个愚蠢的问题,我是Java的新手

主要功能:

import android.annotation.SuppressLint;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

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

    final EditText firstName = (EditText)findViewById(R.id.FirstName);
    final EditText lastName = (EditText)findViewById(R.id.LastName);
    ListView listView = (ListView)findViewById(R.id.listView);
    final Button save =  (Button)findViewById(R.id.SaveUser);


    BaseAdapter myAdapter = new BaseAdapter() {
        @Override
        public int getCount() {
            return 1;
        }

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

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

        @SuppressLint("ViewHolder")
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            LayoutInflater inflater = (LayoutInflater) getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.stopwatchview,parent,false);

            final TextView Screen = (TextView) convertView.findViewById(R.id.Clock_View);
            final Button start = (Button) convertView.findViewById(R.id.button_start);
            Button reset = (Button) convertView.findViewById(R.id.button_reset);
            final Person person = new Person();
            final Stopwatch stopwatch = new Stopwatch(Screen,start,reset,person);;
            Button save = (Button) findViewById(R.id.SaveUser);
            final EditText first = (EditText) findViewById(R.id.FirstName);
            final EditText last = (EditText) findViewById(R.id.LastName);

            assert save != null;
            save.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    person.setName(first.getText().toString(), last.getText().toString());
                }
            });


            start.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (stopwatch.isTicking()) {
                        stopwatch.stop();
                    } else {
                        stopwatch.start();
                    }
                }
            });

            reset.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    stopwatch.reset();
                }
            });
            return convertView;
        }
    };
    listView.setAdapter(myAdapter);
}
}

秒表课程:

import android.graphics.Color;
import android.os.Handler;
import android.os.SystemClock;
import android.widget.Button;
import android.widget.TextView;

public class Stopwatch {
    TextView text;
    Button start;
    Button reset;
    Person person;


public Stopwatch(TextView t, Button Start, Button Reset, Person p){
    text = t;
    start = Start;
    reset = Reset;
    person = p;

}

long starttime = 0L;
long timeInMilliseconds = 0L;
long timeSwapBuff = 0L;
long updatedtime = 0L;
int t = 1;
int secs = 0;
int mins = 0;
int milliseconds = 0;
Handler handler = new Handler();
Runnable callback;

public void start(){
    callback = updateTimer();
    start.setText("pause");
    starttime = SystemClock.uptimeMillis();
    handler.postDelayed(callback, 0);
    t = 0;
}

public void stop(){
    text.setTextColor(Color.BLUE);
    start.setText(person.firstName);
    timeSwapBuff += timeInMilliseconds;
    handler.removeCallbacks(callback);
    t = 1;
}

public void reset(){
    stop();
    starttime = 0L;
    timeInMilliseconds = 0L;
    timeSwapBuff = 0L;
    updatedtime = 0L;
    t = 1;
    secs = 0;
    mins = 0;
    milliseconds = 0;
    if(t==0){
        handler.removeCallbacks(callback);
    }
    text.setText("00:00:00");
}

public boolean isTicking(){
    if(t==0){
        return true;
    }
    return false;
}

//Update Timer
private Runnable updateTimer() {
    return new Runnable() {
        public void run() {
            timeInMilliseconds = SystemClock.uptimeMillis() - starttime;
            updatedtime = timeSwapBuff + timeInMilliseconds;
            secs = (int) (updatedtime / 1000);
            mins = secs / 60;
            secs = secs % 60;
            milliseconds = (int) (updatedtime % 1000);
            text.setText("" + mins + ":" + String.format("%02d", secs) + ":"
                    + String.format("%03d", milliseconds));
            text.setTextColor(Color.RED);
            handler.postDelayed(this, 0);
        }
    };
};

}

人类:

public class Person {
String firstName;
String lastName;
String initials;

public Person(){
    firstName = null;
    lastName = null;
    initials = null;
};

public void setName(String FirstName, String LastName){
    firstName = FirstName;
    lastName = LastName;
    setInitials(FirstName, LastName);
}

private void setInitials(String firstName, String lastName) {
    String firstLetter = firstName.substring(0,1);
    String lastLetter = lastName.substring(0,1);
    initials = firstLetter.concat(lastLetter);
}

}

1 个答案:

答案 0 :(得分:0)

主要问题是您的BaseAdapter永远不会填充数据。所以你访问空数据。这是因为您没有正确使用BaseAdapter。

首先定义人员数据的集合。这可以使用Array实现:

ArrayList<Person> mPersonList;

然后通过扩展BaseAdapter来创建你的适配器:

public class MyBaseAdapter extends BaseAdapter {

    ArrayList<Person> mPersonList = new ArrayList()<>;
    LayoutInflater inflater;
    Context context;


    public MyBaseAdapter(Context context, ArrayList<Person> myList) {
        this.myList = myList;
        this.context = context;
        inflater = LayoutInflater.from(this.context);
    }

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

    @Override
    public ListData getItem(int position) {
        return myList.get(position);
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        MyViewHolder mViewHolder;

        if (convertView == null) {
            convertView = inflater.inflate(R.layout.layout_list_item, parent, false);
            mViewHolder = new MyViewHolder(convertView);
            convertView.setTag(mViewHolder);
        } else {
            mViewHolder = (MyViewHolder) convertView.getTag();
        }

    // get data in position
        ListData currentListData = getItem(position);

    // set data to view
        mViewHolder.edtFirstName.setText(currentListData.getFirstName());
    // add your other data to other view.

        return convertView;
    }

    private class MyViewHolder {
        EditText edtFirstName;
    // Add the other view here.

        public MyViewHolder(View item) {
            edtFirstName = (EditText) item.findViewById(R.id.FirstName);
        // add the other view here.
        }
    }
}

通过添加扩展BaseAdapter使用的setter和getter修复Person类:

public class Person {
  private String firstName;
  private String lastName;
  private String initials;

  public Person(){
    this("", "");
  };

  public Person(String FirstName, String LastName){
    firstName = FirstName;
    lastName = LastName;
    setInitials(FirstName, LastName);
  }

  private void setInitials(String firstName, String lastName) {
    String firstLetter = firstName.substring(0,1);
    String lastLetter = lastName.substring(0,1);
    initials = firstLetter.concat(lastLetter);
  }

  private void setFirstName(String firstName) {
    this.firstName = firstName;
  }

  private String firstName() {
    return this.firstName;
  }

  //ADD the other setter and getter like setFirstName and firstName method.
}

为BaseAdapter填充PersonList的一些数据:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ...
    ...
    ArrayList<Person> mPersonList = new ArrayList<Person>();
    // this is a simple data
    Person person1 = new Person("John", "Keley");
    Person person2 = new Person("Chris", "Maloy");
    Person person3 = new Person("Andery", "Dreyfus");
    Person person4 = new Person("Portgas", "D. Ace");
    Person person5 = new Person("Bankai", "Zankupatto");
    mPersonList.add(person1);
    mPersonList.add(person2);
    mPersonList.add(person3);
    mPersonList.add(person4);
    mPersonList.add(person5);
}

然后在添加人员数据后添加适配器:     //这应该在添加了mPersonList数据之后。     listView.setAdapter(new MyBaseAdapter(this,mPersonList));

...

有关完整教程,您可以查看: ListView using BaseAdapter - Android

相关问题