如何修改方法内的数组?

时间:2015-07-19 12:10:21

标签: java android arrays

我有一个课程:

import android.content.Context;
import android.graphics.Color;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class workingOneWayAdapter extends BaseAdapter {

    private Context mContext;

    public workingOneWayAdapter(Context c) {
        mContext = c;
    }

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

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

    public View getView(int position, View convertView, ViewGroup parent) {
        TextView workingLabel;
        if (convertView == null) {
            workingLabel = new TextView(mContext);
            workingLabel.setLayoutParams(new MyGridView.LayoutParams(85, 85));
            workingLabel.setPadding(10, 5, 5, 5);
            workingLabel.setTextColor(Color.parseColor("#000000"));
            workingLabel.setTextSize(TypedValue.COMPLEX_UNIT_SP, 19);
            workingLabel.setSingleLine();

            setTimes();

        } else {
            workingLabel = (TextView) convertView;
        }

        workingLabel.setText(workingOneWayArray[position]);
        return workingLabel;
    }

    String[] workingOneWayArray;

    void setTimes() {

        workingOneWayArray = new String[] { "00:00" };    
    }

    public int getCount() {
        return workingOneWayArray.length;
    }
}

但这会让我的应用程序崩溃。我需要编辑方法内部的数组,因为然后从类的其他部分访问该数组。你能告诉我有什么问题吗?谢谢!

3 个答案:

答案 0 :(得分:0)

此代码工作正常,但如果我以相反的顺序调用您的两个方法,它将崩溃。

还要考虑将setTimes调用放在构造函数

public test() {
    setTimes();
}

或者只是简单地创建你的数组...

String[] workingOneWayArray = new String[] { "00:00" };

这是工作代码

public class test {


  String[] workingOneWayArray;

   void setTimes() {

     // THIS DOESN'T WORK

      workingOneWayArray = new String[] { "00:00" };

  }

  public int getCount() {
      return workingOneWayArray.length;
  }

  public static void main(String[] args) {
    test t = new test();

    t.setTimes();
    t.getCount();

  }

}

答案 1 :(得分:0)

如果数组从未被初始化,则getCount()方法将抛出异常,因为workingOneWayArray不是数组,因此没有.length属性。确保在getCount()之前永远不会调用setTimes()

答案 2 :(得分:0)

解决了这个问题:

String[] workingOneWayArray;

由此:

String[] workingOneWayArray = new String[1];

谢谢大家。