Список просмотра страниц в Android

У меня есть просмотр списка, где у меня отображается 50 элементов. Я решил разбить представление на страницы, чтобы в каждой части было 10 элементов, а затем нажимали следующую кнопку, чтобы перейти к следующим 10 элементам. Как я могу установить 10 данных? Я следую за этой статьейhttp://rakhi577.wordpress.com/2013/05/20/listview-pagination-ex-2/ Вот мой код. Можете ли вы помочь мне с моим кодом или ссылкой на руководство о том, как правильно это реализовать?

public class MainActivity extends ListActivity {


Context context;
Button btnSearch ;
EditText txtSearch;

private ProgressDialog pDialog;

// URL to get contacts JSON

    public int TOTAL_LIST_ITEMS = 50;
    public int NUM_ITEMS_PAGE   = 10;
    private int noOfBtns;
    private Button[] btns;


// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";

// contacts JSONArray
JSONArray contacts = null;

// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btnSearch=(Button)findViewById(R.id.buttonSearch);
    txtSearch=(EditText)findViewById(R.id.Searchtext);




}

public String gotourl()
{


    final  EditText txtSearch=(EditText)findViewById(R.id.Searchtext);

     String ts=txtSearch.getText().toString();

     String url = "http://latest.bloomapi.com/api/search?limit=50&offset=0&key1=last_name&op1=eq&value1="+ts;

    return url ;
}

public void Searchfunction(View v)

{
    Btnfooter();
    //loadList(0);
    CheckBtnBackGroud(0);
    contactList = new ArrayList<HashMap<String, String>>();

    ListView lv = getListView();




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

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {



            // getting values from selected ListItem
            String name = ((TextView) view.findViewById(R.id.name))
                    .getText().toString();
            String cost = ((TextView) view.findViewById(R.id.email))
                    .getText().toString();
            String description = ((TextView) view.findViewById(R.id.mobile))
                    .getText().toString();

            // Starting single contact activity
            Intent in = new Intent(getApplicationContext(),
                    SingleContactActivity.class);
            in.putExtra(TAG_NAME, name);
            in.putExtra(TAG_EMAIL, cost);
            in.putExtra(TAG_PHONE_MOBILE, description);
            startActivity(in);

        }
    });

    // Calling async task to get json
    new GetContacts().execute();    
}
private void Btnfooter()
{
    int val = TOTAL_LIST_ITEMS%NUM_ITEMS_PAGE;
    val = val==0?0:1;
    noOfBtns=TOTAL_LIST_ITEMS/NUM_ITEMS_PAGE+val;

    LinearLayout ll = (LinearLayout)findViewById(R.id.btnLay);

    btns    =new Button[noOfBtns];

    for(int i=0;i<noOfBtns;i++)
    {
        btns[i] =   new Button(this);
        btns[i].setBackgroundColor(getResources().getColor(android.R.color.transparent));
        btns[i].setText(""+(i+1));

        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        ll.addView(btns[i], lp);

        final int j = i;
        btns[j].setOnClickListener(new OnClickListener() {

            public void onClick(View v) 
            {
                //loadList(j);
                CheckBtnBackGroud(j);
            }
        });
    }

}

 private void CheckBtnBackGroud(int index)
    {

        for(int i=0;i<noOfBtns;i++)
        {
            if(i==index)
            {
                btns[index].setBackgroundDrawable(getResources().getDrawable(R.drawable.box_green));
                btns[i].setTextColor(getResources().getColor(android.R.color.white));
            }
            else
            {
                btns[i].setBackgroundColor(getResources().getColor(android.R.color.transparent));
                btns[i].setTextColor(getResources().getColor(android.R.color.black));
            }
        }

    }




private class GetContacts extends AsyncTask<Void, Void, Void> {

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

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        // Creating service handler class instance
        ServiceHandler sh = new ServiceHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(gotourl(), ServiceHandler.GET);

        Log.d("Response: ", "> " + jsonStr);

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

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

                // looping through All Contacts
                for (int i = 0; i < contacts.length(); i++) {
                    Integer a = contacts.length();
                    Log.d("loop", a.toString());
                    JSONObject c = contacts.getJSONObject(i);

                    String id = c.getString("npi");
                    String name = c.getString("first_name");
                    String email = c.getString("last_name");
                    //String address = c.getString(TAG_ADDRESS);
                    String gender = c.getString("type");


                    // tmp hashmap for single contact
                    HashMap<String, String> contact = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    contact.put("npi", id);
                    contact.put("first_name", name);
                    contact.put("last_name", email);
                    //contact.put(TAG_PHONE_MOBILE, mobile);

                    contact.put("type", gender);
                    // adding contact to contact list
                    contactList.add(contact);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            Log.d("ServiceHandler", "Couldn't get any data from the url");


        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();
        /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(
                MainActivity.this, contactList,
                R.layout.list_item, new String[] { "first_name", "last_name",
                        "type" }, new int[] { R.id.name,
                        R.id.email, R.id.mobile });

        setListAdapter(adapter);
    }

}}

Я изменяю код Когда я нажимаю кнопку «Далее» [как 2,3,4,5]. показывая данные первой страницы. Вот мой модифицированный код. Любая помощь оценена:

