【发布时间】:2021-08-03 01:05:29
【问题描述】:
我正在尝试将我使用 URL 检索到的 JSON 文件中的一些但不是全部信息显示到 Android JAVA 中的列表视图中。 JSON 有很多字段,但我只想要其中两个。我已经设法在 iOS 中完成了相同的应用程序,并且不得不将这些字段设为可选,但我不确定如何在 Android 中执行此操作。
主活动
public class MainActivity extends AppCompatActivity {
private ListView lv;
String username, online;
private static String JSON_URL = "http://**.***.**.***:*****/userconfig";
ArrayList<HashMap<String, String>> usersList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
usersList = new ArrayList<>();
lv = findViewById(R.id.listView);
GetData getData = new GetData();
getData.execute();
}
public class GetData extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... strings) {
String current = "";
try {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(JSON_URL);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(in);
int data = isr.read();
while (data != -1) {
current += (char) data;
data = isr.read();
}
return current;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return current;
}
@Override
protected void onPostExecute(String s) {
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray jsonArray = jsonObject.getJSONArray("users");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
username = jsonObject1.getString("username");
online = jsonObject1.getString("online");
//Hashmap
HashMap<String, String> friends = new HashMap<>();
friends.put("username", username);
friends.put("online", online);
usersList.add(friends);
}
} catch (JSONException e) {
e.printStackTrace();
}
//Display the results
ListAdapter adapter = new SimpleAdapter(
MainActivity.this,
usersList,
R.layout.row_layout,
new String[] {"username", "online"},
new int[]{R.id.textView, R.id.textView2});
lv.setAdapter(adapter);
}
}
}
【问题讨论】:
标签: java android json listview url