[英]Android - Java null pointer exception
我正在嘗試從在線數據庫中獲取數據,並將其作為項目顯示在Alert Dialog Builder中,
而且我已經成功地在警報對話框中顯示了數據,現在我想將所選項目的值存儲到變量中,並將其顯示在Alertdialog(我當前的活動)之外的TextView上。
但是,我的代碼有問題,每當我按下警報對話框中的“確定”按鈕時,它就會不斷出現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$2.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())
。
引用數組的元素會自動初始化為null,因此此時array[0]
為null。
然后,當您在null引用上調用方法時, array[0].booleanValue()
會引發NullPointerException。
您可能曾經打算創建一個boolean
基本數組而不是一個Boolean
引用數組。 boolean
數組的元素初始化為false
。
更改此:
final Boolean[] itemsChecked = new Boolean[mGroupList.size()];
至
final boolean[] itemsChecked = new boolean[mGroupList.size()];
代碼的問題是,您創建了一個布爾對象數組,該對象最初將為null 。 如果將其更改為原始布爾值,則可以。 您將獲得一個初始化為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;
當條件匹配時使索引為真。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.