android-amazing-listview,如何通过将数据传递给URL来更新新的页面加载

时间:2014-05-09 04:33:45

标签: android android-listview android-json

在自动加载时,我需要能够从URL加载更多项目。我通过Json获取数据的地方。

在我的API调用类中,我需要添加到此nuber 10中:

pairs.add(new BasicNameValuePair("limit", "10"));

每当列表视图完成加载当前数据时,然后更改上面的值并再次检查。

我虽然需要在PaginationDemoActivity中创建一个方法,它检查是否有更多页面,然后使用intent传递一个新变量来覆盖(" limit"," 10") )在JSONfunctions类

有什么建议吗?谢谢你们

JSONfunctions

public class JSONfunctions extends Activity{

    public static JSONObject getJSONfromURL(String url) {
        InputStream is = null;
        String result = "";
        JSONObject jArray = null;



        // Download JSON data from URL
        try { 
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);

            //Add URL Encoding by sending post data
            List<NameValuePair> pairs = new ArrayList<NameValuePair>();  
                pairs.add(new BasicNameValuePair("c","getlist"));  
                pairs.add(new BasicNameValuePair("page","1"));
                pairs.add(new BasicNameValuePair("limit", "10"));

            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs,HTTP.UTF_8);
            httppost.setEntity(entity); 
            // end Add URL Encoding by sending post data



            HttpResponse httpResponse = httpclient.execute(httppost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

            //end test 
            /*
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
*/
        } catch (Exception e) {
            Log.e("log_tag", "Error in http connection " + e.toString());
        }

        // Convert response to string
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            result = sb.toString();
        } catch (Exception e) {
            Log.e("log_tag", "Error converting result " + e.toString());
        }

        try {

            jArray = new JSONObject(result);
        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());
        }

        return jArray;
    }
}

数据

public class Data {

    static String URL = " my api url";

    static String itemsPerPage = "20";

    public static final String TAG = Data.class.getSimpleName();

    public static List<Pair<String, List<Composer>>> getAllData() {
        List<Pair<String, List<Composer>>> res = new ArrayList<Pair<String, List<Composer>>>();

        for (int i = 0; i < 4; i++) {
            res.add(getOneSection(i));
        }

        return res;
    }

    public static List<Composer> getFlattenedData() {
        List<HashMap<String, String>> arraylist;

        JSONObject jsonobject;
        JSONArray jsonarray;


         List<Composer> res = new ArrayList<Composer>();

         //Pair<String, List<Composer>> mydata;

         arraylist = new ArrayList<HashMap<String, String>>();
            // Retrieve JSON Objects from the given URL address
            jsonobject = JSONfunctions.getJSONfromURL(URL);

            Log.e("check", jsonobject.toString());

            try {
                // Locate the array name in JSON
                jsonarray = jsonobject.getJSONArray("data");

                for (int i = 0; i < jsonarray.length(); i++) {
                    HashMap<String, String> map = new HashMap<String, String>();
                    jsonobject = jsonarray.getJSONObject(i);
                    // Retrive JSON Objects
                    map.put("id", jsonobject.getString("id"));
                    map.put("title", jsonobject.getString("title"));
                    map.put("s_desc", jsonobject.getString("s_desc"));
                    map.put("img", jsonobject.getString("img"));
                    // Set the JSON Objects into the array
                    arraylist.add(map);

                    Composer s = new Composer(
                            jsonobject.getString("title"), 
                            jsonobject.getString("s_desc"), 
                            jsonobject.getString("id"), 
                            jsonobject.getString("img"));

                    res.add(s);
                }
            } catch (JSONException e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }

         return res;
    }

    protected void updateUrlItems()
    {


    }

    public static Pair<Boolean, List<Composer>> getRows(int page) {
        List<Composer> flattenedData = getFlattenedData();
        if (page == 1) {
            return new Pair<Boolean, List<Composer>>(true, flattenedData.subList(0, 5));
        } else {
            SystemClock.sleep(2000); // simulate loading
            return new Pair<Boolean, List<Composer>>(page * 5 < flattenedData.size(), 
                    flattenedData.subList((page - 1) * 5, Math.min(page * 5, flattenedData.size())));
        }
    }

    public static Pair<String, List<Composer>> getOneSection(int index) {
        String[] titles = {"", "", "", ""};
        Composer[][] composerss = {
            {
                new Composer("", "", "", ""),

            },

        };
        return new Pair<String, List<Composer>>(titles[index], Arrays.asList(composerss[index]));
    }
}

