简体   繁体   English

Android-Java空指针异常

[英]Android - Java null pointer exception

I'm trying to get data from online database, and show it as an item in Alert Dialog Builder,, 我正在尝试从在线数据库中获取数据,并将其作为项目显示在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).. 而且我已经成功地在警报对话框中显示了数据,现在我想将所选项目的值存储到变量中,并将其显示在Alertdialog(我当前的活动)之外的TextView上。

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 但是,我的代码有问题,每当我按下警报对话框中的“确定”按钮时,它就会不断出现java.lang.nullpointerexception错误。

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 : 这是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()) . 因为array[0]是一个Boolean引用(不是原始类型boolean ),所以if(array[0])调用自动拆箱(将Boolean转换为boolean ),并转换为if(array[0].booleanValue())

Elements of reference arrays are initialized to null automatically, so array[0] is null at this point. 引用数组的元素会自动初始化为null,因此此时array[0]为null。

Then array[0].booleanValue() throws a NullPointerException, as you are invoking a method on a null reference. 然后,当您在null引用上调用方法时, array[0].booleanValue()会引发NullPointerException。

You might have meant to create a boolean primitive array instead of a Boolean reference array. 您可能曾经打算创建一个boolean基本数组而不是一个Boolean引用数组。 Elements of a boolean array are initialized to false . boolean数组的元素初始化为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. 代码的问题是,您创建了一个布尔对象数组,该对象最初将为null If you change it to primitive boolean it will be okay. 如果将其更改为原始布尔值,则可以。 You will get an array of booleans initialized to false . 您将获得一个初始化为false的布尔数组。

Size of itemsChecked variable is declared in this line itemsChecked变量的大小在此行中声明

final Boolean[] itemsChecked = new Boolean[mGroupList.size()];

If listGroupName.length is greater than mGroupList.size() , it will create an exception. 如果listGroupName.length大于mGroupList.size() ,它将创建一个异常。 Check both the values and modify accordingly. 检查两个值并进行相应修改。

Initialize your itemsChecked array first then use it. 首先初始化您的itemsChecked数组,然后使用它。

for(int i=0;i<itemsChecked.lenth;i++)   
itemsChecked[i]=false;

Make index true when your condition matches. 当条件匹配时使索引为真。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM