当前位置: 首页 > 知识库问答 >
问题:

我想从 json api 中获取 jsonarray 并将其显示在 android 的列表视图中

阙新觉
2023-03-14

这是我的代码,我们在MainActivity中使用。我在主活动中使用以下代码,但它显示空指针异常。

public class MainActivity extends ListActivity {

    // URL to get contacts JSON
    private static String url = "https://swastianalytics.herokuapp.com/api/v1/fw_f/?access_token=2xbvwsIlD5gQgoSsqqb3wKiW0soLrqUSVoBBOzcxED9A1D9WFP5M6HGBQlX5aroV";

    // JSON Node names
    private static final String TABLE_INFO = "fw_f";
    private static final String TAG_FIELDWORKER_ID = "fieldworkerid";
    private static final String TAG_FW_NAME = "fw_name";
    private static final String TAG_FACILITY_ID = "facility_id";
    private static final String TAG_FACILITY_NAME = "facility_name";
    private static final String TAG_FS_MENTOR_ID = "fs_mentor_id";
    private static final String TAG_FS_MENTOR_NAME = "fs_mentor_name";
    private static final String TAG_STATE_ID = "state_id";
    private static final String TAG_STATE_NAME = "state_name";
    private static final String TAG_REGION_ID = "region_id";
    private static final String TAG_REGION_NAME = "region_name";
    private static final String TAG_NATIONAL_ID = "national_id";
    private static final String TAG_NATIONAL_NAME = "national_name";
    private static final String TAG_TOTAL_MEMBERS = "total_members";
    private static final String TAG_POSITIVE_MEMBERS = "positive_members";
    private static final String TAG_ELIGIBLE_FOR_ART = "eligible_for_art";
    private static final String TAG_MEMBERS_ON_ART = "members_on_art";
    private static final String TAG_LOST_TO_FOLLOW_UP = "lost_to_follow_up";
    private static final String TAG_MEM_NOT_MET_COUNT = "mem_not_met_count";
    private static final String TAG_VULNERABLE_COUNT = "vulnerable_count";
    private static final String TAG_ID_ZERO = "id_zero";
    private static final String TAG_ID_ONE = "id_one";
    private static final String TAG_ID_TWO = "id_two";
    private static final String TAG_TOP_SCHEMES_ZERO = "top_schems_zero";
    private static final String TAG_TOP_SCHEMES_ONE = "top_schems_one";
    private static final String TAG_TOP_SCHEMES_TWO = "top_schems_two";
    private static final String TAG_SCHEMES_ZERO = "schems_zero";
    private static final String TAG_SCHEMES_ONE = "schems_one";
    private static final String TAG_SCHEMES_TWO = "schems_two";
    private static final String TAG_INCIDENTS_EXTREME = "incidents_extreme";
    private static final String TAG_INCIDENTS_FOLLOW = "incidents_follow";
    private static final String TAG_INCIDENTS_OPENED = "incidents_opened";
    private static final String TAG_INCIDENTS_SEVERITY = "incidents_severity";
    private static final String TAG_MEM_1_INCIDENT_WEEK = "mem_1_incident_week";
    private static final String TAG_MEM_FLS_NOT_COMPLETE = "mem_fls_not_complete";
    private static final String TAG_MEM_FPS_NOT_COMPLETE = "mem_fps_not_complete";
    private static final String TAG_MEM_NO_BANK_ACC_PO = "mem_no_bank_acc_po";
    private static final String TAG_MEM_NO_3MON_SAVINGS = "mem_no_3mon_savings";
    private static final String TAG_MEM_NO_SAVINGS = "mem_no_savings";
    private static final String TAG_MEM_NO_INSURANCE = "mem_no_insurance";
    private static final String TAG_MEM_NO_INVESTMENT = "mem_no_investment";
    private static final String TAG_MEM_DUE = "mem_due";
    private static final String TAG_MEM_CHAMPIONS = "mem_champions";
    private static final String TAG_DUE_COUNT = "due_count";
    private static final String TAG_OVERDUE_COUNT = "overdue_count";
    private static final String TAG_MEM_CHAMPIONS_PROPOSED = "mem_champions_proposed";
    private static final String TAG_MEM_CHAMPIONS_APPROVED = "mem_champions_approved";
    private static final String TAG_ID = "id";

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

