Android - Java 空指针异常
Android - Java null pointer exception
我正在尝试从在线数据库中获取数据,并将其显示为警报对话框生成器中的一个项目,
并且我已经在警报对话框中成功显示了我的数据,现在我想将所选项目的值存储到一个变量中并在警报对话框外的 TextView 上显示它(我当前的 activity)。 .
但是我猜我的代码有问题,每当我在警报对话框中按下 "OK" 按钮时,它总是收到 java.lang.nullpointerexception 错误
这是我的代码:
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bBrowseSelectGroup:
new AttemptViewMyGroup().execute();
Log.d("flag", "bottom of browse select Group");
break;
}
public void viewGroup() {
int success;
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Username", Username));
Log.d("Request!", "Starting");
JSONObject json = jsonParser.makeHttpRequest(url, "POST", params);
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Success", "Getting array");
mGroupList = new ArrayList<HashMap<String, String>>();
mGroups = json.getJSONArray(TAG_GROUPS);
try {
for (int i = 0; i < mGroups.length(); i++) {
JSONObject c = mGroups.getJSONObject(i);
String newGroupId = c.getString(TAG_GROUPID);
String newGroupName = c.getString(TAG_GROUPNAME);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_GROUPID, newGroupId);
map.put(TAG_GROUPNAME, newGroupName);
mGroupList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
class AttemptViewMyGroup extends AsyncTask<Void, Void, Boolean> {
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pd = new ProgressDialog(CreateAnnouncementActivity.this);
pd.setMessage("Loadng...");
pd.setIndeterminate(false);
pd.setCancelable(true);
pd.show();
}
@Override
protected Boolean doInBackground(Void... params) {
// TODO Auto-generated method stub
viewGroup();
return null;
}
@Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pd.dismiss();
alertDialogBuilder();
Log.d("flag", "end of post Execute");
}
}
public void alertDialogBuilder() {
// TODO Auto-generated method stub
Log.d("Flag", "arrive at alertdialogBuilder");
final String[] listGroupName = new String[mGroupList.size()];
final String[] listGroupId = new String[mGroupList.size()];
final Boolean[] itemsChecked = new Boolean[mGroupList.size()];
for (int i = 0; i < mGroupList.size(); i++) {
listGroupName[i] = mGroupList.get(i).get(TAG_GROUPNAME);
listGroupId[i] = mGroupList.get(i).get(TAG_GROUPID);
}
AlertDialog.Builder builder = new AlertDialog.Builder(
CreateAnnouncementActivity.this);
builder.setTitle("Choose Your Group : ");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
stringList.clear();
for (int i = 0; i < listGroupName.length; i++) {
if (itemsChecked[i]) {
groupList.add(listGroupName[i]);
stringList.add(listGroupId[i]);
itemsChecked[i] = false;
}
Log.d("flag", "after for");
}
String string = "";
for (int i = 0; i < groupList.size(); i++) {
string = string + " " + groupList.get(i);
}
PostTo.setText(string);
}
});
builder.setMultiChoiceItems(listGroupName, new boolean[] { false,
false, false },
new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
itemsChecked[which] = isChecked;
}
});
builder.show();
Log.d("flag", "bottom of alert dialog");
}
}
这里是 logcat:
01-11 12:56:33.291: D/TextLayoutCache(2034): Enable myanmar Zawgyi converter
01-11 12:56:33.291: D/TextLayoutCache(2034): Enable myanmar Zawgyi converter
01-11 12:56:33.291: D/TextLayoutCache(2034): Enable myanmar Zawgyi converter
01-11 12:56:33.291: D/TextLayoutCache(2034): Enable myanmar Zawgyi converter
01-11 12:56:34.306: D/flag(2034): bottom of browse select Group
01-11 12:56:34.306: D/Request!(2034): Starting
01-11 12:56:34.326: D/TextLayoutCache(2034): Enable myanmar Zawgyi converter
01-11 12:56:34.356: D/ProgressBar(2034): updateDrawableBounds: left = 0
01-11 12:56:34.356: D/ProgressBar(2034): updateDrawableBounds: top = 0
01-11 12:56:34.356: D/ProgressBar(2034): updateDrawableBounds: right = 96
01-11 12:56:34.356: D/ProgressBar(2034): updateDrawableBounds: bottom = 96
01-11 12:56:34.386: D/TextLayoutCache(2034): Enable myanmar Zawgyi converter
01-11 12:56:35.301: D/Success(2034): Getting array
01-11 12:56:35.321: D/Flag(2034): arrive at alertdialogBuilder
01-11 12:56:35.356: D/AbsListView(2034): Get MotionRecognitionManager
01-11 12:56:35.436: D/flag(2034): bottom of alert dialog
01-11 12:56:35.436: D/flag(2034): end of post Execute
01-11 12:56:35.446: D/TextLayoutCache(2034): Enable myanmar Zawgyi converter
01-11 12:56:35.456: D/TextLayoutCache(2034): Enable myanmar Zawgyi converter
01-11 12:56:35.461: D/TextLayoutCache(2034): Enable myanmar Zawgyi converter
01-11 12:56:35.461: D/TextLayoutCache(2034): Enable myanmar Zawgyi converter
01-11 12:56:35.466: D/TextLayoutCache(2034): Enable myanmar Zawgyi converter
01-11 12:56:35.576: E/ViewRootImpl(2034): sendUserActionEvent() mView == null
01-11 12:56:35.601: D/TextLayoutCache(2034): Enable myanmar Zawgyi converter
01-11 12:56:35.606: D/TextLayoutCache(2034): Enable myanmar Zawgyi converter
01-11 12:56:35.606: D/TextLayoutCache(2034): Enable myanmar Zawgyi converter
01-11 12:56:35.606: D/TextLayoutCache(2034): Enable myanmar Zawgyi converter
01-11 12:56:35.606: D/TextLayoutCache(2034): Enable myanmar Zawgyi converter
01-11 12:56:36.736: D/flag(2034): after for
01-11 12:56:36.741: D/flag(2034): after for
01-11 12:56:36.741: D/AndroidRuntime(2034): Shutting down VM
01-11 12:56:36.741: W/dalvikvm(2034): threadid=1: thread exiting with uncaught exception (group=0x41e2bc08)
01-11 12:56:36.741: E/AndroidRuntime(2034): FATAL EXCEPTION: main
01-11 12:56:36.741: E/AndroidRuntime(2034): Process: com.thesis.teamizer, PID: 2034
01-11 12:56:36.741: E/AndroidRuntime(2034): java.lang.NullPointerException
01-11 12:56:36.741: E/AndroidRuntime(2034): at com.thesis.teamizer.CreateAnnouncementActivity.onClick(CreateAnnouncementActivity.java:231)
01-11 12:56:36.741: E/AndroidRuntime(2034): at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:167)
01-11 12:56:36.741: E/AndroidRuntime(2034): at android.os.Handler.dispatchMessage(Handler.java:102)
01-11 12:56:36.741: E/AndroidRuntime(2034): at android.os.Looper.loop(Looper.java:146)
01-11 12:56:36.741: E/AndroidRuntime(2034): at android.app.ActivityThread.main(ActivityThread.java:5602)
01-11 12:56:36.741: E/AndroidRuntime(2034): at java.lang.reflect.Method.invokeNative(Native Method)
01-11 12:56:36.741: E/AndroidRuntime(2034): at java.lang.reflect.Method.invoke(Method.java:515)
01-11 12:56:36.741: E/AndroidRuntime(2034): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
01-11 12:56:36.741: E/AndroidRuntime(2034): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
01-11 12:56:36.741: E/AndroidRuntime(2034): at dalvik.system.NativeStart.main(Native Method)
这里是完整代码(以防万一):
package com.thesis.teamizer;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
public class CreateAnnouncementActivity extends Activity implements
View.OnClickListener {
userSessionManager session;
String Username, title, detail, time, expired, url, selectedGroup = "";
Button myButton, browseGroup, bExpired;
ProgressDialog pd;
DatePickerDialog dpd;
EditText announcementTitle, announcementDetail;
Intent intent;
Calendar c;
int flag = 0, mStartYear = 0, mStartMonth = 0, mStartDay = 0;
Database myDb;
TextView PostTo;
AlertDialog dialog;
public ArrayList<String> stringList = new ArrayList<String>();
public ArrayList<String> groupList = new ArrayList<String>();
JSONParser jsonParser;
public static final String TAG_SUCCESS = "success";
public static final String TAG_MESSAGE = "message";
public static final String TAG_GROUPS = "groups";
public static final String TAG_GROUPID = "groupId";
public static final String TAG_GROUPNAME = "groupName";
public static final String TAG_TOTALROW = "totalRow";
private JSONArray mGroups = null;
private ArrayList<HashMap<String, String>> mGroupList;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.create_announcement_screen);
sessionDeclaration();
variableDeclaration();
browseGroup.setOnClickListener(this);
// myButton.setOnClickListener(this);
bExpired.setOnClickListener(this);
}
private void variableDeclaration() {
// TODO Auto-generated method stub
intent = getIntent();
myButton = (Button) findViewById(R.id.bDoPostAnnouncement);
browseGroup = (Button) findViewById(R.id.bBrowseSelectGroup);
announcementTitle = (EditText) findViewById(R.id.et_AnnouncementTitle);
announcementDetail = (EditText) findViewById(R.id.et_AnnouncementDetail);
PostTo = (TextView) findViewById(R.id.tvSelectedGroupList);
bExpired = (Button) findViewById(R.id.bExpiredDate);
}
private void sessionDeclaration() {
// TODO Auto-generated method stub
session = new userSessionManager(getApplicationContext());
HashMap<String, String> user = session.getUserDetails();
Username = user.get(userSessionManager.KEY_USERNAME);
myIP ip = new myIP();
String publicIp = ip.getIp();
String thisPhp = "viewMyGroup.php";
url = publicIp + thisPhp;
jsonParser = new JSONParser();
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bBrowseSelectGroup:
new AttemptViewMyGroup().execute();
Log.d("flag", "bottom of browse select Group");
break;
case R.id.bDoPostAnnouncement:
break;
case R.id.bExpiredDate:
c = Calendar.getInstance();
mStartDay = c.get(Calendar.DAY_OF_MONTH);
mStartMonth = c.get(Calendar.MONTH);
mStartYear = c.get(Calendar.YEAR);
dpd = new DatePickerDialog(this,
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
// TODO Auto-generated method stub
bExpired.setText(year + "-" + (monthOfYear + 1)
+ "-" + dayOfMonth);
// ("yyyy-MM-dd HH:mm")
}
}, mStartYear, mStartMonth, mStartDay);
dpd.show();
break;
}
}
public void viewGroup() {
int success;
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Username", Username));
Log.d("Request!", "Starting");
JSONObject json = jsonParser.makeHttpRequest(url, "POST", params);
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Success", "Getting array");
mGroupList = new ArrayList<HashMap<String, String>>();
mGroups = json.getJSONArray(TAG_GROUPS);
try {
for (int i = 0; i < mGroups.length(); i++) {
JSONObject c = mGroups.getJSONObject(i);
String newGroupId = c.getString(TAG_GROUPID);
String newGroupName = c.getString(TAG_GROUPNAME);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_GROUPID, newGroupId);
map.put(TAG_GROUPNAME, newGroupName);
mGroupList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
class AttemptViewMyGroup extends AsyncTask<Void, Void, Boolean> {
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pd = new ProgressDialog(CreateAnnouncementActivity.this);
pd.setMessage("Loadng...");
pd.setIndeterminate(false);
pd.setCancelable(true);
pd.show();
}
@Override
protected Boolean doInBackground(Void... params) {
// TODO Auto-generated method stub
viewGroup();
return null;
}
@Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pd.dismiss();
alertDialogBuilder();
Log.d("flag", "end of post Execute");
}
}
public void alertDialogBuilder() {
// TODO Auto-generated method stub
Log.d("Flag", "arrive at alertdialogBuilder");
final String[] listGroupName = new String[mGroupList.size()];
final String[] listGroupId = new String[mGroupList.size()];
final Boolean[] itemsChecked = new Boolean[mGroupList.size()];
for (int i = 0; i < mGroupList.size(); i++) {
listGroupName[i] = mGroupList.get(i).get(TAG_GROUPNAME);
listGroupId[i] = mGroupList.get(i).get(TAG_GROUPID);
}
AlertDialog.Builder builder = new AlertDialog.Builder(
CreateAnnouncementActivity.this);
builder.setTitle("Choose Your Group : ");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
stringList.clear();
for (int i = 0; i < listGroupName.length; i++) {
if (itemsChecked[i]) {
groupList.add(listGroupName[i]);
stringList.add(listGroupId[i]);
itemsChecked[i] = false;
}
Log.d("flag", "after for");
}
String string = "";
for (int i = 0; i < groupList.size(); i++) {
string = string + " " + groupList.get(i);
}
PostTo.setText(string);
}
});
builder.setMultiChoiceItems(listGroupName, new boolean[] { false,
false, false },
new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
itemsChecked[which] = isChecked;
}
});
builder.show();
Log.d("flag", "bottom of alert dialog");
}
}
这个短得多的程序演示了同样的问题,没有那么多不相关的细节:
public class Main {
public static void main(String[] args) {
Boolean[] array = new Boolean[10];
if(array[0]) // <--- NullPointerException HERE
System.out.println("true");
else
System.out.println("false");
}
}
因为 array[0]
是一个 Boolean
引用(不是基本类型 boolean
),if(array[0])
调用自动拆箱(将 Boolean
转换为boolean
) 并被翻译成 if(array[0].booleanValue())
.
引用数组的元素自动初始化为空,所以array[0]
此时为空。
然后 array[0].booleanValue()
抛出 NullPointerException,因为您正在对空引用调用方法。
您可能打算创建一个 boolean
原始数组而不是 Boolean
引用数组。 boolean
数组的元素被初始化为 false
.
改变这个:
final Boolean[] itemsChecked = new Boolean[mGroupList.size()];
到
final boolean[] itemsChecked = new boolean[mGroupList.size()];
您的代码的问题在于您创建了一个布尔对象数组,最初为 nulls。如果你把它改成原始布尔值就可以了。你会得到一个布尔值数组,初始化为 false.
itemsChecked 变量的大小在这一行声明
final Boolean[] itemsChecked = new Boolean[mGroupList.size()];
如果listGroupName.length
大于mGroupList.size()
,则会产生异常。检查这两个值并进行相应修改。
先初始化您的 itemsChecked
数组,然后再使用它。
for(int i=0;i<itemsChecked.lenth;i++)
itemsChecked[i]=false;
条件匹配时使索引为真。
我正在尝试从在线数据库中获取数据,并将其显示为警报对话框生成器中的一个项目,
并且我已经在警报对话框中成功显示了我的数据,现在我想将所选项目的值存储到一个变量中并在警报对话框外的 TextView 上显示它(我当前的 activity)。 .
但是我猜我的代码有问题,每当我在警报对话框中按下 "OK" 按钮时,它总是收到 java.lang.nullpointerexception 错误
这是我的代码:
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bBrowseSelectGroup:
new AttemptViewMyGroup().execute();
Log.d("flag", "bottom of browse select Group");
break;
}
public void viewGroup() {
int success;
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Username", Username));
Log.d("Request!", "Starting");
JSONObject json = jsonParser.makeHttpRequest(url, "POST", params);
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Success", "Getting array");
mGroupList = new ArrayList<HashMap<String, String>>();
mGroups = json.getJSONArray(TAG_GROUPS);
try {
for (int i = 0; i < mGroups.length(); i++) {
JSONObject c = mGroups.getJSONObject(i);
String newGroupId = c.getString(TAG_GROUPID);
String newGroupName = c.getString(TAG_GROUPNAME);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_GROUPID, newGroupId);
map.put(TAG_GROUPNAME, newGroupName);
mGroupList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
class AttemptViewMyGroup extends AsyncTask<Void, Void, Boolean> {
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pd = new ProgressDialog(CreateAnnouncementActivity.this);
pd.setMessage("Loadng...");
pd.setIndeterminate(false);
pd.setCancelable(true);
pd.show();
}
@Override
protected Boolean doInBackground(Void... params) {
// TODO Auto-generated method stub
viewGroup();
return null;
}
@Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pd.dismiss();
alertDialogBuilder();
Log.d("flag", "end of post Execute");
}
}
public void alertDialogBuilder() {
// TODO Auto-generated method stub
Log.d("Flag", "arrive at alertdialogBuilder");
final String[] listGroupName = new String[mGroupList.size()];
final String[] listGroupId = new String[mGroupList.size()];
final Boolean[] itemsChecked = new Boolean[mGroupList.size()];
for (int i = 0; i < mGroupList.size(); i++) {
listGroupName[i] = mGroupList.get(i).get(TAG_GROUPNAME);
listGroupId[i] = mGroupList.get(i).get(TAG_GROUPID);
}
AlertDialog.Builder builder = new AlertDialog.Builder(
CreateAnnouncementActivity.this);
builder.setTitle("Choose Your Group : ");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
stringList.clear();
for (int i = 0; i < listGroupName.length; i++) {
if (itemsChecked[i]) {
groupList.add(listGroupName[i]);
stringList.add(listGroupId[i]);
itemsChecked[i] = false;
}
Log.d("flag", "after for");
}
String string = "";
for (int i = 0; i < groupList.size(); i++) {
string = string + " " + groupList.get(i);
}
PostTo.setText(string);
}
});
builder.setMultiChoiceItems(listGroupName, new boolean[] { false,
false, false },
new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
itemsChecked[which] = isChecked;
}
});
builder.show();
Log.d("flag", "bottom of alert dialog");
}
}
这里是 logcat:
01-11 12:56:33.291: D/TextLayoutCache(2034): Enable myanmar Zawgyi converter
01-11 12:56:33.291: D/TextLayoutCache(2034): Enable myanmar Zawgyi converter
01-11 12:56:33.291: D/TextLayoutCache(2034): Enable myanmar Zawgyi converter
01-11 12:56:33.291: D/TextLayoutCache(2034): Enable myanmar Zawgyi converter
01-11 12:56:34.306: D/flag(2034): bottom of browse select Group
01-11 12:56:34.306: D/Request!(2034): Starting
01-11 12:56:34.326: D/TextLayoutCache(2034): Enable myanmar Zawgyi converter
01-11 12:56:34.356: D/ProgressBar(2034): updateDrawableBounds: left = 0
01-11 12:56:34.356: D/ProgressBar(2034): updateDrawableBounds: top = 0
01-11 12:56:34.356: D/ProgressBar(2034): updateDrawableBounds: right = 96
01-11 12:56:34.356: D/ProgressBar(2034): updateDrawableBounds: bottom = 96
01-11 12:56:34.386: D/TextLayoutCache(2034): Enable myanmar Zawgyi converter
01-11 12:56:35.301: D/Success(2034): Getting array
01-11 12:56:35.321: D/Flag(2034): arrive at alertdialogBuilder
01-11 12:56:35.356: D/AbsListView(2034): Get MotionRecognitionManager
01-11 12:56:35.436: D/flag(2034): bottom of alert dialog
01-11 12:56:35.436: D/flag(2034): end of post Execute
01-11 12:56:35.446: D/TextLayoutCache(2034): Enable myanmar Zawgyi converter
01-11 12:56:35.456: D/TextLayoutCache(2034): Enable myanmar Zawgyi converter
01-11 12:56:35.461: D/TextLayoutCache(2034): Enable myanmar Zawgyi converter
01-11 12:56:35.461: D/TextLayoutCache(2034): Enable myanmar Zawgyi converter
01-11 12:56:35.466: D/TextLayoutCache(2034): Enable myanmar Zawgyi converter
01-11 12:56:35.576: E/ViewRootImpl(2034): sendUserActionEvent() mView == null
01-11 12:56:35.601: D/TextLayoutCache(2034): Enable myanmar Zawgyi converter
01-11 12:56:35.606: D/TextLayoutCache(2034): Enable myanmar Zawgyi converter
01-11 12:56:35.606: D/TextLayoutCache(2034): Enable myanmar Zawgyi converter
01-11 12:56:35.606: D/TextLayoutCache(2034): Enable myanmar Zawgyi converter
01-11 12:56:35.606: D/TextLayoutCache(2034): Enable myanmar Zawgyi converter
01-11 12:56:36.736: D/flag(2034): after for
01-11 12:56:36.741: D/flag(2034): after for
01-11 12:56:36.741: D/AndroidRuntime(2034): Shutting down VM
01-11 12:56:36.741: W/dalvikvm(2034): threadid=1: thread exiting with uncaught exception (group=0x41e2bc08)
01-11 12:56:36.741: E/AndroidRuntime(2034): FATAL EXCEPTION: main
01-11 12:56:36.741: E/AndroidRuntime(2034): Process: com.thesis.teamizer, PID: 2034
01-11 12:56:36.741: E/AndroidRuntime(2034): java.lang.NullPointerException
01-11 12:56:36.741: E/AndroidRuntime(2034): at com.thesis.teamizer.CreateAnnouncementActivity.onClick(CreateAnnouncementActivity.java:231)
01-11 12:56:36.741: E/AndroidRuntime(2034): at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:167)
01-11 12:56:36.741: E/AndroidRuntime(2034): at android.os.Handler.dispatchMessage(Handler.java:102)
01-11 12:56:36.741: E/AndroidRuntime(2034): at android.os.Looper.loop(Looper.java:146)
01-11 12:56:36.741: E/AndroidRuntime(2034): at android.app.ActivityThread.main(ActivityThread.java:5602)
01-11 12:56:36.741: E/AndroidRuntime(2034): at java.lang.reflect.Method.invokeNative(Native Method)
01-11 12:56:36.741: E/AndroidRuntime(2034): at java.lang.reflect.Method.invoke(Method.java:515)
01-11 12:56:36.741: E/AndroidRuntime(2034): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
01-11 12:56:36.741: E/AndroidRuntime(2034): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
01-11 12:56:36.741: E/AndroidRuntime(2034): at dalvik.system.NativeStart.main(Native Method)
这里是完整代码(以防万一):
package com.thesis.teamizer;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
public class CreateAnnouncementActivity extends Activity implements
View.OnClickListener {
userSessionManager session;
String Username, title, detail, time, expired, url, selectedGroup = "";
Button myButton, browseGroup, bExpired;
ProgressDialog pd;
DatePickerDialog dpd;
EditText announcementTitle, announcementDetail;
Intent intent;
Calendar c;
int flag = 0, mStartYear = 0, mStartMonth = 0, mStartDay = 0;
Database myDb;
TextView PostTo;
AlertDialog dialog;
public ArrayList<String> stringList = new ArrayList<String>();
public ArrayList<String> groupList = new ArrayList<String>();
JSONParser jsonParser;
public static final String TAG_SUCCESS = "success";
public static final String TAG_MESSAGE = "message";
public static final String TAG_GROUPS = "groups";
public static final String TAG_GROUPID = "groupId";
public static final String TAG_GROUPNAME = "groupName";
public static final String TAG_TOTALROW = "totalRow";
private JSONArray mGroups = null;
private ArrayList<HashMap<String, String>> mGroupList;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.create_announcement_screen);
sessionDeclaration();
variableDeclaration();
browseGroup.setOnClickListener(this);
// myButton.setOnClickListener(this);
bExpired.setOnClickListener(this);
}
private void variableDeclaration() {
// TODO Auto-generated method stub
intent = getIntent();
myButton = (Button) findViewById(R.id.bDoPostAnnouncement);
browseGroup = (Button) findViewById(R.id.bBrowseSelectGroup);
announcementTitle = (EditText) findViewById(R.id.et_AnnouncementTitle);
announcementDetail = (EditText) findViewById(R.id.et_AnnouncementDetail);
PostTo = (TextView) findViewById(R.id.tvSelectedGroupList);
bExpired = (Button) findViewById(R.id.bExpiredDate);
}
private void sessionDeclaration() {
// TODO Auto-generated method stub
session = new userSessionManager(getApplicationContext());
HashMap<String, String> user = session.getUserDetails();
Username = user.get(userSessionManager.KEY_USERNAME);
myIP ip = new myIP();
String publicIp = ip.getIp();
String thisPhp = "viewMyGroup.php";
url = publicIp + thisPhp;
jsonParser = new JSONParser();
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bBrowseSelectGroup:
new AttemptViewMyGroup().execute();
Log.d("flag", "bottom of browse select Group");
break;
case R.id.bDoPostAnnouncement:
break;
case R.id.bExpiredDate:
c = Calendar.getInstance();
mStartDay = c.get(Calendar.DAY_OF_MONTH);
mStartMonth = c.get(Calendar.MONTH);
mStartYear = c.get(Calendar.YEAR);
dpd = new DatePickerDialog(this,
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
// TODO Auto-generated method stub
bExpired.setText(year + "-" + (monthOfYear + 1)
+ "-" + dayOfMonth);
// ("yyyy-MM-dd HH:mm")
}
}, mStartYear, mStartMonth, mStartDay);
dpd.show();
break;
}
}
public void viewGroup() {
int success;
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Username", Username));
Log.d("Request!", "Starting");
JSONObject json = jsonParser.makeHttpRequest(url, "POST", params);
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Success", "Getting array");
mGroupList = new ArrayList<HashMap<String, String>>();
mGroups = json.getJSONArray(TAG_GROUPS);
try {
for (int i = 0; i < mGroups.length(); i++) {
JSONObject c = mGroups.getJSONObject(i);
String newGroupId = c.getString(TAG_GROUPID);
String newGroupName = c.getString(TAG_GROUPNAME);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_GROUPID, newGroupId);
map.put(TAG_GROUPNAME, newGroupName);
mGroupList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
class AttemptViewMyGroup extends AsyncTask<Void, Void, Boolean> {
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pd = new ProgressDialog(CreateAnnouncementActivity.this);
pd.setMessage("Loadng...");
pd.setIndeterminate(false);
pd.setCancelable(true);
pd.show();
}
@Override
protected Boolean doInBackground(Void... params) {
// TODO Auto-generated method stub
viewGroup();
return null;
}
@Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pd.dismiss();
alertDialogBuilder();
Log.d("flag", "end of post Execute");
}
}
public void alertDialogBuilder() {
// TODO Auto-generated method stub
Log.d("Flag", "arrive at alertdialogBuilder");
final String[] listGroupName = new String[mGroupList.size()];
final String[] listGroupId = new String[mGroupList.size()];
final Boolean[] itemsChecked = new Boolean[mGroupList.size()];
for (int i = 0; i < mGroupList.size(); i++) {
listGroupName[i] = mGroupList.get(i).get(TAG_GROUPNAME);
listGroupId[i] = mGroupList.get(i).get(TAG_GROUPID);
}
AlertDialog.Builder builder = new AlertDialog.Builder(
CreateAnnouncementActivity.this);
builder.setTitle("Choose Your Group : ");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
stringList.clear();
for (int i = 0; i < listGroupName.length; i++) {
if (itemsChecked[i]) {
groupList.add(listGroupName[i]);
stringList.add(listGroupId[i]);
itemsChecked[i] = false;
}
Log.d("flag", "after for");
}
String string = "";
for (int i = 0; i < groupList.size(); i++) {
string = string + " " + groupList.get(i);
}
PostTo.setText(string);
}
});
builder.setMultiChoiceItems(listGroupName, new boolean[] { false,
false, false },
new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
itemsChecked[which] = isChecked;
}
});
builder.show();
Log.d("flag", "bottom of alert dialog");
}
}
这个短得多的程序演示了同样的问题,没有那么多不相关的细节:
public class Main {
public static void main(String[] args) {
Boolean[] array = new Boolean[10];
if(array[0]) // <--- NullPointerException HERE
System.out.println("true");
else
System.out.println("false");
}
}
因为 array[0]
是一个 Boolean
引用(不是基本类型 boolean
),if(array[0])
调用自动拆箱(将 Boolean
转换为boolean
) 并被翻译成 if(array[0].booleanValue())
.
引用数组的元素自动初始化为空,所以array[0]
此时为空。
然后 array[0].booleanValue()
抛出 NullPointerException,因为您正在对空引用调用方法。
您可能打算创建一个 boolean
原始数组而不是 Boolean
引用数组。 boolean
数组的元素被初始化为 false
.
改变这个:
final Boolean[] itemsChecked = new Boolean[mGroupList.size()];
到
final boolean[] itemsChecked = new boolean[mGroupList.size()];
您的代码的问题在于您创建了一个布尔对象数组,最初为 nulls。如果你把它改成原始布尔值就可以了。你会得到一个布尔值数组,初始化为 false.
itemsChecked 变量的大小在这一行声明
final Boolean[] itemsChecked = new Boolean[mGroupList.size()];
如果listGroupName.length
大于mGroupList.size()
,则会产生异常。检查这两个值并进行相应修改。
先初始化您的 itemsChecked
数组,然后再使用它。
for(int i=0;i<itemsChecked.lenth;i++)
itemsChecked[i]=false;
条件匹配时使索引为真。