【问题标题】:JSON data doesn't load when send a request发送请求时未加载 JSON 数据
【发布时间】:2020-10-05 16:25:52
【问题描述】:

我正在尝试构建一个 JSON 请求应用程序。它从这个网站“https://earthquake.usgs.gov/fdsnws/event/1/query”获取地震参数。我面临的问题是,当应用程序 Activity 启动时,只有进度条可见,但没有显示 JSON 数据,也没有显示 textview,只有进度条一直加载到最后。我试过但无法解决错误所在。请帮帮我,我刚在这里呆了几天。提前谢谢你

我的主要活动代码

package com.example.volleyearthquake;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

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

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private RequestQueue mRequestQueue;
    private ArrayList<Earthquake> mEarthquake;
    private RecyclerView mRecycleView;
    private EarthquakeAdapter adapter;

    boolean isConnected;
    /**
     * Textview to be displayed when the listview have no data
     */
    TextView emptyView;
    /**
     * Progressbar variable which is circular spinner (loading indicator)
     */
    ProgressBar loadingIndicator;
    private static final String USS_REQUEST_URL = "https://earthquake.usgs.gov/fdsnws/event/1/query";

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

        final ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);

        Read_network_state(cm);
        loadingIndicator = findViewById(R.id.loading_indicator);
        emptyView = findViewById(R.id.empty_view);

        mRecycleView = findViewById(R.id.recycle_list);
        mRecycleView.setHasFixedSize(true);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        mRecycleView.setLayoutManager(manager);
        mEarthquake = new ArrayList<>();
        adapter = new EarthquakeAdapter(MainActivity.this, mEarthquake);

        mRecycleView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        mRequestQueue = Volley.newRequestQueue(this);
        parseEarthquake();

    }

    private void parseEarthquake() {

        final JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, USS_REQUEST_URL,
                null, response -> {

            try {
                JSONArray feature = response.getJSONArray("features");
                for (int index = 0; index < feature.length(); index++) {
                    JSONObject features = feature.getJSONObject(index);
                    JSONObject properties = features.getJSONObject("properties");
                    Double magnitude = properties.getDouble("mag");
                    String location = properties.getString("place");
                    long time = properties.getLong("time");
                    String url = properties.getString("url");

                    mEarthquake.add(new Earthquake(magnitude, location, time, url));
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }, error -> {

        });
        mRequestQueue.add(request);
    }

    public void Read_network_state(ConnectivityManager connectivityManager) {

        NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
        if (activeNetwork != null && activeNetwork.isConnectedOrConnecting()) {
            isConnected = true;
            Log.d("Ruhul", "CONNECTED TO INTERNET");
        } else {
            isConnected = false;
        }
    }
}

在清单文件中我也添加了

<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

【问题讨论】:

  • mEarthquake.add() 之后添加 adapter.notifyDataSetChanged(); 如果 JSONException 被抛出,还要注意你的日志猫
  • 我终于解决了。问题出在 URL 中,我认为该 url 已过时,所以我使用新的(earthquake.usgs.gov/earthquakes/feed/v1.0/summary/…),现在它工作正常。感谢您的回复

标签: java android json android-studio android-volley


【解决方案1】:

请检查是否有 JSON 异常。很可能,这就是您解析不正确的原因,如果不检查您的 JSON 响应,就很难确定您是否正确解析了内容。

【讨论】:

  • 我是这样写的 catch (JSONException e) { Log.e("QueryUtils", "Problem parsing the earthquake JSON results", e); } 然后我 logcat 它但是当我在 logcat 中搜索“QueryUtils”时没有显示任何内容。我想我在那里犯了一些错误,如果我犯了,请告诉我如何写以及在哪里写。我对 android 开发有点陌生
【解决方案2】:

把 parseEarthquake();以上 mRequestQueue = Volley.newRequestQueue(this);

喜欢这个

mRecycleView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        parseEarthquake();
        mRequestQueue = Volley.newRequestQueue(this);

如果 dosetn 工作请分享您的错误。

【讨论】:

  • 按照您上面所说的更改代码后。应用程序崩溃并出现错误Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.android.volley.Request com.android.volley.RequestQueue.add(com.android.volley.Request)' on a null object reference at com.example.volleyearthquake.MainActivity.parseEarthquake(MainActivity.java:103) at com.example.volleyearthquake.MainActivity.onCreate(MainActivity.java:69) 69 line was-parseEarthquake();第 103 行是 mRequestQueue.add(request);
【解决方案3】:

首先你必须解析Earthquakes,然后将它们放在recyclerView中,如果仍然有错误,请尝试逐步跟踪您的请求并检查locat以确保您正确解析json并且解析时没有错误, 提示:json在解析时发生错误不会导致应用程序崩溃...希望我的回答对您有所帮助^_^

【讨论】:

  • 如果您不介意,请出示一下。我有点困惑
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-23
  • 1970-01-01
  • 1970-01-01
  • 2020-01-11
  • 1970-01-01
  • 1970-01-01
  • 2020-08-19
相关资源
最近更新 更多