Java ArrayList中nameArr的空值
我在下面的源代码中得到了nameArr的空值,我不知道为什么 当我尝试使用以下内容时:Java ArrayList中nameArr的空值,java,android,arrays,arraylist,nullpointerexception,Java,Android,Arrays,Arraylist,Nullpointerexception,我在下面的源代码中得到了nameArr的空值,我不知道为什么 当我尝试使用以下内容时: System.out.println("testing123"); System.out.println(nameArr); 我得到: 08-07 19:51:53.540: I/System.out(1048): testing123 08-07 19:51:53.540: I/System.out(1048): [] 现在看来它是空的-有什么建议吗 我真的不知道为什么会这样 资料来源: public
System.out.println("testing123");
System.out.println(nameArr);
我得到:
08-07 19:51:53.540: I/System.out(1048): testing123
08-07 19:51:53.540: I/System.out(1048): []
现在看来它是空的-有什么建议吗
我真的不知道为什么会这样
资料来源:
public class UpdateActivity extends Activity implements OnClickListener {
public static ArrayList<String> NameArr = new ArrayList<String>();
public static ArrayList<String> ValueArr = new ArrayList<String>();
public static ArrayList<String> nameArr = new ArrayList<String>();
public static ArrayList<String> ApnArr = new ArrayList<String>();
public static ArrayList<String> mmscArr = new ArrayList<String>();
public static ArrayList<String> mmsportArr = new ArrayList<String>();
public static ArrayList<String> mmsproxyArr = new ArrayList<String>();
public static ArrayList<String> portArr = new ArrayList<String>();
public static ArrayList<String> proxyArr = new ArrayList<String>();
public static int count;
AlertDialog mErrorAlert = null;
public static int TotalSteps = 8;
private TelephonyManager tm;
private static final String LOG_TAG = "STDataSettings";
private Button mUpdateButton = null;
private Button mAssistUpdateButton = null;
private Button mAssistInstrButton = null;
private TextView mReadAgainButton = null;
private int mInstructionNumber = 0;
AlertDialog mConfirmAlert = null;
public static InputStream stream = null;
public static XmlParserHandlerFinal handler;
private NetworkTask task;
private AnimationDrawable loadingAnimation;
private static final String TAG = "UpdateActivity";
Context ctx;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
int networkType = tm.getNetworkType();
int phoneType = tm.getPhoneType();
task = new NetworkTask();
handler = new XmlParserHandlerFinal();
handler.setContext(ctx);
int version = android.os.Build.VERSION.SDK_INT;
if (phoneType == TelephonyManager.PHONE_TYPE_CDMA
|| (phoneType != TelephonyManager.PHONE_TYPE_GSM
&& networkType != TelephonyManager.NETWORK_TYPE_GPRS
&& networkType != TelephonyManager.NETWORK_TYPE_EDGE
&& networkType != TelephonyManager.NETWORK_TYPE_HSDPA
&& networkType != TelephonyManager.NETWORK_TYPE_HSPA
&& networkType != TelephonyManager.NETWORK_TYPE_HSPAP
&& networkType != TelephonyManager.NETWORK_TYPE_HSUPA
&& networkType != TelephonyManager.NETWORK_TYPE_UMTS && networkType != TelephonyManager.NETWORK_TYPE_LTE)) {
// If the phone type is CDMA or
// the phone phone type is not GSM and the network type is none of
// the network types indicated in the statement
// Display incompatibility message
showAlert(getString(R.string.incomp_sm_dialog));
// Network type is looked because some tablets have no phone type.
// We rely on network type in such cases
} else if (!(tm.getSimState() == TelephonyManager.SIM_STATE_ABSENT
|| (tm.getSimOperator())
.equals(getString(R.string.numeric_tmo)) || (tm
.getSimOperator()).equals(getString(R.string.numeric_att)))) {
// if SIM is present and is NOT a T-Mo network SIM,
// display Error message alert indicating to use SM SIM
showAlert(getString(R.string.insert_sm_dialog));
}// No SIM or SIM with T-Mo MNC MCC present
else if (version < VERSION_CODES.ICE_CREAM_SANDWICH) {
// Initial UI setup for versions lower than ICS
setContentView(R.layout.update);
mUpdateButton = (Button) findViewById(R.id.update_button);
mUpdateButton.setOnClickListener(this);
} else {// ICS and up
// task.execute();
if ((tm.getSimOperator()).equals(getString(R.string.numeric_tmo))
|| (tm.getSimOperator())
.equals(getString(R.string.numeric_att))) {
// Update APN table in separate thread
task.execute("");
// Device has T-Mo network SIM card MCC and MNC correctly
// populated
// Reduce number of steps to 6
TotalSteps = 6;
}
//
// Initial UI setup for ICS and up
// setContentView(R.layout.updating);
// String assistUpdate = getString(R.string.apn_app_text_cta2);
// CharSequence styledText = Html.fromHtml(assistUpdate);
// xtView assistText = (TextView)
// findViewById(R.id.apn_app_text_cta2);
// sistText.setText(styledText);
// mAssistUpdateButton = (Button)
// findViewById(R.id.assist_update_btn);
//mAssistUpdateButton.setOnClickListener(this);
}
}
public void onClick(View v) {
if (v == mUpdateButton) {
// Update button for versions lower than ICS is selected
// setContentView(R.layout.updating);
onClickMethod(v);
Intent i = new Intent(this, ConfigFinalActivity.class);
startActivity(i);
finish();
} else if (v == mAssistUpdateButton) {
// Update button for ICS and up is selected
// Get the TextView in the Assist Update UI
TextView tv = (TextView) findViewById(R.id.apn_app_text_cta2);
String text = "";
CharSequence styledText = text;
switch (mInstructionNumber) {
case 0:
// Retrieve the instruction string resource corresponding the
// 2nd set of instructions
text = String.format(getString(R.string.apn_app_text_instr),
TotalSteps);
styledText = Html.fromHtml(text);
// Update the TextView with the correct set of instructions
tv.setText(styledText);
// Increment instruction number so the correct instructions
// string resource can be retrieve the next time the update
// button is pressed
mInstructionNumber++;
break;
case 1:
text = getString(R.string.apn_app_text_instr2);
styledText = Html.fromHtml(text);
tv.setText(styledText);
// Increment instruction number so the correct instructions
// string resource can be retrieve the next time the update
// button is pressed
mInstructionNumber++;
break;
case 2:
// Final set of instructions-Change to the corresponding layout
setContentView(R.layout.assist_instructions);
String assistUpdateInstr = String.format(
getString(R.string.apn_app_text_instr3), TotalSteps);
styledText = Html.fromHtml(assistUpdateInstr);
TextView assistInstrText = (TextView) findViewById(R.id.updated_text);
assistInstrText.setText(styledText);
mAssistInstrButton = (Button) findViewById(R.id.assist_instr_btn);
mReadAgainButton = (TextView) findViewById(R.id.read_again_btn);
mAssistInstrButton.setOnClickListener(this);
mReadAgainButton.setOnClickListener(this);
}
} else if (v == mAssistInstrButton) {
// "LET'S DO THIS" Button in final instructions screen for ICS and
// up is selected
// Create ConfigActivity Intent
Intent i = new Intent(this, ConfigFinalActivity.class);
// Invoke ConfigActivity Intent to start the assisted update
startActivity(i);
finish();
} else if (v == mReadAgainButton) {
// go back to 1st set of instructions if read again is selected
mInstructionNumber = 0;
setContentView(R.layout.assist_update);
String assistUpdate = getString(R.string.apn_app_text_cta2);
CharSequence styledText = Html.fromHtml(assistUpdate);
TextView assistText = (TextView) findViewById(R.id.apn_app_text_cta2);
assistText.setText(styledText);
mAssistUpdateButton = (Button) findViewById(R.id.assist_update_btn);
mAssistUpdateButton.setOnClickListener(this);
}
}
public void onClickMethod(View v) {
mUpdateButton = (Button) findViewById(R.drawable.btn_update_active_hdpi);
}
private void showAlert(String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(message).setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
UpdateActivity.this.finish();
}
});
mConfirmAlert = builder.create();
mConfirmAlert.show();
}
// AsyncTask to call web service
private class NetworkTask extends AsyncTask<String, Integer, InputStream> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected InputStream doInBackground(String... params) {
try {
// saving the response in InputStream
stream = getQueryResults("https://dl.dropboxusercontent.com/u/31771876/GetPhoneSettings-rsp-eng.xml");
// stream = new BufferedInputStream(https.getInputStream());
DataInputStream in = new DataInputStream(stream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) { // Print the content on the console
System.out.println (strLine);
in.close();
}
} catch (IOException e) {
Log.v(LOG_TAG, e.toString());
e.printStackTrace();
} catch (SAXException e) {
Log.v(LOG_TAG, e.toString());
e.printStackTrace();
} catch (Exception e) {
Log.v(LOG_TAG, e.toString());
e.printStackTrace();
}
// The code below plays a Simple Promo animation
for (int incr = 0; incr < 2; incr++) {
// Sleep for 1/2 second
// Invoke UI to change updating text to show 1 dot
// And Increasing the level to reduce the amount of clipping and
// slowly reveals the hand image
publishProgress(R.drawable.loading_full,
R.drawable.loading_empty, R.drawable.loading_empty,
R.drawable.loading_empty, R.drawable.loading_empty);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.d(TAG, "sleep failure");
}
publishProgress(R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_empty,
R.drawable.loading_empty, R.drawable.loading_empty);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.d(TAG, "sleep failure");
}
publishProgress(R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_full,
R.drawable.loading_empty, R.drawable.loading_empty);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.d(TAG, "sleep failure");
}
publishProgress(R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_empty);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.d(TAG, "sleep failure");
}
publishProgress(R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_full);
// Sleep for 1/2 second
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.d(TAG, "sleep failure");
}
}
return stream;
}
/*
* Sends a query to server and gets back the parsed results in a bundle
* urlQueryString - URL for calling the webservice
*/
protected synchronized InputStream getQueryResults(String urlQueryString)
throws IOException, SAXException, SSLException,
SocketTimeoutException, Exception {
// HttpsURLConnection https = null;
HttpsURLConnection https = null;
String uri = urlQueryString;
URL urlo = new URL(uri);
try {
https = (HttpsURLConnection) urlo.openConnection();
https.setConnectTimeout(20000); // 20 second timeout
https.setRequestProperty("Connection", "Keep-Alive");
if ("gzip".equals(https.getContentEncoding())) {
stream = new GZIPInputStream(stream);
} else
stream = https.getInputStream();
} catch (SSLException e) {
Log.e(LOG_TAG, e.toString());
e.printStackTrace();
} catch (SocketTimeoutException e) {
Log.e(LOG_TAG, e.toString());
e.printStackTrace();
} catch (IOException e) {
Log.e(LOG_TAG, e.toString());
e.printStackTrace();
} catch (Exception e) {
Log.e(LOG_TAG, e.toString());
e.printStackTrace();
} finally {
// https.disconnect();
}
return stream;
}
@Override
protected void onProgressUpdate(Integer... progress) {
// Call function to update image view
setProgressImgView(progress[0], progress[1]);
}
@Override
protected void onPostExecute(InputStream stream) {
super.onPostExecute(stream);
// This method is called to parse the response and save the ArrayLists
success();
}
}
private void setProgressImgView(Integer textViewId, Integer imageViewId) {
// update image view with the updating dots
// Reset view layout in case orientation while updating
//setContentView(R.layout.updating);
}
@Override
protected void onRestart() {
super.onRestart();
if (mErrorAlert != null)
mErrorAlert.dismiss();
}
public void success() {
// to parse the response
try {
handler.getQueryResponse(stream);
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// to set method to save the ArryaLists from the parser
setArrayList();
Intent i = new Intent(this, ConfigFinalActivity.class);
startActivity(i);
finish();
}
// method to save the ArrayLists from parser
public static void setArrayList() {
//nameArr = handler.getnameArr();
nameArr.addAll(handler.getnameArr());
ApnArr = handler.getApnArr();
mmscArr = handler.getMMSCArr();
mmsproxyArr = handler.getMmscProxyArr();
mmsportArr = handler.getMmsPortArr();
proxyArr = handler.getMmscProxyArr();
portArr = handler.getMmsPortArr();
count = handler.getCount();
System.out.println("testing123");
System.out.println(nameArr);
}
}
日志:
08-07 21:30:24.510: E/AndroidRuntime(1998): FATAL EXCEPTION: main
08-07 21:30:24.510: E/AndroidRuntime(1998): java.lang.NullPointerException
08-07 21:30:24.510: E/AndroidRuntime(1998): at com.project.new.datasettings.ConfigFinalActivity.showNotification(ConfigFinalActivity.java:509)
08-07 21:30:24.510: E/AndroidRuntime(1998): at com.project.new.datasettings.ConfigFinalActivity.onClick(ConfigFinalActivity.java:620)
08-07 21:30:24.510: E/AndroidRuntime(1998): at android.view.View.performClick(View.java:4204)
08-07 21:30:24.510: E/AndroidRuntime(1998): at android.view.View$PerformClick.run(View.java:17355)
08-07 21:30:24.510: E/AndroidRuntime(1998): at android.os.Handler.handleCallback(Handler.java:725)
08-07 21:30:24.510: E/AndroidRuntime(1998): at android.os.Handler.dispatchMessage(Handler.java:92)
08-07 21:30:24.510: E/AndroidRuntime(1998): at android.os.Looper.loop(Looper.java:137)
08-07 21:30:24.510: E/AndroidRuntime(1998): at android.app.ActivityThread.main(ActivityThread.java:5041)
08-07 21:30:24.510: E/AndroidRuntime(1998): at java.lang.reflect.Method.invokeNative(Native Method)
08-07 21:30:24.510: E/AndroidRuntime(1998): at java.lang.reflect.Method.invoke(Method.java:511)
08-07 21:30:24.510: E/AndroidRuntime(1998): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
08-07 21:30:24.510: E/AndroidRuntime(1998): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
08-07 21:30:24.510: E/AndroidRuntime(1998): at dalvik.system.NativeStart.main(Native Method)
08-07 21:30:28.750: I/Process(1998): Sending signal. PID: 1998 SIG: 9
现在看来它是空的-有什么建议吗
不,它不是空的。它是一个空列表(大小=0)
旁注:有一个名为
nameArr
的变量和一个名为nameArr
的变量非常容易混淆。您必须更改nameArr=handler.getnameArr()
tonameArr.addAll(handler.getnameArr())
为了将所有结果添加到数组列表中如果nameArr的值为null,System.out.println会说“null”,而不是“[]”。所以你有一个空的列表
nameArr.addAll(handler.getnameArr());
这是您要添加到此名为“nameArr”的Arraylist中的位置
也许检查handler.getnameArr()
返回的内容可以为您提供线索。
请注意,它没有返回null,而是返回一个空集合。nameArr中是否添加了任何内容?我已经看过你的代码好几次了,在初始声明之外没有看到任何对该变量的引用,在setArrayList()中,请停止使用这么多全局变量。给你的东西命名一些有意义的东西。你不应该声明像NameArr,NameArr。。。等等。还要仔细思考为什么需要10个不同的全局阵列列表,有更好的解决方案吗?可能是一个类来封装数据?我尝试了你的解决方案(上面更新的源代码),但我仍然得到08-07 20:32:48.942:I/System.out(1371):[]在我的日志中你必须发布处理程序类的代码,那么数组中应该有什么?我在上面添加了它。。。可以在这里找到:你知道为什么它显示为空(或者我能做些什么来解决它?)它没有显示为“空”,而是显示为“[]”-空列表。通过查看代码-希望我看到的是正确的位置-你在UpdateActivity类中定义了大约3行变量名,并将其初始化为空ArrayList。我在你的类中没有发现任何改变ArrayList内容的代码,所以它是空的。大多数IDE都包含一个step调试器,它允许您监视变量或字段的值发生变化时要中断的变量或字段。您可以尝试这样做,并查看在初始化ArrayList之后是否有任何内容将任何字符串添加到该ArrayList中。Ok。谢谢你指出这一点!:)知道为什么它会显示为空白(或者我能做些什么来解决它?[再次]-它不会显示为“空白”,而是显示为“[]”-空列表。@DroidZilla:当然,
add()
在打印之前将一些项添加到列表中。知道为什么它会显示为空白(或者我能做些什么来解决它?)@DroidZilla:如果您检查您的方法“public ArrayList getnameArr(){System.out.println(“testing123”);return nameArr;}”,那么实际上返回的是您在顶部创建的相同的ArrayList,它是空的(这是它刚刚初始化,但不包含任何元素。如果执行nameArr.add(“testing123”),这将向此arraylist nameArr.public arraylist getnameArr(){System.out.println(“test”);System.out.println(nameArr);nameArr.add(“testing123”)添加字符串元素;return nameArr;似乎没有解决空指针问题-我仍然得到一个空指针@String value=Values.get(“name”).toString();@DroidZilla:检查什么是空的,对象“Values”是空的还是值。get(“name”)是空的?查看代码,我怀疑您不需要对这个值调用toString()。get(“name”)因为它返回了一个字符串。值显示为空-也是在我尝试使用string value=Values.get(“name”);eclipse抛出了一个“类型不匹配错误:无法从对象转换为字符串”
nameArr.addAll(handler.getnameArr());