안드로이드 Json질문입니다


Json 파서 중에 에러가 계속 떠서 이렇게 올립니다! 계속 null값이 떠서요 ㅠㅠ json가져오는 사이트는 구글 스프레드시트를 통해서 가져옵니다 https://script.google.com/macros/s/AKfycbxW2X5zPvG1ED7opyJ7_1zbHOvHQdVGn2rUmfDdabTA8rEkGf5o/exec json사이트구요..이미지는 피카소를 이용중입니다!

public class tools_main2 extends AppCompatActivity {

    private GridView mGridView;

    private tools_adapter2 mGridAdapter;
    private ArrayList<tools_item2> mGridData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gridbase);

        mGridView = (GridView) findViewById(R.id.gridView_base);

        //Initialize with empty data
        mGridData = new ArrayList<>();
        mGridAdapter = new tools_adapter2(this, R.layout.tools_grid_view, mGridData);
        mGridView.setAdapter(mGridAdapter);
        //Start download
        new AsyncHttpTask().execute("");
    }

    //Downloading data asynchronously
    public class AsyncHttpTask extends AsyncTask<String, Void, String> {
        HttpURLConnection urlConnection;
        StringBuilder result;

        @Override
        protected String doInBackground(String... params) {
            result = new StringBuilder();
            urlConnection = null;

            try {
                URL url = new URL("https://script.google.com/macros/s/AKfycbxW2X5zPvG1ED7opyJ7_1zbHOvHQdVGn2rUmfDdabTA8rEkGf5o/exec");
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.connect();
                InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                String line;
                String result = "";
                while ((line = reader.readLine()) != null) {
                    result += line;
                }
                parseResult(line);
                // Close stream
                if (null != in) {
                    in.close();
                }
                return result;

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                assert urlConnection != null;
                urlConnection.disconnect();
            }
            return result.toString();
        }


        @Override
        protected void onPostExecute(String result) {
            // Download complete. Lets update UI

            mGridAdapter.setGridData(mGridData);
        }


        String streamToString(InputStream stream) throws IOException {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
            String line;
            String result = "";
            while ((line = bufferedReader.readLine()) != null) {
                result += line;
            }

            // Close stream
            if (null != stream) {
                stream.close();
            }
            return result;
        }

        /**
         * Parsing the feed results and get the list
         *
         * @param result
         */
        private void parseResult(String result) {

            try {
                JSONObject response = new JSONObject(result);
                JSONArray posts = response.optJSONArray("posts");
                tools_item2 item;
                for (int i = 0; i < posts.length(); i++)
                {
                    String title = posts.optJSONObject(i).getString("title");
                    String image = posts.optJSONObject(i).getString("image");
                    item = new tools_item2();
                    item.setTitle(title);
                    item.setImage(image);
                    mGridData.add(item);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
          }
       }
    }

메인화면 소스구요

//public class tools_adapter2 extends ArrayAdapter<tools_item2> {

    //private final ColorMatrixColorFilter grayscaleFilter;
    private Context mContext;
    private int layoutResourceId;
    private ArrayList<tools_item2> mGridData = new ArrayList<tools_item2>();

    public tools_adapter2(Context mContext, int layoutResourceId, ArrayList<tools_item2> mGridData) {
        super(mContext, layoutResourceId, mGridData);
        this.layoutResourceId = layoutResourceId;
        this.mContext = mContext;
        this.mGridData = mGridData;
    }


    /**
     * Updates grid data and refresh grid items.
     *
     * @param mGridData
     */
    public void setGridData(ArrayList<tools_item2> mGridData) {
        this.mGridData = mGridData;
        notifyDataSetChanged();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View row = convertView;
        ViewHolder holder;

        if (row == null) {
            LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
            row = inflater.inflate(layoutResourceId, parent, false);
            holder = new ViewHolder();
            holder.titleTextView = (TextView) row.findViewById(R.id.tools_grid_textview);
            holder.imageView = (ImageView) row.findViewById(R.id.tools_grid_image);
            row.setTag(holder);
        } else {
            holder = (ViewHolder) row.getTag();
        }

        tools_item2 item = mGridData.get(position);
        holder.titleTextView.setText(mGridData.get(position).getTitle());
        Picasso.with(mContext).load(item.getImage()).into(holder.imageView);
        return row;
    }

    static class ViewHolder {
        TextView titleTextView;
        ImageView imageView;
    }
}

