2

Androidアプリでサーバーからjsonデータを消費しようとしています。CakePHP Web アプリからのデータの形式は次のようになります。

[{"Chapter":{"id":"1","chapter":"4","chaptertitle":"権利章典"}}]

以下は、私の目標を達成するために使用しているJavaコードです。

    public class Sheria extends SherlockListFragment {

    // Progress Dialog
//  private ProgressDialog pDialog;
//  private View view;

    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();

    ArrayList<HashMap<String, String>> chapterList;

    // url to get all products list
    // private static String url_all_products =
    // "http://10.0.2.2/android_projects/sanisani/today_getall.php";
    private static String url_chapters = "http://10.0.2.2/constitution/laws/chapters";
    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_CHAPTERS = "Chapter";
    private static final String TAG_CHAP = "chapter";
    private static final String TAG_CHAP_TITLE = "chaptertitle";

    JSONArray chaps = null;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.sheria, container, false);
        new FetchDetails().execute();

        return super.onCreateView(inflater, container, savedInstanceState);
    }

    class FetchDetails extends AsyncTask<String, String, String> {

        private ProgressDialog pDialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(getSherlockActivity());
            pDialog.setMessage("Fetching Data...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
//          pDialog.show();
        }

        @Override
        protected String doInBackground(String... arg0) {
            // TODO Auto-generated method stub
            chapterList = new ArrayList<HashMap<String, String>>();

            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // getting JSON string from URL
            JSONObject json = jParser.getJSONFromUrl(url_chapters);

            // Check your log cat for JSON reponse
            Log.d("Chapters: ", json.toString());
            try {
                // Checking for SUCCESS TAG
//              int success = json.getInt(TAG_SUCCESS);
//              if (success == 1) {
                    // products found
                    // Getting Array of Products
                    chaps = json.getJSONArray(TAG_CHAPTERS);
                    System.out.println(chaps);

                    // looping through All Products
                    for (int i = 0; i < chaps.length(); i++) {
                        JSONObject c = chaps.getJSONObject(i);

                        // Storing each json item in variable
                        String chapter = c.getString(TAG_CHAP);
                        String chapter_title = c.getString(TAG_CHAP_TITLE);



                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        map.put(TAG_CHAP, chapter);
                        map.put(TAG_CHAP_TITLE, chapter_title);

                        // adding HashList to ArrayList
                        chapterList.add(map);
                        // getSherlockActivity().finish();
                    }

//              }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once product deleted
            pDialog.dismiss();

            // Keys used in Hashmap
            String[] from = { TAG_CHAP, TAG_CHAP_TITLE };

            // Ids of views in listview_layout
            int[] to = { R.id.chapter, R.id.chaptertitle };

            // Instantiating an adapter to store each items
            // R.layout.listview_layout defines the layout of each item
            SimpleAdapter adapter = new SimpleAdapter(getActivity()
                    .getBaseContext(), chapterList, R.layout.sheriainfo, from,
                    to);

            // Setting the adapter to the listView
            setListAdapter(adapter);

        }

    }

}

コードを実行すると、JSONArray を JSONObject に変換できないというエラーが表示されます。

助けてください

4

1 に答える 1

1

を取得しているJSONArrayので、JSONObjectこれを試してください:

JSONArray json = jParser.getJSONFromUrl(url_chapters);

そしてreturn JSONArrayからgetJSONFromUrl(String)

また、配列ではないため削除chaps = json.getJSONArray(TAG_CHAPTERS);します。TAG_CHAPTER

そしてforループで

JSONObject c = json.getJSONObject(i);

代わりに

JSONObject c = chaps.getJSONObject(i);

編集

public class Sheria extends SherlockListFragment {

// Progress Dialog
// private ProgressDialog pDialog;
// private View view;

// Creating JSON Parser object
JSONParser jParser = new JSONParser();

ArrayList<HashMap<String, String>> chapterList;

// url to get all products list
// private static String url_all_products =
// "http://10.0.2.2/android_projects/sanisani/today_getall.php";
private static String url_chapters = "http://10.0.2.2/constitution/laws/chapters";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_CHAPTERS = "Chapter";
private static final String TAG_CHAP = "chapter";
private static final String TAG_CHAP_TITLE = "chaptertitle";

JSONArray chaps = null;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.sheria, container, false);
    new FetchDetails().execute();

    return super.onCreateView(inflater, container, savedInstanceState);
}

class FetchDetails extends AsyncTask<String, String, String> {

    private ProgressDialog pDialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(getSherlockActivity());
        pDialog.setMessage("Fetching Data...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        // pDialog.show();
    }

    @Override
    protected String doInBackground(String... arg0) {
        // TODO Auto-generated method stub
        chapterList = new ArrayList<HashMap<String, String>>();

        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // getting JSON string from URL

/* メソッド内で、サーバーから取得した u を notにgetJSONFromUrl()変換します */StringJSONArrayJSONObject

        JSONArray json = jParser.getJSONFromUrl(url_chapters);

        // Check your log cat for JSON reponse
        Log.d("Chapters: ", json.toString());
        try {
            // Checking for SUCCESS TAG
            // int success = json.getInt(TAG_SUCCESS);
            // if (success == 1) {
            // products found
            // Getting Array of Products
            // chaps = json.getJSONArray(TAG_CHAPTERS);
            // System.out.println(chaps);

            // looping through All Products
            for (int i = 0; i < json.length(); i++) {
                JSONObject c = json.getJSONObject(i);
                JSONObject jObj = c.getJSONObject("TAG_CHAPTERS ");

                // Storing each json item in variable
                String chapter = jObj.getString(TAG_CHAP);
                String chapter_title = jObj.getString(TAG_CHAP_TITLE);

                // creating new HashMap
                HashMap<String, String> map = new HashMap<String, String>();

                // adding each child node to HashMap key => value
                map.put(TAG_CHAP, chapter);
                map.put(TAG_CHAP_TITLE, chapter_title);

                // adding HashList to ArrayList
                chapterList.add(map);
                // getSherlockActivity().finish();
            }

            // }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog once product deleted
        pDialog.dismiss();

        // Keys used in Hashmap
        String[] from = { TAG_CHAP, TAG_CHAP_TITLE };

        // Ids of views in listview_layout
        int[] to = { R.id.chapter, R.id.chaptertitle };

        // Instantiating an adapter to store each items
        // R.layout.listview_layout defines the layout of each item
        SimpleAdapter adapter = new SimpleAdapter(getActivity()
                .getBaseContext(), chapterList, R.layout.sheriainfo, from,
                to);

        // Setting the adapter to the listView
        setListAdapter(adapter);

    }

}

}
于 2013-05-09T06:03:41.073 に答える