从EditTexts计算平均值

时间:2014-08-21 14:58:53

标签: android android-listview android-edittext textview

在我的活动中,有两个按钮:一个用于向ListView添加项目,ListView由EditText(用户输入十进制数字)和另一个(将开始计算)形成。目标是计算在EditTexts中输入的数字的平均值,具体取决于添加到ListView的项目数。

以下是活动的代码:

public class PersActivity extends Activity {

Button start, calcaverage1;
ListView MarkListView;
TextView markresult;
private SubjectAdapter adapter;


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

    setupListViewAdapter();

    setupAddMarkButton();

    // Start button
            start = (Button)findViewById(R.id.start1);
            start.setOnClickListener(new OnClickListener() 
            {   public void onClick(View v) 
                {   
                    Intent intent = new Intent(PersActivity.this, MainActivity.class);
                        startActivity(intent);      
                        finish();
                }
            });

    // Calc average button
            calcaverage1 = (Button) findViewById(R.id.calcaverage);
            calcaverage1.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    addNumberFromText();                        
                }
            });
}

public void removeClick(View v) {
    Mark itemToRemove = (Mark)v.getTag();
    adapter.remove(itemToRemove);
}

private void setupListViewAdapter() {
    adapter = new SubjectAdapter(PersActivity.this, R.layout.subject_list_item, new ArrayList<Mark>());
    MarkListView = (ListView)findViewById(R.id.subject_list_item);
    MarkListView.setAdapter(adapter);
}

private void setupAddMarkButton() {
    findViewById(R.id.addsubject).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            adapter.insert(new Mark("", 0), 0);
        }
    });
}
void addNumberFromText()
{
    double total=0;
    for(int i=0;i<MarkListView.getChildCount();i++)
    {
        View wantedView = MarkListView.getChildAt(i);
        markresult = (TextView)wantedView.findViewById(R.id.subjectmark);
        double value=Double.parseDouble(markresult.toString());
        total+=value;
    }
    Log.d("PersActivity","total sum is "+total);
}

}

这是我使用的适配器的代码:

public class SubjectAdapter extends ArrayAdapter<Mark> {

protected static final String LOG_TAG = SubjectAdapter.class.getSimpleName();

private List<Mark> items;
private int layoutResourceId;
private Context context;

public SubjectAdapter(Context context, int layoutResourceId, List<Mark> items) {
    super(context, layoutResourceId, items);
    this.layoutResourceId = layoutResourceId;
    this.context = context;
    this.items = items;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View row = convertView;
    MarkHolder holder = null;

    LayoutInflater inflater = ((Activity) context).getLayoutInflater();
    row = inflater.inflate(layoutResourceId, parent, false);

    holder = new MarkHolder();
    holder.Mark = items.get(position);
    holder.removeButton = (ImageButton)row.findViewById(R.id.remove);
    holder.removeButton.setTag(holder.Mark);

    holder.name = (TextView)row.findViewById(R.id.subjectname);
    setNameTextChangeListener(holder);
    holder.value = (TextView)row.findViewById(R.id.subjectmark);
    setValueTextListeners(holder);

    row.setTag(holder);

    setupItem(holder);
    return row;
}

private void setupItem(MarkHolder holder) {
    holder.name.setText(holder.Mark.getName());
    holder.value.setText(String.valueOf(holder.Mark.getValue()));
}

public static class MarkHolder {
    Mark Mark;
    TextView name;
    TextView value;
    ImageButton removeButton;
}

private void setNameTextChangeListener(final MarkHolder holder) {
    holder.name.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            holder.Mark.setName(s.toString());
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) { }

        @Override
        public void afterTextChanged(Editable s) { }
    });
}

private void setValueTextListeners(final MarkHolder holder) {
    holder.value.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            try{
                holder.Mark.setValue(Double.parseDouble(s.toString()));
            }catch (NumberFormatException e) {
                Log.e(LOG_TAG, "error reading double value: " + s.toString());
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) { }

        @Override
        public void afterTextChanged(Editable s) { }
    });
}
}

