【问题标题】:Count number of elements in a JSON Array, and display the result on Textview - Android计算 JSON 数组中的元素数量,并在 Textview 上显示结果 - Android
【发布时间】:2016-08-27 11:54:43
【问题描述】:

我想计算通过 JSON 数组获得的元素数量,并使用 .settext() 方法将其显示在 TextView 上。 我得到以下 JSON 数组:

{ “结果”: [ { “id”:“283”, "全名":"shyam", "联系人号码":"898888888", “学院名称”:“mjc”, “电子邮件地址”:“shyamzawar”, “事件名称”:“游戏” }, { “id”:“285”, "全名":"ffca", "联系人号码":"8888888888", "collegename":"布里汉马哈拉施特拉商学院 (BMCC)", "电子邮件地址":"shyamzawar@ymail.com", “事件名称”:“足球” } ] }

以下是我的活动:

private static final String TAG = "userList";
private List<FeedItem> feedsList;
private RecyclerView mRecyclerView;
private MyRecyclerAdapter adapter;
private ProgressBar progressBar;
private TextView ParticipantsCounts;
int count=0;

private SwipeRefreshLayout swipeRefreshLayout;

private final String url="http://bmcctroika.hol.es/get-data.php";;

private int offSet = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_admin);
    // Initialize recycler view
    mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(this));

    progressBar = (ProgressBar) findViewById(R.id.progress_bar);
    progressBar.setVisibility(View.VISIBLE);

    ParticipantsCounts= (TextView) findViewById(R.id.ParticipantsCount);

    // Downloading data from below url
    new AsyncHttpTask().execute(url);
    swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);

    swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            refreshitems();
        }
    });
}

private void refreshitems() {
    new AsyncHttpTask().execute(url);
}

@Override
public void onRefresh() {
    new AsyncHttpTask().execute(url);
}

public class AsyncHttpTask extends AsyncTask<String, Void, Integer> {

    @Override
    protected void onPreExecute() {
        setProgressBarIndeterminateVisibility(true);
    }

    @Override
    protected Integer doInBackground(String... params) {
        Integer result = 0;
        HttpURLConnection urlConnection;
        try {
            URL url = new URL(params[0]);
            urlConnection = (HttpURLConnection) url.openConnection();
            int statusCode = urlConnection.getResponseCode();

            // 200 represents HTTP OK
            if (statusCode == 200)
            {
                BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = r.readLine()) != null)
                {
                    response.append(line);
                }
                parseResult(response.toString());
                result = 1; // Successful

            } else {
                result = 0; //"Failed to fetch data!";
            }
        } catch (Exception e) {
            Log.d(TAG, e.getLocalizedMessage());
        }
        return result; //"Failed to fetch data!";
    }

    @Override
    protected void onPostExecute(Integer result)
    {
        // Download complete.
        progressBar.setVisibility(View.GONE);
        if (result == 1)
        {
            adapter = new MyRecyclerAdapter(AdminActivity.this, feedsList);
            mRecyclerView.setAdapter(adapter);
        } else
        {
            Toast.makeText(AdminActivity.this, "Failed to fetch data!", Toast.LENGTH_SHORT).show();
        }
        swipeRefreshLayout.setRefreshing(false);
    }
}

private void parseResult(String result) {
    try {
        JSONObject response = new JSONObject(result);
        JSONArray posts = response.optJSONArray("result");
        feedsList = new ArrayList<>();
        for (int i = 0; i < posts.length(); i++) {
            JSONObject post = posts.optJSONObject(i);
            FeedItem item = new FeedItem();
            item.setTitle(post.optString("fullname"));
            item.setContact(post.optString("contactno"));
            item.setEmail(post.optString("emailaddress"));
            item.setEventname(post.optString("eventname"));
            item.setCollegename(post.optString("collegename"));
            feedsList.add(item);
        }

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

【问题讨论】:

    标签: android arrays json parsing


    【解决方案1】:

    您需要获取result JSONArraylenght。所以在你的代码中,你可以得到posts——JSONArray posts = response.optJSONArray("result");的长度。 这将为您提供结果数组中的项目数:

    private void parseResult(String result) {
        try {
            JSONObject response = new JSONObject(result);
            JSONArray posts = response.optJSONArray("result");
            int number = posts.length();
            //then to set it to the text view:
            ParticipantsCounts.setText(String.valueOf(number));
            //the rest of your code ...
            feedsList = new ArrayList<>();
            for (int i = 0; i < posts.length(); i++) {
                JSONObject post = posts.optJSONObject(i);
                FeedItem item = new FeedItem();
                item.setTitle(post.optString("fullname"));
                item.setContact(post.optString("contactno"));
                item.setEmail(post.optString("emailaddress"));
                item.setEventname(post.optString("eventname"));
                item.setCollegename(post.optString("collegename"));
                feedsList.add(item);
            }
    
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    

    【讨论】:

    • 太好了,我很高兴它有帮助。继续编码。
    • 嘿,等等,它在解析 JSON 数据时出错,计数运行良好,但现在,它不显示解析的数据 @ishmaelMakitla
    • 但那是一个不同的问题(你拒绝答案?) - 你想知道如何在 JSONArray 中显示项目的计数/数量。在任何情况下,请粘贴您遇到的错误 - 或发布一个单独的问题,其中包含您需要帮助的特定错误。
    • 如果我删除此代码 'int number = posts.length(); //然后将其设置为文本视图:ParticipantsCounts.setText(String.valueOf(number));'我得到解析的数据,否则我只得到元素计数
    • 这很奇怪,因为这两行并没有对实际的 JSONArray 对象做任何事情——只是得到了计数。请粘贴 parseResult 函数的更新代码 - 这样我就可以看到您的代码版本并建议如何更正它。
    猜你喜欢
    • 2016-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-09
    • 1970-01-01
    • 2020-07-21
    相关资源
    最近更新 更多