        // Calling async task to get json
        new GetTable().execute();
    }

    /**
     * Async task class to get json by making HTTP call
     */
    private class GetTable extends AsyncTask<Void, Void, Void> {

        // Hashmap for ListView
        ArrayList<HashMap<String, String>> tableList;
        ProgressDialog pDialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();
        }

        @Override
        protected Void doInBackground(Void... arg0) {
            // Creating service handler class instance
            WebRequest webreq = new WebRequest();

            // Making a request to url and getting response
            String jsonStr = webreq.makeWebServiceCall(url, WebRequest.GET);

            Log.d("Response: ", "> " + jsonStr);

            tableList = ParseJSON(jsonStr);
           // JSONArray jsonArray=jsonStr.makeWebSer(url);

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**
             * Updating parsed JSON data into ListView
             * */
            ListAdapter adapter = new SimpleAdapter(
                    MainActivity.this, tableList,
                    R.layout.list_item, new String[]{TAG_FIELDWORKER_ID,
                    TAG_FW_NAME,TAG_FACILITY_ID,TAG_FACILITY_NAME}, new int[]{
                    R.id.fieldworkerid, R.id.fw_name,R.id.facility_id,
                    R.id.facility_name});

                     setListAdapter(adapter);
        }

    }

    private ArrayList<HashMap<String, String>> ParseJSON(String json) {
        if (json != null) {
            try {
                // Hashmap for ListView
                ArrayList<HashMap<String, String>> tableList = new ArrayList<HashMap<String, String>>();

               // JSONObject jsonObj = new JSONObject(json);

                // Getting JSON Array node
                JSONArray tableFields = new JSONArray(TABLE_INFO);

                // looping through All tableFields
                for (int i = 0; i < tableFields.length(); i++) {
                     //c=new JSONObject();
                    JSONObject c = tableFields.getJSONObject(i);
                    //JSONObject c=(JSONObject)tableFields.get(i);
                    String fieldworkerid = c.getString(TAG_FIELDWORKER_ID);
                    String fw_name = c.getString(TAG_FW_NAME);
                    String facility_id = c.getString(TAG_FACILITY_ID);
                    String facility_name = c.getString(TAG_FACILITY_NAME);
                    Log.d(TAG_FIELDWORKER_ID,fieldworkerid);
                    Log.d(TAG_FW_NAME,fw_name);
                    Log.d(TAG_FACILITY_ID,facility_id);
                    Log.d(TAG_FACILITY_NAME,facility_name);
                  /*  String fs_mentor_id = c.getString(TAG_FS_MENTOR_ID);
                    String fs_mentor_name = c.getString(TAG_FS_MENTOR_NAME);
                    String state_id = c.getString(TAG_STATE_ID);
                    String state_name = c.getString(TAG_STATE_NAME);
                    String region_id = c.getString(TAG_REGION_ID);
                    String region_name = c.getString(TAG_REGION_NAME);
                    String national_id = c.getString(TAG_NATIONAL_ID);
                    String national_name = c.getString(TAG_NATIONAL_NAME);
                    String total_members = c.getString(TAG_TOTAL_MEMBERS);
                    String positive_members = c.getString(TAG_POSITIVE_MEMBERS);
                    String eligible_for_art = c.getString(TAG_ELIGIBLE_FOR_ART);
                    String members_on_art = c.getString(TAG_MEMBERS_ON_ART);
                    String lost_to_follow_up = c.getString(TAG_LOST_TO_FOLLOW_UP);
                    String mem_not_met_count = c.getString(TAG_MEM_NOT_MET_COUNT);
                    String vulnerable_count = c.getString(TAG_VULNERABLE_COUNT);
                    String id_zero = c.getString(TAG_ID_ZERO);
                    String id_one = c.getString(TAG_ID_ONE);
                    String id_two = c.getString(TAG_ID_TWO);
                    String top_schems_zero = c.getString(TAG_TOP_SCHEMES_ZERO);
                    String top_schems_one = c.getString(TAG_TOP_SCHEMES_ONE);
                    String top_schems_two = c.getString(TAG_TOP_SCHEMES_TWO);
                    String schems_zero = c.getString(TAG_SCHEMES_ZERO);
                    String schschems_one = c.getString(TAG_SCHEMES_ONE);
                    String schems_two = c.getString(TAG_SCHEMES_TWO);
                    String incidents_extreme = c.getString(TAG_INCIDENTS_EXTREME);
                    String incidents_follow = c.getString(TAG_INCIDENTS_FOLLOW);
                    String incidents_opened = c.getString(TAG_INCIDENTS_OPENED);
                    String incidents_severity = c.getString(TAG_INCIDENTS_SEVERITY);
                    String mem_1_incident_week = c.getString(TAG_MEM_1_INCIDENT_WEEK);
                    String mem_fls_not_complete = c.getString(TAG_MEM_FLS_NOT_COMPLETE);
                    String mem_fps_not_complete = c.getString(TAG_MEM_FPS_NOT_COMPLETE);
                    String mem_no_bank_acc_po = c.getString(TAG_MEM_NO_BANK_ACC_PO);
                    String mem_no_3mon_savings = c.getString(TAG_MEM_NO_3MON_SAVINGS);
                    String mem_no_savings = c.getString(TAG_MEM_NO_SAVINGS);
                    String mem_no_insurance = c.getString(TAG_MEM_NO_INSURANCE);
                    String mem_no_investment = c.getString(TAG_MEM_NO_INVESTMENT);
                    String mem_due = c.getString(TAG_MEM_DUE);
                    String mem_champions = c.getString(TAG_MEM_CHAMPIONS);
                    String due_count = c.getString(TAG_DUE_COUNT);
                    String overdue_count = c.getString(TAG_OVERDUE_COUNT);
                    String mem_champions_proposed = c.getString(TAG_MEM_CHAMPIONS_PROPOSED);
                    String mem_champions_approved = c.getString(TAG_MEM_CHAMPIONS_APPROVED);
                    String id = c.getString(TAG_ID);*/

                   /* // 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);*/

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

                    // adding each child node to HashMap key => value
                    table.put(TAG_FIELDWORKER_ID, fieldworkerid);
                    table.put(TAG_FW_NAME, fw_name);
                    table.put(TAG_FACILITY_ID, facility_id);
                    table.put(TAG_FACILITY_NAME, facility_name);

                    // adding table to tablelist
                    tableList.add(table);
                }
                return tableList;
            } catch (JSONException e) {
                e.printStackTrace();
                return null;
            }
        } else {
            Log.e("ServiceHandler", "Couldn't get any data from the url");
            return null;
        }
    }

}

这是http代码...

public class WebRequest {

    static String response = null;
    public final static int GET = 1;
    public final static int POST = 2;

    //Constructor with no parameter
    public WebRequest() {

    }

    /**
    * Making web service call
    *
    * @url - url to make request
    * @requestmethod - http request method
    */
    public String makeWebServiceCall(String url, int requestmethod) {
        return this.makeWebServiceCall(url, requestmethod, null);
    }

    /**
    * Making service call
    *
    * @url - url to make request
    * @requestmethod - http request method
    * @params - http request params
    */
    public String makeWebServiceCall(String urladdress, int requestmethod, HashMap<String, String> params) {
        URL url;
        String response = "";
        try {
            url = new URL(urladdress);

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(15000);
            conn.setConnectTimeout(15000);
            conn.setDoInput(true);
            conn.setDoOutput(true);

            if (requestmethod == POST) {
                conn.setRequestMethod("POST");
            } else if (requestmethod == GET) {
                conn.setRequestMethod("GET");
            }

            if (params != null) {
                OutputStream os = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));

                StringBuilder result = new StringBuilder();
                boolean first = true;
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    if (first)
                        first = false;
                    else
                        result.append("&");

                    result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
                    result.append("=");
                    result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
                }

                writer.write(result.toString());

                writer.flush();
                writer.close();
                os.close();
            }

            int responseCode = conn.getResponseCode();

            if (responseCode == HttpsURLConnection.HTTP_OK) {
                String line;
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                while ((line = br.readLine()) != null) {
                    response += line;
                }

            } else {
                response = "";
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return response;
    }

}