public class MainActivity extends ListActivity {

private TextView title;
Context context;
Button btnSearch ;
EditText txtSearch;
private ListView listview;

private ProgressDialog pDialog;

// URL to get contacts JSON

    public int TOTAL_LIST_ITEMS = 50;
    public int NUM_ITEMS_PAGE   = 10;
    private int noOfBtns;
    private Button[] btns;




// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";

// contacts JSONArray
JSONArray contacts = null;

// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btnSearch=(Button)findViewById(R.id.buttonSearch);
    txtSearch=(EditText)findViewById(R.id.Searchtext);
    title    = (TextView)findViewById(R.id.title);

}

public String gotourl()
{


     final  EditText txtSearch=(EditText)findViewById(R.id.Searchtext);

     String ts=txtSearch.getText().toString();

     String url = "http://latest.bloomapi.com/api/search?limit=50&offset=0&key1=last_name&op1=eq&value1="+ts;

     return url ;
}

public void Searchfunction(View v)

{
    Btnfooter();


    CheckBtnBackGroud(0);
    contactList = new ArrayList<HashMap<String, String>>();

    ListView lv = getListView();




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

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {

            if(position%2==0)
            {
                view.setBackgroundColor(Color.parseColor("#F4FA58"));

            }else
            {
            view.setBackgroundColor(Color.parseColor("#DA81F5"));
            }

            // getting values from selected ListItem
            String name = ((TextView) view.findViewById(R.id.name))
                    .getText().toString();
            String cost = ((TextView) view.findViewById(R.id.email))
                    .getText().toString();
            String description = ((TextView) view.findViewById(R.id.mobile))
                    .getText().toString();

            // Starting single contact activity
            Intent in = new Intent(getApplicationContext(),
                    SingleContactActivity.class);
            in.putExtra(TAG_NAME, name);
            in.putExtra(TAG_EMAIL, cost);
            in.putExtra(TAG_PHONE_MOBILE, description);
            startActivity(in);

        }
    });

    // Calling async task to get json
    new GetContacts().execute();    
}
private void Btnfooter()
{
    int val = TOTAL_LIST_ITEMS%NUM_ITEMS_PAGE;
    val = val==0?0:1;
    noOfBtns=TOTAL_LIST_ITEMS/NUM_ITEMS_PAGE+val;

    LinearLayout ll = (LinearLayout)findViewById(R.id.btnLay);

    btns    =new Button[noOfBtns];

    for(int i=0;i<noOfBtns;i++)
    {
        btns[i] =   new Button(this);
        btns[i].setBackgroundColor(getResources().getColor(android.R.color.transparent));
        btns[i].setText(""+(i+1));

        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        ll.addView(btns[i], lp);

        final int j = i;
        btns[j].setOnClickListener(new OnClickListener() {

            public void onClick(View v) 
            {

                new GetContacts().execute();    
                CheckBtnBackGroud(j);
            }


        });
    }

}

 private void CheckBtnBackGroud(int index)
    {
      title.setText("Page "+(index+1)+" of "+noOfBtns);
        for(int i=0;i<noOfBtns;i++)
        {
            if(i==index)
            {
                btns[index].setBackgroundDrawable(getResources().getDrawable(R.drawable.box_green));
                btns[i].setTextColor(getResources().getColor(android.R.color.white));
            }
            else
            {
                btns[i].setBackgroundColor(getResources().getColor(android.R.color.transparent));
                btns[i].setTextColor(getResources().getColor(android.R.color.black));
            }
        }

    }




private class GetContacts extends AsyncTask<Void, Void, Void> {

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

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        // Creating service handler class instance
        ServiceHandler sh = new ServiceHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(gotourl(), ServiceHandler.GET);

        Log.d("Response: ", "> " + jsonStr);

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

                int number = 0;
                int start = number * NUM_ITEMS_PAGE;


                // looping through All Contacts




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

                // looping through All Contacts
                //for (int i = 0; i < contacts.length(); i++) {
                for(int i=start;i<(start)+NUM_ITEMS_PAGE;i++) {


                    Integer a = contacts.length();
                    Log.d("loop", a.toString());
                    JSONObject c = contacts.getJSONObject(i);

                    String id = c.getString("npi");
                    String name = c.getString("first_name");
                    String email = c.getString("last_name");

                    String gender = c.getString("type");


                    // tmp hashmap for single contact
                    HashMap<String, String> contact = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    contact.put("npi", id);
                    contact.put("first_name", name);
                    contact.put("last_name", email);
                    //contact.put(TAG_PHONE_MOBILE, mobile);

                    contact.put("type", gender);
                    // adding contact to contact list
                    contactList.add(contact);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            Log.d("ServiceHandler", "Couldn't get any data from the url");


        }

        return null;
    }



    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();
        /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(
                MainActivity.this, contactList,
                R.layout.list_item, new String[] { "first_name", "last_name",
                        "type" }, new int[] { R.id.name,
                        R.id.email, R.id.mobile });

        setListAdapter(adapter);
    }

}}

Ответы на вопрос(1)

Ваш ответ на вопрос