I'm trying to get data from online database, and show it as an item in Alert Dialog Builder,,
And I've successfully showed my data in alert dialog, and now I want to stored the value of selected items to a variable and shows it on the TextView outside the alertdialog (my current activity)..
But guess there is something wrong with my code, it keeps getting an error of java.lang.nullpointerexception whenever I press the "OK" button inside the alert dialog
This is my code :
@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");
}
}
And here is the 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)
And here is the full code (in case) :
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");
}
}
This much shorter program demonstrates the same problem, without as many irrelevant details:
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");
}
}
Because array[0]
is a Boolean
reference (not the primitive type boolean
), if(array[0])
invokes auto-unboxing (to convert the Boolean
to a boolean
) and is translated to if(array[0].booleanValue())
.
Elements of reference arrays are initialized to null automatically, so array[0]
is null at this point.
Then array[0].booleanValue()
throws a NullPointerException, as you are invoking a method on a null reference.
You might have meant to create a boolean
primitive array instead of a Boolean
reference array. Elements of a boolean
array are initialized to false
.
Change this:
final Boolean[] itemsChecked = new Boolean[mGroupList.size()];
to
final boolean[] itemsChecked = new boolean[mGroupList.size()];
The problem with your code is that you make an array of Boolean objects, which will be nulls initially. If you change it to primitive boolean it will be okay. You will get an array of booleans initialized to false .
Size of itemsChecked variable is declared in this line
final Boolean[] itemsChecked = new Boolean[mGroupList.size()];
If listGroupName.length
is greater than mGroupList.size()
, it will create an exception. Check both the values and modify accordingly.
Initialize your itemsChecked
array first then use it.
for(int i=0;i<itemsChecked.lenth;i++)
itemsChecked[i]=false;
Make index true when your condition matches.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.