PaginationDemoActivity

public class PaginationDemoActivity extends Activity {
    AmazingListView lsComposer;
    PaginationComposerAdapter adapter;
    ImageLoader imageLoader;

    // Flag for current page
    static Integer current_page = 10;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pagination_demo);
        imageLoader = new ImageLoader(this);

        lsComposer = (AmazingListView) findViewById(R.id.lsComposer);
        lsComposer.setLoadingView(getLayoutInflater().inflate(R.layout.loading_view, null));
        lsComposer.setAdapter(adapter = new PaginationComposerAdapter());



        adapter.notifyMayHaveMorePages();

    }





    public void bRefresh_click(View v) {
        adapter.reset();
        adapter.resetPage();
        adapter.notifyMayHaveMorePages();
    }

    class PaginationComposerAdapter extends AmazingAdapter {


        List<Composer> list = Data.getRows(1).second;


        private AsyncTask<Integer, Void, Pair<Boolean, List<Composer>>> backgroundTask;

        public void reset() {
            if (backgroundTask != null) backgroundTask.cancel(false);

            list = Data.getRows(1).second;

            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Composer getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }


        @Override
        protected void onNextPageRequested(int page) {
            Log.d(TAG, "Got onNextPageRequested page=" + page);

            if (backgroundTask != null) {
                backgroundTask.cancel(false);
            }



            backgroundTask = new AsyncTask<Integer, Void, Pair<Boolean, List<Composer>>>() {
                @Override
                protected Pair<Boolean, List<Composer>> doInBackground(Integer... params) {
                    int page = params[0];

                    Log.e("more page", "page: " + page);

                    return Data.getRows(page);  
                }

                @Override
                protected void onPostExecute(Pair<Boolean, List<Composer>> result) {
                    if (isCancelled()) return; 

                    Log.e("onPostExecute", "result: " + result.first);
                    list.addAll(result.second);
                    nextPage();
                    notifyDataSetChanged();



                    if (result.first) {
                        // still have more pages
                        notifyMayHaveMorePages();
                    } else {
                        notifyNoMorePages();
                    }
                };
            }.execute(page);
        }

        @Override
        protected void bindSectionHeader(View view, int position, boolean displaySectionHeader) {
        }

        @Override
        public View getAmazingView(int position, View convertView, ViewGroup parent) {
            View res = convertView;

            if (res == null) res = getLayoutInflater().inflate(R.layout.item_composer, null);

            // we don't have headers, so hide it
            res.findViewById(R.id.header).setVisibility(View.GONE);

            TextView lName = (TextView) res.findViewById(R.id.lName);
            TextView lYear = (TextView) res.findViewById(R.id.lYear);
            TextView lId = (TextView) res.findViewById(R.id.lId);
            // Locate the ImageView in listview_item.xml
            ImageView lImg = (ImageView) res.findViewById(R.id.lImg);

            Composer composer = getItem(position);
            lName.setText(composer.name);
            lYear.setText(composer.year);
            lId.setText(composer.id);

            Log.e("getAmazingView PRINT THE URL 1111111111", "URL: " + composer.img);
            // Capture position and set results to the ImageView
            // Passes img images URL into ImageLoader.class
            imageLoader.DisplayImage(composer.img, lImg);
            Log.e("222","333");



            //khen
            lsComposer.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                 // TODO Auto-generated method stub
                             if(id > -1){
                  Composer composer = adapter.getItem(position);

                  Intent intent = new Intent();
                  intent.setClass(getApplicationContext(), SingleItemView.class);

                        Bundle bundle = new Bundle();
                        bundle.putString("id", composer.id);
                        bundle.putString("name", composer.name);
                        bundle.putString("year", composer.year);
                        bundle.putString("img", composer.img); 

                        intent.putExtras(bundle);
                        startActivity(intent); 
                   }
                 }
               });
            //end khen 


            return res;

        }




        @Override
        public void configurePinnedHeader(View header, int position, int alpha) {
        }

        @Override
        public int getPositionForSection(int section) {
            return 0;
        }

        @Override
        public int getSectionForPosition(int position) {
            return 0;
        }

        @Override
        public Object[] getSections() {
            return null;
        }

    }
}

0 个答案:

没有答案