处理滚动Android

时间:2014-07-24 09:08:07

标签: android json android-listview scroll handle

我已经在片段中使用了json和我的Listview但是它需要时间,因为我有190个对象,所以我希望它只显示15个Json项目,如果用户滚动到结尾将会更多15个项目。我从dropbox获得的json文件大小为2,3MB。谁能告诉我一个好建议?提前谢谢。

以下是代码。

public class UniversityFragment extends Fragment implements OnScrollListener{

ListView lv;
private ProgressDialog pDialog;


// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_NAME = "name";
private static final String TAG_ADDRESS = "address";
private static final String TAG_CityProvince = "city/province";
private static final String TAG_Country = "country";
private static final String TAG_PHONE_OFFICE = "officephone";
private static final String TAG_Fax = "fax";
private static final String TAG_EMAIL = "email";
private static final String TAG_Site = "site";
private static final String TAG_image = "image";

int textlength = 0;

// contacts JSONArray
JSONArray contacts = null;
JSONObject jsonobject;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;

// Search EditText
EditText inputSearch;

public UniversityFragment() {
}

@SuppressLint("CutPasteId")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_university,
            container, false);
      // Execute DownloadJSON AsyncTask
    contactList = new ArrayList<HashMap<String, String>>();

    lv = (ListView) rootView.findViewById(R.id.listView1);
    inputSearch = (EditText) rootView.findViewById(R.id.inputSearch);
    lv.setTextFilterEnabled(true);
    inputSearch.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence cs, int start, int before,
                int count) {
            // TODO Auto-generated method stub
            // When user changed the Text
            // UniversityFragment.this.adapter.getFilter().filter(cs);
        }

        @Override
        public void beforeTextChanged(CharSequence cs, int start,
                int count, int after) {
            // TODO Auto-generated method stub
            try {
                // ((Filterable)
                // UniversityFragment.this.contacts).getFilter().filter(cs);
            } catch (Exception e) {
                // TODO: handle exception
                Toast.makeText(getActivity(), "" + e, Toast.LENGTH_SHORT)
                        .show();
            }
            // lv.setTextFilterEnabled(true);

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

        }
    });
    // Listview on item click listener
    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // TODO Auto-generated method stub
            Toast.makeText(getActivity(), "Clicked" + position,
                    Toast.LENGTH_LONG).show();
            // getting values from selected ListItem

            String name = ((TextView) view.findViewById(R.id.name))
                    .getText().toString();
            String cp = ((TextView) view.findViewById(R.id.CPt)).getText()
                    .toString();
            String country = ((TextView) view.findViewById(R.id.countryt))
                    .getText().toString();
            String fax = ((TextView) view.findViewById(R.id.faxt))
                    .getText().toString();
            String site = ((TextView) view.findViewById(R.id.sitet))
                    .getText().toString();
            String email = ((TextView) view.findViewById(R.id.emailt))
                    .getText().toString();
            String phone = ((TextView) view.findViewById(R.id.phonet))
                    .getText().toString();
            String address = ((TextView) view.findViewById(R.id.addresst))
                    .getText().toString();
            // Starting single contact activity
            Intent in = new Intent(getActivity(), SingleListItem.class);
            in.putExtra("email", email);
            in.putExtra("city/province", cp);
            in.putExtra("country", country);
            in.putExtra("fax", fax);
            in.putExtra("site", site);
            in.putExtra("name", name);
            in.putExtra("officephone", phone);
            in.putExtra("address", address);enter code here
            startActivity(in);
        }
    });

    lv.setOnScrollListener(new OnScrollListener() {

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem,
                int visibleItemCount, int totalItemCount) {
            // TODO Auto-generated method stub
             if (firstVisibleItem+visibleItemCount == totalItemCount && totalItemCount!=0) {

             }  
        }
    });
    // Calling async task to get json
    new GetContacts().execute();
    return rootView;
}

/**
 * Async task class to get json by making HTTP call
 * */
private class GetContacts extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(getActivity());
        pDialog.setTitle("Loading");
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @Override
    protected Void doInBackground(Void... params) {
        // TODO Auto-generated method stub
          // Create an array
        contactList = new ArrayList<HashMap<String, String>>();
        // Retrieve JSON Objects from the given URL address
        // Creating service handler class instance


        ServiceHandler sh = new ServiceHandler();

        String url = "https://dl.dropbox.com........";
        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
enter code here
        // Log.d("Response: ", "> " + jsonStr);

        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array node
                contacts = jsonObj.getJSONArray(TAG_CONTACTS);

                // looping through All Contacts
                for (int i = 0; i < contacts.length(); i++) {
                    JSONObject c = contacts.getJSONObject(i);
                    String name = c.getString(TAG_NAME);
                    String address = c.getString(TAG_ADDRESS);
                    String country = c.getString(TAG_Country);
                    String cityprovince = c.getString(TAG_CityProvince);
                    String officephone = c.getString(TAG_PHONE_OFFICE);
                    String fax = c.getString(TAG_Fax);
                    String email = c.getString(TAG_EMAIL);
                    String site = c.getString(TAG_Site);
                    // // Phone node is JSON Object
                    // JSONObject phone = c.getJSONObject(TAG_PHONE);
                    // String home = phone.getString(TAG_PHONE_HOME);
                    // tmp hashmap for single contact
                    HashMap<String, String> contact = new HashMap<String, String>();
                    // adding each child node to HashMap key => value
                    contact.put(TAG_NAME, name);
                    contact.put(TAG_ADDRESS, address);
                    contact.put(TAG_CityProvince, cityprovince);
                    contact.put(TAG_Country, country);
                    contact.put(TAG_PHONE_OFFICE, officephone);
                    contact.put(TAG_EMAIL, email);
                    contact.put(TAG_Site, site);
                    contact.put(TAG_Fax, fax);
                    // adding contact to contact list
                    contactList.add(contact);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            Log.e("ServiceHandler", "Couldn't get any data from the url");
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();
        Toast.makeText(getActivity(), "Thank for your patience", Toast.LENGTH_LONG).show();
        /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(getActivity(), contactList,
                R.layout.listsingleitem, new String[] { TAG_NAME,
                        TAG_ADDRESS, TAG_CityProvince, TAG_Country,
                        TAG_PHONE_OFFICE, TAG_Fax, TAG_EMAIL, TAG_Site },
                new int[] { R.id.name, R.id.addresst, R.id.CPt,
                        R.id.countryt, R.id.phonet, R.id.faxt, R.id.emailt,
                        R.id.sitet });
        adapter.notify();
        //adapter.notifyDataSetChanged();
        lv.setAdapter(adapter);


    }
}

1 个答案:

答案 0 :(得分:0)

您需要实现无限适配器(自定义列表视图适配器)以支持并发加载和显示。

请参阅本教程:http://www.survivingwithandroid.com/2013/10/android-listview-endless-adapter.html