2015-01-11 6 views
0

내가 온라인 데이터베이스에서 데이터를 얻기 위해 노력하고 경고 대화 상자 빌더의 항목으로 표시하고 있습니다 ,,안드로이드 - 자바 널 포인터 예외

그리고 성공적으로 경고 대화 상자에서 내 데이터를 보였으며, 지금은 한 선택한 항목의 값을 변수에 저장하고 alertdialog (현재 활동) 외부의 TextView에 표시하려고합니다.

내 코드에 문제가있는 것 같아서 계속 java 오류가 발생합니다. 알림 대화 상자에서 "OK"버튼을 누를 때마다 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"); 
} 

} 

그리고 6,는 로그 캣입니다 :

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"); 
} 

} 
+1

그리고 어떤 줄이'CreateAnnouncementActivity.java : 231'입니까? – immibis

+0

@immibis 해당 코드 : if (itemsChecked [i]) { – redRabbit

+0

mview r이 초기화되지 않았습니까? –

답변

2

이 훨씬 짧은 프로그램이 같은 문제를 보여, 많은 관련이없이 세부 정보 :

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])Booleanboolean으로 변환하기 위해 자동 언 박싱을 호출하고 if(array[0].booleanValue())으로 변환됩니다.

참조 배열의 요소는 자동으로 null로 초기화되므로이 시점에서 array[0]은 null입니다.

그런 다음 array[0].booleanValue()은 널 참조에서 메소드를 호출 할 때 NullPointerException을 발생시킵니다.

Boolean 참조 배열 대신 boolean 프리미티브 배열을 만들었을 수도 있습니다. boolean 배열 요소는 false으로 초기화됩니다.

+0

예, 그렇습니다! 나는 부울을 부울로 착각했다. 나의 신 !! 고마워요 – redRabbit

0

변경이 :

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

코드의 문제

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

에 당신이 널 (null) 처음됩니다 부울 객체의 배열을 만들 것입니다. 기본 부울로 변경하면 괜찮을 것입니다. false으로 초기화 된 불리언 배열을 가져옵니다. listGroupName.lengthmGroupList.size() 이상, 예외를 생성 할 경우 itemsChecked 변수의

+0

쿨! 예 부울과 부울이 다릅니다. 하나는 객체이고 다른 하나는 원시 객체입니다. – ZakiMak

+0

하지만 객체 배열이 객체 배열 인덱스를 초기화 할 수 있다면 원시 배열을 만들 필요가 없습니다 –

+0

예, 부울 배열이 정확히 필요한 경우 그는 for 루프를 사용하여 초기화 할 수 있습니다. 그렇지 않으면 그는 부울 프리미티브의 배열을 사용하고 시작 부분에서 초기화를 건너 뛸 수 있습니다. 둘 다 작동해야합니다. – ZakiMak

0

크기는이 라인

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

에 선언되어있다. 두 값을 모두 확인하고 그에 맞게 수정하십시오.

0

itemsChecked 배열을 먼저 초기화 한 다음 사용하십시오.

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

조건이 일치하면 색인을 만듭니다.