【发布时间】:2020-03-11 23:22:53
【问题描述】:
我是 android 的新手,也是 JSON。我正在尝试使用 recyclerviw 从 Web 服务器显示 JSON 格式的数据。在我的 MainActivity 代码中,我在 ArrayList 中使用了 HashMap,我已经从 Web 服务器解析数据并将其放入 ArrayList 下的 HashMap 中。我将 id、name、email、移动数据放入 ArrayList 下的 HashMap 中。但我想使用 recyclerview 只显示电子邮件和移动数据。但我不知道如何使用 recyclerview 仅显示电子邮件和移动数据。
这是我的 JSON Web 服务器链接:http://api.androidhive.info/contacts/
我的完整代码如下:
MainActivity 代码:
public class MainActivity extends AppCompatActivity {
JSONArray contacts;
Context context;
ArrayList<HashMap<String, String>> contactList;
public static final String TAG =MainActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = findViewById(R.id.recyclerview);
ArrayAdapter adapter = new ArrayAdapter(context,contactList,contacts);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
new getContacts().execute();
}
private class getContacts extends AsyncTask<Void, Void, Void>{
@Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(getApplicationContext(),"JSON Data is" +
" downloading",Toast.LENGTH_LONG).show();
}
@Override
protected Void doInBackground(Void... voids) {
HttpHandler sh = new HttpHandler();
String url = "http://api.androidhive.info/contacts/";
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG,"Response from url: " + jsonStr);
if(jsonStr != null){
try{
JSONObject jsonObject = new JSONObject(jsonStr);
contacts = jsonObject.getJSONArray("contacts");
for (int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String email = c.getString("email");
String address = c.getString("address");
String gender = c.getString("gender");
JSONObject phone = c.getJSONObject("phone");
String mobile = phone.getString("mobile");
String home = phone.getString("home");
String office = phone.getString("office");
HashMap<String, String> contact = new HashMap<>();
contact.put("id", id);
contact.put("name", name);
contact.put("email", email);
contact.put("mobile", mobile);
contactList.add(contact);
}
}catch (final JSONException e){
Log.e(TAG, "Json parsing error: " +e.getMessage());
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),"Json parsing error: "
+ e.getMessage(),Toast.LENGTH_LONG).show();
}
});
}
}else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),"Couldn't get json from server. Check LogCat for possible errors",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
}
}
ArrayAdapter 代码:
public class ArrayAdapter extends RecyclerView.Adapter<ArrayAdapter.MyViewHolder>{
Context context;
ArrayList<HashMap<String, String>> contactList;
JSONArray contacts;
public ArrayAdapter(Context context, ArrayList<HashMap<String, String>> contactList, JSONArray contacts) {
this.context = context;
this.contactList = contactList;
this.contacts = contacts;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.row_item,parent,false);
return new MyViewHolder(v);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
holder.email.setText((CharSequence) contactList.get(position));
holder.mobile.setText((CharSequence) contactList.get(position));
}
@Override
public int getItemCount() {
return contacts.length();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView email;
TextView mobile;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
if(contacts.length() >= 2){
email = itemView.findViewById(R.id.email);
mobile = itemView.findViewById(R.id.mobile);
}
}
}
}
HttpHandler 代码:
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl){
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn =(HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
}catch (MalformedURLException e){
Log.e(TAG,"MalformException: " + e.getMessage());
}catch (ProtocolException e){
Log.e(TAG,"ProtocolException: " + e.getMessage());
}catch (IOException e){
Log.e(TAG, "IOException: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is){
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
boolean line;
try {
while (line = reader.readLine() != null){
sb.append(line).append('\n');
}
}catch (IOException e){
e.printStackTrace();
}finally {
try {
is.close();
}catch (IOException e){
e.printStackTrace();
}
}
return sb.toString();
}
}
【问题讨论】:
标签: android json android-studio android-recyclerview hashmap