我发现我现在的主要问题是我的 Intent 代码。我不知道如何构建我的 Intent ,使数据从网站返回,所以如果有人可以帮助我,那就太棒了!我正在尝试从 openweather api 获取 JSON 数据,我的应用程序将加载网页而不是将其带入 ListView 。现在,按照我的 Intent ,会打开一个网页,其中包含我需要的数据。任何帮助都会很棒!
public class MainActivity extends AppCompatActivity {
private String url = "http://api.openweathermap.org/data/2.5/weather?q=London,us&APPID=805bd9f830268d5274c60e41613c28a5";
private List<String> items = new ArrayList<String>();
private ArrayAdapter<String> mArrayAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button btnRequest = (Button) findViewById(R.id.button); //your button id must be button
final ListView lv = (ListView) findViewById(R.id.listView); //your listview ide must be listview
final RequestQueue requestQueue = Volley.newRequestQueue(this);
final JsonObjectRequest jor = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONObject jcity = response.getJSONObject("city");
String name = jcity.getString("name");
JSONArray wlist = response.getJSONArray("list");
for (int i = 0; i < 10; i++) {
JSONObject jsonObject = wlist.getJSONObject(i);
String dt = jsonObject.getString("dt");
JSONArray warray = jsonObject.getJSONArray("weather");
JSONObject wobj = warray.getJSONObject(0);
String desc = wobj.getString("description");
items.add(dt + " " + desc);
Log.d("date", dt); //Log.d prints to the terminal
Log.d("desc", desc);//good for debugging
}
mArrayAdapter = new ArrayAdapter<String>
(getApplicationContext(),
android.R.layout.simple_list_item_1, items);
//lv.setAdapter(mArrayAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "Error");
}
}
);
btnRequest.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
requestQueue.add(jor);
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
}
}
最佳答案
我认为这是因为您错过了 ListView
的设置适配器。并且还要确保您的项目内部有数据。
mArrayAdapter = new ArrayAdapter<String> (getApplicationContext(), android.R.layout.simple_list_item_1, items);
lv.setAdapter(mArrayAdapter);
关于java - 有人可以告诉我为什么我的 listView 没有填充 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47724247/