这是logcat中显示的错误....

04-26 05:54:40.534 5884-5884/com.example.converbiz.apidemo E/AndroidRuntime: 致命异常: main java.lang.NullPointerException at android.widget.SimpleAdapter.getCount(SimpleAdapter.java:93) at android.widget.ListView.setAdapter(ListView.java:462) at android.app.ListActivity.setListAdapter(ListActivity.java:265) at com.example.converbiz.apidemo.MainActivity$GetTable.onPostExecute(MainActivity.java:134) at com.example.converbiz.apidemo.MainActivity$GetTable.onPostExecute(MainActivity.java:86) at android.os.AsyncTask.finish(AsyncTask.java:631) at android.os.AsyncTask.access$600(AsyncTask.java:177) at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:137) at android.app.ActivityThread.main(ActivityThread.java:5041) at java.lang.reflect.Method.invokeNative(Native Method) atjava.lang.reflect.Method.invoke(Method.java:511) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) at dalvik.system.NativeStart.main(Native Method)

共有2个答案

柴正祥
2023-03-14

我认为setListAdapter()中有问题。

您调用 setListAdapter(adapter);来自 GetTable 类。

所以尝试从 MainActivity 类的 onCreate() 调用 setListAdapter()。

许子平
2023-03-14

你能替换下面的代码并检查吗

// Hashmap for ListView
    ArrayList<HashMap<String, String>> tableList;
    ProgressDialog pDialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        tableList= new ArrayList<HashMap<String, String>> ;
        // Showing progress dialog
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();
    }

    @Override
    protected Void doInBackground(Void... arg0) {
        // Creating service handler class instance
        WebRequest webreq = new WebRequest();

        // Making a request to url and getting response
        String jsonStr = webreq.makeWebServiceCall(url, WebRequest.GET);

        Log.d("Response: ", "> " + jsonStr);

        tableList = ParseJSON(jsonStr);
       // JSONArray jsonArray=jsonStr.makeWebSer(url);

        return null;
    }
 类似资料:
  • 问题内容: 我正在尝试解析从我的Android应用中的URL提取的JSON结果… 我已经在Internet上尝试了一些示例,但无法使其正常工作。JSON数据如下所示: 提取URL和解析JSON数据的最简单方法是在列表视图中显示它 问题答案: 您可以使用,您必须进行自定义以满足您的需求,但是类似以下内容 异步任务有三种主要方法: -最常用于设置和启动进度对话框 -建立连接并从服务器接收响应(请勿尝试

  • 但是宽度和高度较低的图像成功地加载到图像视图中! 有人能告诉我代码有什么问题吗?我做错了什么?我只想从库中导入相机图像,并在图像视图中显示它们!

  • 问题内容: 我试图获取查找栏的值,只要它发生更改并在下面显示。我正在使用我的seekbar上的方法来调用此方法。 问题答案: 这里有一些额外的帮助: 使用该事件检查搜索栏的进度,您可以将该int返回以在应用程序的其他地方使用它。

  • 问题内容: 这是我正在处理的代码: 我想在列表视图上显示它们。您有任何教程可以帮助我入门吗?我是Web服务的新手。谢谢。 问题答案: 列表视图中最受欢迎的教学作品之一,可能会帮助您: - 拉维的博客 解析json之后要执行的步骤: 您可以使用jackson库用一行代码来解析json。 (单击此链接以获取有关对象映射教程的更多信息)

  • 问题内容: 在最近的几天里,我试图从SQL表中获取数据并将其放入文本框。 表名称:“检查”。 我正在使用的代码: 结果我什么也没得到。有人知道为什么吗?也许我没有正确调用SQL? 问题答案: 一些评论: 不要使用,仅指定您需要的字段 使用-更少的代码,保证处理 我假设这是一个测试程序,否则在循环中将其重置为无意义