Java 如何修改方法内部的数组?
我有一门课是这样的:Java 如何修改方法内部的数组?,java,android,arrays,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 workin
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;
}
}
但这让我的应用程序崩溃了。我需要编辑该方法内部的数组,因为该数组随后将从类的其他部分访问。你能告诉我怎么了吗?谢谢 这段代码运行得很好,但是如果我以相反的顺序调用您的两个方法,它将崩溃
还考虑将您的设置时间调用赋给构造函数
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();
}
}
如果数组从未初始化过,则
getCount()
方法将引发异常,因为workingowayarray
还不是数组,因此没有.length
属性。确保在调用setTimes()
之前从未调用过getCount()
解决了此问题:
String[] workingOneWayArray;
据此:
String[] workingOneWayArray = new String[1];
谢谢大家。您能提供更多此类代码吗?因为似乎没有问题,请尝试调试您的android应用程序。应用程序在getCount()方法上崩溃,但我不知道为什么您在发布getCount之前没有调用setTimes方法。向我们展示您的完整代码我建议创建这个类的构造函数,并在那里初始化您的workingOneWayArray=newstring[0];并确保在调用setTimes()之后调用getCount,还要通过使用Log.d(“APP”,“EXECUTED”)了解setTimes()是否实际执行;在这个函数内部,并在LogcatIf中检查它,我得到:“(上下文)在workingOneWayAdapter中不能被应用”如果你不能运行这个自包含的代码,你会遇到比数组更大的问题