마스터Q&A 안드로이드는 안드로이드 개발자들의 질문과 답변을 위한 지식 커뮤니티 사이트입니다. 안드로이드펍에서 운영하고 있습니다. [사용법, 운영진]

안드로이드 java.lang.NullPointerException 도와주세요!

0 추천

전에 만든 엑티비티에서는 돌아가는데 메소드에서는 또 json형식 파싱이 잘됩니다. 근데 onCreate에서는

전역으로 선언한 객체가 null값이라니.. 이해가 너무 안되서 질문드려요 ㅠㅠㅠ 도와주세요!

onCreate 부분에서 

test1.setText(detailInformation[0].getChkbabycarriage());

이부분이 detailnformation 값을 아래메소드에서 받았고 전역으로 선언했는데 nullpointer가 나오니.. ㅠㅠ

부탁드려요!!!

 

public class MainActivity extends Activity {
// ListActivity를 상속받습니다.
    private String myJSON;
    final DetailInformation[] detailInformation = new DetailInformation[3];                                // 새로 파싱해서 받아오는 컨텐츠 정보들
    private DetailInformation test;                                // 새로 파싱해서 받아오는 컨텐츠 정보들
    private ArrayList<DetailInformation> SendInformation = new ArrayList<DetailInformation>();
    TextView test1,test2,test3,test4,test5;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        test1 = (TextView)findViewById(R.id.t);
        test2 = (TextView)findViewById(R.id.ts);
        test3 = (TextView)findViewById(R.id.testt);

        LoadData();                         //웹에서 데이터 받아오기






        //Intent t = new Intent(getApplicationContext(),test.class);
        //t.putParcelableArrayListExtra("t",SendInformation);
        //startActivity(t);


//        test3 = (TextView)findViewById(R.id.test3);
//        test4 = (TextView)findViewById(R.id.test4);
//        test5 = (TextView)findViewById(R.id.test5);

        test1.setText(detailInformation[0].getChkbabycarriage());
    }
    public void LoadData()                                                                              // 웹으로 부터 데이터 받음
    {
//        MapPoint.GeoCoordinate geo = mapView.getMapCenterPoint().getMapPointGeoCoord();                          //나의 위도경도 받아오는 객체
//        latitude = geo.latitude;
//        longitude = geo.longitude;
//        String URL = "생략";       //현재 나의 위치에서의 데이터 값 받아오기
//        String testUrl = "url 생략";
        getData("url 생략");

        // InserM();


    }

    public void getData(String url) {
        class GetDataJSON extends AsyncTask<String, Void, String> {

            @Override
            protected String doInBackground(String... params) {

                String uri = params[0];

                BufferedReader bufferedReader = null;
                try {
                    URL url = new URL(uri);
                    HttpURLConnection con = (HttpURLConnection) url.openConnection();
                    StringBuilder sb = new StringBuilder();

                    bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));

                    String json;
                    while ((json = bufferedReader.readLine()) != null) {
                        sb.append(json + "\n");
                    }

                    return sb.toString().trim();

                } catch (Exception e) {
                    return null;
                }

            }

            @Override
            protected void onPostExecute(String result) {
                myJSON = result;
               // Toast.makeText(getApplicationContext(), myJSON, Toast.LENGTH_SHORT).show();
                showList();
            }
        }
        GetDataJSON g = new GetDataJSON();
        g.execute(url);
    }

    protected void showList() {
        //TextView wpqkf = (TextView) findViewById(R.id.serverRequest);
        //wpqkf.setText(myJSON.toString());

        ArrayList<String> array = new ArrayList<String>();
        try {
            JSONObject jsonRootObject = new JSONObject(myJSON);
            JSONArray jsonArray = jsonRootObject.optJSONArray("data");
            for (int i = 0; i < jsonArray.length(); i++) {
                array.clear();
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String chkbabycarriage = jsonObject.optString("chkbabycarriage").toString();
                String chkcreditcard = jsonObject.optString("chkcreditcard").toString();
                String chkpet = jsonObject.optString("chkpet").toString();
                String heritage = jsonObject.optString("heritage").toString();
                String infocenter = jsonObject.optString("infocenter").toString();
                String content_id = jsonObject.optString("content_id").toString();
                String content_type = jsonObject.optString("content_type".toString());
                String tel = jsonObject.optString("tel".toString());
                String like = jsonObject.optString("like".toString());
                String homepage = jsonObject.optString("homepage".toString());
                String overview = jsonObject.optString("overview".toString());
                // 객체 생성하고 할당하는거
                detailInformation[i] = new DetailInformation(chkbabycarriage, chkcreditcard, chkpet, heritage, infocenter, content_id, content_type, tel, like, homepage, overview);
                SendInformation.add(detailInformation[i]);
                test1.setText(SendInformation.get(0).getChkbabycarriage());
                test2.setText(detailInformation[i].getChkbabycarriage());


            }

            //  mapView.setCalloutBalloonAdapter(new CustomCalloutBalloonAdapter());
            // wpqkf.setText(LocalInformation[0].getTitle() + LocalInformation[0].getLatitude() + LocalInformation[0].getLongitude() + LocalInformation[0].getContent_type() + " distance : " + LocalInformation[0].getDistance());
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


}
안드로이드 NullPointerException 님이 2016년 11월 2일 질문
2016년 11월 2일 수정

1개의 답변

0 추천
asynctask 는 말 그대로 비동기적실행입니다.

loaddata부분을 oncreate에 넣으시고 new getData(url).excute().get()로 변경하셔서

동기적 실행을 하시던지

oncreate 안에 있는 test1.setText부분을 주석처리 하셔야 합니다
익명사용자 님이 2016년 11월 2일 답변
...