有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java无法为BaseAdapter创建类的新实例

我有两个类,一个是创建Person新实例的Person类,另一个是创建Stopwatch新实例的Stopwatch类(它接受变量Button、Button、TextView和Person)

在我的主要功能中,我有两个编辑文本框、一个按钮和一个列表视图。我要做的是用名字和姓氏填写EditText,然后单击save。保存时,我希望将该数据保存到我个人的特定实例中。然后使用此人更新stopwatch实例中按钮的文本。每个秒表实例都应该分配一个不同的person实例,以便每个秒表具有不同的名称。到目前为止,我的保存按钮onclick侦听器没有做任何事情,我不知道为什么。现在我将getCount硬编码为1,直到我能够将一个人分配给秒表

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

主要功能:

import 安卓.annotation.SuppressLint;
import 安卓.content.Context;
import 安卓.support.v7.app.AppCompatActivity;
import 安卓.os.Bundle;
import 安卓.view.LayoutInflater;
import 安卓.view.View;
import 安卓.view.ViewGroup;
import 安卓.widget.BaseAdapter;
import 安卓.widget.Button;
import 安卓.widget.EditText;
import 安卓.widget.ListView;
import 安卓.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 安卓.graphics.Color;
import 安卓.os.Handler;
import 安卓.os.SystemClock;
import 安卓.widget.Button;
import 安卓.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) 个答案

  1. # 1 楼答案

    主要问题是BaseAdapter从未填充数据。所以你需要访问空数据。这是因为您没有正确使用BaseAdapter

    首先定义人员数据的集合。这可以通过使用阵列来实现:

    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数据后,应在下面进行此操作。 列表视图。setAdapter(新的MyBaseAdapter(这个,mPersonList))

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