如何在ExpandableListView中减少服务器数据的加载时间?

时间:2017-10-25 05:28:46

标签: java android

我想要做的是:将会有一些标题项目将从" string.xml"中借出。单击特定标题项时,其下的子项将从服务器加载并立即缓慢扩展。如果再次点击它会慢慢崩溃。

我做了什么:

activity_main.xml中:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.cnpinyin.lastchinese.activities.VocabularyList"
    tools:showIn="@layout/app_bar_vocabulary_list">


    <ExpandableListView
        android:id="@+id/expnadable_listview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:divider="#A4C739"
        android:dividerHeight="0.5dp"
        android:indicatorLeft="?android:attr/expandableListPreferredItemIndicatorLeft">

    </ExpandableListView>

</android.support.constraint.ConstraintLayout>

parent_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/header_title"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="?android:attr/expandableListPreferredItemPaddingLeft"
        android:paddingTop="10dp"
        android:paddingBottom="10dp"
        android:textColor="#A4C739"
        android:textSize="18dp"

        />

</LinearLayout>

child_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/child_header"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="10dp"
        android:paddingLeft="?android:attr/expandableListPreferredItemPaddingLeft"
        android:paddingTop="10dp"
        android:text="Thsi is child"
        android:textColor="#000"
        android:textSize="18dp" />

</LinearLayout>

MainActivity

package com.cnpinyin.lastchinese.activities;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.Toast;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.cnpinyin.lastchinese.R;
import com.cnpinyin.lastchinese.adapters.ExpandabelListAdapter;
import com.cnpinyin.lastchinese.singleton.MySingleton;

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

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import static android.icu.lang.UCharacter.GraphemeClusterBreak.T;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    ExpandableListView exp_listview;
    ExpandabelListAdapter adapter;

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


        exp_listview = (ExpandableListView) findViewById(R.id.expnadable_listview);

        String[] heading_items = getResources().getStringArray(R.array.heading_items);

        final List<String> headings = new ArrayList<String>(Arrays.asList(heading_items));

        final HashMap<String, List<String>> childList  = new HashMap<String, List<String>>();

        for(int i=0; i<headings.size(); i++){
            childList.put(headings.get(i), new ArrayList<String>());
        }

        adapter = new ExpandabelListAdapter(headings, childList, getApplicationContext());

        exp_listview.setAdapter(adapter);

        exp_listview.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, final int groupPosition, final long id) {

                String server_url =  "http://192.168.56.1:8080/voc/topic";
                JsonArrayRequest jsonArray = new JsonArrayRequest(Request.Method.GET, server_url, (String)null,
                        new Response.Listener<JSONArray>() {
                            @Override
                            public void onResponse(JSONArray response) {
                                List<String> topicList = new ArrayList<String>();

                                try{

                                    for(int i=0;i<response.length();i++){
                                        // Get current json object
                                        JSONObject topicObj = response.getJSONObject(i);

                                        // Get the current student (json object) data
                                        String topic = topicObj.getString("topic");
                                        topicList.add(topic);

                                    }

                                    childList.put(headings.get(groupPosition), topicList);

                                    Toast.makeText(VocabularyList.this,  topicList +"", Toast.LENGTH_SHORT).show();

                                }catch (Exception e){
                                    e.printStackTrace();
                                }

                            }
                        },

                        new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {

                                Toast.makeText(VocabularyList.this,  error + "", Toast.LENGTH_SHORT).show();
                            }
                        }

                );

                MySingleton.getInstance(getApplicationContext()).addToRequestQueue(jsonArray);

                return false;
            }
        });
    }

}

ExpandabelListAdapter

package com.cnpinyin.lastchinese.adapters;

import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;

import com.cnpinyin.lastchinese.R;

import java.util.HashMap;
import java.util.List;

/**
 * Created by inspiron on 8/24/2017.
 */

public class ExpandabelListAdapter extends BaseExpandableListAdapter {

    private List<String> header_titles;
    private HashMap<String, List<String>> child_titles;
    private Context ctx;

    public ExpandabelListAdapter(List<String> header_titles, HashMap<String, List<String>> child_titles, Context ctx) {
        this.header_titles = header_titles;
        this.child_titles = child_titles;
        this.ctx = ctx;
    }



    @Override
    public int getGroupCount() {
        return header_titles.size();
    }




    @Override
    public int getChildrenCount(int groupPosition) {
        return child_titles.get(header_titles.get(groupPosition)).size();
    }




    @Override
    public Object getGroup(int groupPosition) {
        return header_titles.get(groupPosition);
    }




    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return child_titles.get(header_titles.get(groupPosition)).get(childPosition);
    }




    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }





    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }





    @Override
    public boolean hasStableIds() {
        return false;
    }





    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        String title = (String) this.getGroup(groupPosition);

        if(convertView == null){
            LayoutInflater layoutInflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = layoutInflater.inflate(R.layout.parent_layout, null);
        }

        TextView headerTitle = (TextView) convertView.findViewById(R.id.header_title);
        headerTitle.setText(title);
        headerTitle.setTypeface(null, Typeface.BOLD);

        return convertView;
    }



    @Override
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        String child_title = (String) getChild(groupPosition, childPosition);
        if(convertView == null){
            LayoutInflater inflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.child_layout, null);
        }

        TextView childHeader = (TextView) convertView.findViewById(R.id.child_header);
        childHeader.setText(child_title);
        childHeader.setTypeface(null, Typeface.BOLD);
        return convertView;
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }
}

当我点击特定标题项时,Toast立即显示maessage。但不扩展其下的项目。这花费了很多时间。我无法解决问题。需要帮助。感谢。

1 个答案:

答案 0 :(得分:0)

为了更好的响应时间,您可以使用缓存机制。

您可以在服务器端使用Guava进行缓存。这将缩短请求的响应时间。您也可以在Android的客户端缓存。