【问题标题】:How to display JSON format data from web server using recyclerview in android如何在android中使用recyclerview显示来自Web服务器的JSON格式数据
【发布时间】: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


    【解决方案1】:

    在你的arrayAdapter.class的onBindViewHolder方法中

    改变这个:

    holder.email.setText((CharSequence) contactList.get(position));
    

    与:

    holder.email.setText((CharSequence) contactList.get(position).get("email"));
    

    对其他项目也做同样的事情

    【讨论】:

    • 现在显示错误消息: public int getItemCount() { return contacts.length(); }
    • JSON Web 服务器链接在上面给出。请帮忙。getItemCount 的长度是多少。
    • @SheikhSaadi return contactList.length();或(替换为您拥有的联系人数量)
    • 它不适用于contactList.size();或contact.size();
    • @SheikhSaadi 你是在 asynkTask 中的 for 循环之后调用适配器 notifyDataSetChanged
    【解决方案2】:

    holder.email.setText((CharSequence) contactList.get(position).get("email"); holder.mobile.setText((CharSequence) contactList.get(position).get("mobile"); 通过键名从arraylist获取电子邮件和手机

    【讨论】:

    • getItemCount() 的返回值是多少;对于上面的代码。
    • 返回contactList.size();你确保contactList不为空
    【解决方案3】:

    试试这个

    MainActivity

    public class MainActivity extends AppCompatActivity {
    
    private ArrayAdapter adapter;
    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);
        adapter = new ArrayAdapter(getApplicationContext());
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        new getContacts().execute();
    
    }
    
        private class getContacts extends AsyncTask<Void, Void, List<HashMap<String, String>>> {
    
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            Toast.makeText(getApplicationContext(),"JSON Data is" +
                    " downloading",Toast.LENGTH_LONG).show();
        }
    
        @Override
        protected List<HashMap<String, String>> 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);
    
                    List<HashMap<String, String>> contactList = new ArrayList<>();
    
                    JSONArray 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);
                    }
                    return contactList;
                }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(List<HashMap<String, String>> result) {
            super.onPostExecute(result);
            if(result != null){
                adapter.add(result);
                adapter.notifyDataSetChanged();
            }
        }
    }
    

    }

    阵列适配器

    public class ArrayAdapter extends RecyclerView.Adapter<ArrayAdapter.MyViewHolder>{
    
    Context context;
    LayoutInflater inflater;
    List<HashMap<String, String>> contactList;
    
    public ArrayAdapter(Context context) {
        this.context = context;
        inflater = LayoutInflater.from(context);
        this.contactList = new ArrayList<>();
    }
    
    public void add(List<HashMap<String, String>> arg){
        contactList.addAll(arg);
    }
    
    
    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View v = inflater.inflate(R.layout.row_item,parent,false);
    
        return new  MyViewHolder(v);
    }
    
    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        HashMap<String, String> data = contactList.get(position);
        holder.bindData(data);
    }
    
    @Override
    public int getItemCount() {
        return contactList.size();
    }
    
    public class MyViewHolder extends RecyclerView.ViewHolder {
        private TextView email;
        private TextView mobile;
    
        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            email = itemView.findViewById(R.id.email);
            mobile = itemView.findViewById(R.id.mobile);
        }
    
        public void bindData(HashMap<String, String> data){
            email.setText(data.get("email"));
            mobile.setText(data.get("mobile"));
        }
    }
    

    }

    【讨论】:

    • 现在显示此错误消息:java.lang.NullPointerException: Attempt to invoke virtual method 'int org.json.JSONArray.length()' on an null object reference at com.example.jsonparsing.ArrayAdapter .getItemCount(ArrayAdapter.java:50)
    • 再次检查我的 getItemCount 方法。我没有使用 jsonarray.length() 方法。这是我的代码 @Override public int getItemCount() { return contactList.size(); }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-22
    • 1970-01-01
    • 2020-08-21
    • 2013-04-03
    • 2015-11-24
    相关资源
    最近更新 更多