按下按钮后,将通过TextView显示结果。

以下是该活动的屏幕截图。实际上它没有错误,但当我尝试开始活动时应用程序停止。

enter image description here

EDIT3: LogCat错误

08-21 15:59:34.170: E/AndroidRuntime(1678): FATAL EXCEPTION: main
08-21 15:59:34.170: E/AndroidRuntime(1678): java.lang.NumberFormatException: Invalid double: "android.widget.EditText@536f3e10"
08-21 15:59:34.170: E/AndroidRuntime(1678):     at java.lang.StringToReal.invalidReal(StringToReal.java:63)
08-21 15:59:34.170: E/AndroidRuntime(1678):     at java.lang.StringToReal.initialParse(StringToReal.java:114)
08-21 15:59:34.170: E/AndroidRuntime(1678):     at java.lang.StringToReal.parseDouble(StringToReal.java:263)
08-21 15:59:34.170: E/AndroidRuntime(1678):     at java.lang.Double.parseDouble(Double.java:295)
08-21 15:59:34.170: E/AndroidRuntime(1678):     at com.isa.gestordecurso.PersActivity.addNumberFromText(PersActivity.java:81)
08-21 15:59:34.170: E/AndroidRuntime(1678):     at com.isa.gestordecurso.PersActivity$2.onClick(PersActivity.java:49)
08-21 15:59:34.170: E/AndroidRuntime(1678):     at android.view.View.performClick(View.java:4084)
08-21 15:59:34.170: E/AndroidRuntime(1678):     at android.view.View$PerformClick.run(View.java:16966)
08-21 15:59:34.170: E/AndroidRuntime(1678):     at android.os.Handler.handleCallback(Handler.java:615)
08-21 15:59:34.170: E/AndroidRuntime(1678):     at android.os.Handler.dispatchMessage(Handler.java:92)
08-21 15:59:34.170: E/AndroidRuntime(1678):     at android.os.Looper.loop(Looper.java:137)
08-21 15:59:34.170: E/AndroidRuntime(1678):     at android.app.ActivityThread.main(ActivityThread.java:4745)
08-21 15:59:34.170: E/AndroidRuntime(1678):     at java.lang.reflect.Method.invokeNative(Native Method)
08-21 15:59:34.170: E/AndroidRuntime(1678):     at java.lang.reflect.Method.invoke(Method.java:511)
08-21 15:59:34.170: E/AndroidRuntime(1678):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
08-21 15:59:34.170: E/AndroidRuntime(1678):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
08-21 15:59:34.170: E/AndroidRuntime(1678):     at dalvik.system.NativeStart.main(Native Method)

希望有一个解决方案!非常感谢你!

2 个答案:

答案 0 :(得分:1)

在您的代码段中,您似乎忘记初始化calcaverage1按钮。这就是您在尝试调用setOnClickListener时获得NullPointerException的原因。只需声明并初始化calcaverage1按钮。

Button calcaverage1= (Button)findViewById(R.id.calc);
calcaverage1.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
         addNumberFromText();                        
    }
});

编辑:

对于第二个NullPointerException: 您已创建成员变量ListView MarkListView;。但是,你没有初始化它。相反,您创建了一个具有相同名称的局部变量 setupListViewAdapter方法中的ListView MarkListView = (ListView)findViewById(R.id.subject_list_item);。 这是一个完全不同的变量。

将此行替换为:

ListView MarkListView = (ListView)findViewById(R.id.subject_list_item);

这一行:

MarkListView = (ListView)findViewById(R.id.subject_list_item);

答案 1 :(得分:0)

根据logCat堆栈跟踪,您将获得数字格式异常。改变这一行:

double value=Double.parseDouble(markresult.toString());

要:

double value=Double.parseDouble(markresult.getText());