어댑터 소스입니다.

public class tools_item2 {
        private String image;
    private String title;

    public tools_item2() {
        super();
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }
}

아이템 소스입니다.

04-27 02:50:19.700 12218-12762/org.androidtown.ezcoffee W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
04-27 02:50:19.700 12218-12762/org.androidtown.ezcoffee W/System.err:     at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
04-27 02:50:19.700 12218-12762/org.androidtown.ezcoffee W/System.err:     at org.json.JSONTokener.nextValue(JSONTokener.java:94)
04-27 02:50:19.700 12218-12762/org.androidtown.ezcoffee W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:156)
04-27 02:50:19.700 12218-12762/org.androidtown.ezcoffee W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:173)
04-27 02:50:19.700 12218-12762/org.androidtown.ezcoffee W/System.err:     at org.androidtown.ezcoffee.tools.tools_main2$AsyncHttpTask.parseResult(tools_main2.java:118)
04-27 02:50:19.700 12218-12762/org.androidtown.ezcoffee W/System.err:     at org.androidtown.ezcoffee.tools.tools_main2$AsyncHttpTask.doInBackground(tools_main2.java:70)
04-27 02:50:19.701 12218-12762/org.androidtown.ezcoffee W/System.err:     at org.androidtown.ezcoffee.tools.tools_main2$AsyncHttpTask.doInBackground(tools_main2.java:50)
04-27 02:50:19.701 12218-12762/org.androidtown.ezcoffee W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:288)
04-27 02:50:19.701 12218-12762/org.androidtown.ezcoffee W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
04-27 02:50:19.701 12218-12762/org.androidtown.ezcoffee W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
04-27 02:50:19.701 12218-12762/org.androidtown.ezcoffee W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
04-27 02:50:19.701 12218-12762/org.androidtown.ezcoffee W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
04-27 02:50:19.701 12218-12762/org.androidtown.ezcoffee W/System.err:     at java.lang.Thread.run(Thread.java:818)

에러 로그 소스입니다 ㅠㅠㅠ 제발 해결좀 부탁 드려요 감사합니다...

  • 2016년 04월 27일에 작성됨
    취준생..ㅠ_ㅠ 안드로이드요

  • 코드가 너무 길어요...    정두식   2016.4.27 06:57     
  • JSONTokener.java:116 가 어디인가요?^^    염지현   2016.4.27 09:47     
  • 죄송합니다 ㅠㅠ 코드가 너무 길었죠 java 116 은 jsonObject 있는 부분입니다 ㅠㅠ     한정희   2016.4.27 15:59     
조회수 989


1 답변


좋아요
1
싫어요
채택취소하기

현재 https://script.google.com/macros/s/AKfycbxW2X5zPvG1ED7opyJ7_1zbHOvHQdVGn2rUmfDdabTA8rEkGf5o/exec 여기 사이트에서 Json을 받아온다고 하셨는데 Json 형태를 보니 "posts"키 값이 없습니다. JSONArray posts = response.optJSONArray("posts"); 를 지워보시고 아래와 같이 다시 해보세요.

private void parseResult(String result) {
    try {
           JSONArray response = new JSONArray(result);
            tools_item2 item;
            for (int i = 0; i < response.length(); i++) {
                String title = response.optJSONObject(i).getString("title");
                String image = response.optJSONObject(i).getString("image");
                item = new tools_item2();
                item.setTitle(title);
                item.setImage(image);
                mGridData.add(item);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
          }
       }
  • 2016년 04월 27일에 수정됨
    안드로이드, 루비온레일즈
  • 2016년 04월 27일에 작성됨
    안드로이드, 루비온레일즈

  • 감사합니다 !! 그대로 한번 해보겠습니다~~! ㅠㅠ 이렇게 답변 달아주셔서 감사해요    한정희   2016.4.27 15:07     

로그인이 필요한 기능입니다.

Hashcode는 개발자들을 위한 무료 QnA사이트 입니다. 작성한 답변에 다른 개발자들이 댓글을 작성하거나 좋아요/싫어요를 할 수 있기 때문에 계정을 필요로 합니다.
► 로그인
► 계정만들기
Close