java - 尝试解析 JSON 数据时通过递归调用在 Android 中获取 StackOverFlowError

标签 java android json

我正在尝试学习如何在 Android 中解析 JSON 数据。我在这里引用了一个教程:http://www.androidhive.info/2012/01/android-json-parsing-tutorial/

我得到的只是一个 StackOverFlowError ,我无法弄清楚其解决方案。对此的任何帮助将不胜感激。您可以在下面找到所有相关的 Java 代码。如果您还需要 XML 文件的代码,请随时告诉我。

ServiceHandler 类的代码:

    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.client.utils.URLEncodedUtils;
    import org.apache.http.impl.client.DefaultHttpClient;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * Created by  on 02-07-2015.
 */
public class ServiceHandler {
    static String response = null;
    public final static int GET = 1;
    public final static int POST = 2;

    public ServiceHandler() {
    }

    public String makeServiceCall(String url, int method) {
        return this.makeServiceCall(url, method);
    }

    public String makeServiceCall(String url, int method, List<NameValuePair> params) {

        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpEntity httpEntity = null;
            HttpResponse httpResponse = null;

            if (method == POST) {
                HttpPost httpPost = new HttpPost(url);
                if (params != null) {
                    httpPost.setEntity(new UrlEncodedFormEntity(params));
                }

                httpResponse = httpClient.execute(httpPost);

            } else if (method == GET) {
                if (params != null) {
                    String paramString = URLEncodedUtils.format(params, "utf-8");
                    url += "?" + paramString;
                }

                HttpGet httpGet = new HttpGet(url);
                httpResponse = httpClient.execute(httpGet);

            }
        } catch (UnsupportedEncodingException ue) {
            ue.printStackTrace();
        } catch (ClientProtocolException ce) {
            ce.printStackTrace();
        } catch (IOException io) {
            io.printStackTrace();
        }

        return response;
    }
}

JSONActivity Activity 代码:

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by  on 03-07-2015.
 */
public class JSONActivity extends ListActivity {

    private ProgressDialog pDialog;
    private static String url = "http://api.androidhive.info/contacts/";
    private static final String TAG_CONTACTS = "contacts";
    private static final String TAG_ID = "id";
    private static final String TAG_NAME = "name";
    private static final String TAG_EMAIL = "email";
    private static final String TAG_ADDRESS = "address";
    private static final String TAG_GENDER = "gender";
    private static final String TAG_PHONE = "phone";
    private static final String TAG_PHONE_MOBILE = "mobile";
    private static final String TAG_PHONE_HOME = "home";
    private static final String TAG_PHONE_OFFICE = "office";

    JSONArray contacts=null;
    ArrayList<HashMap<String, String>> contactList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.webservicestrial);
        contactList = new ArrayList<HashMap<String, String>>();
        ListView lv = getListView();
        new GetContacts().execute();
    }

    private class GetContacts extends AsyncTask<Void, Void, Void>{
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(JSONActivity.this);
            pDialog.setMessage("Fetching...");
            pDialog.setCancelable(false);
            pDialog.show();
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            if (pDialog.isShowing())
                pDialog.dismiss();
            ListAdapter adapter = new SimpleAdapter(
                    JSONActivity.this, contactList,
                    R.layout.list_item, new String[] { TAG_NAME, TAG_EMAIL,
                    TAG_PHONE_MOBILE }, new int[] { R.id.name,
                    R.id.email, R.id.mobile });

            setListAdapter(adapter);

        }

        @Override
        protected Void doInBackground(Void... params) {
            ServiceHandler sh = new ServiceHandler();
            String jsonStr = sh.makeServiceCall(url,ServiceHandler.GET);
            Log.d("Response:", ">"+jsonStr);
            if (jsonStr!=null) {
                try {
                    JSONObject jsonObject = new JSONObject(jsonStr);
                    contacts = jsonObject.getJSONArray(TAG_CONTACTS);
                    for (int i = 0; i < contacts.length(); i++) {
                        JSONObject c = contacts.getJSONObject(i);

                        String id = c.getString(TAG_ID);
                        String name = c.getString(TAG_NAME);
                        String email = c.getString(TAG_EMAIL);
                        String address = c.getString(TAG_ADDRESS);
                        String gender = c.getString(TAG_GENDER);

                        // Phone node is JSON Object
                        JSONObject phone = c.getJSONObject(TAG_PHONE);
                        String mobile = phone.getString(TAG_PHONE_MOBILE);
                        String home = phone.getString(TAG_PHONE_HOME);
                        String office = phone.getString(TAG_PHONE_OFFICE);

                        // tmp hashmap for single contact
                        HashMap<String, String> contact = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        contact.put(TAG_ID, id);
                        contact.put(TAG_NAME, name);
                        contact.put(TAG_EMAIL, email);
                        contact.put(TAG_PHONE_MOBILE, mobile);

                        // adding contact to contact list
                        contactList.add(contact);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }else {Log.e("ServiceHandler", "Couldn't get any data from the url");}

            return null;
        }
    }
}

最佳答案

public String makeServiceCall(String url, int method) {
    return this.makeServiceCall(url, method);
}

该方法正在调用自身,因此导致堆栈溢出。您可能想访问另一个 makeServiceCall方法。因此您必须添加List<NameValuePair>参数

关于java - 尝试解析 JSON 数据时通过递归调用在 Android 中获取 StackOverFlowError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31206312/

相关文章:

java - 维度 2 的自定义对象数组的初始化

java类加载器和运行时编译

android - 删除和添加 View NPE、蜂窝、android

android - Android:按下按钮以快速重置 Activity 会导致程序崩溃

json - 我们如何通过网络安全地将 API key 和 secret token 交付给用户?

c# - 为什么我通过 WCF Resful 服务在 "405 Method not allowed"操作上收到 "Put"错误?

java - 递归移动目录并在Java中合并它们的有效方法

java - 为什么 ArrayList 没有使用运行时输入进行初始化?

java - 通过 ACRA 报告我自己的异常(exception)情况

android无法解析json数据android