每次从服务器调用活动时加载数据

时间:2013-06-12 06:08:10

标签: android listview android-activity

当我调用asynctask函数时,数据加载并显示在listview中,但每当我进入此活动时,每次该函数再次执行并加载数据。但我只希望该函数调用一次并显示在listview中。那么解决方案是什么呢。

这是我的全班代码:

public class Feed extends Fragment implements
    PullToRefreshAttacher.OnRefreshListener {

Button btnSlider;
ListView lv;
String userid, success, message, eventType, feed_title, feed_desc,
        timeDate, like, commemt, Feeduserid, photo, posted, hasLike,
        latsId, noMore, feed_id, category_id, feedImg, result;
InputStream is;
ProgressDialog pDialog;
InterNetConnectionDetector isNet = new InterNetConnectionDetector(
        getActivity());
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
FeedAdapter fdp;
HashMap<String, String> map;
private uk.co.senab.actionbarpulltorefresh.library.PullToRefreshAttacher mPullToRefreshAttacher;
int limit = 5;
View v;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    v = inflater.inflate(R.layout.feed, container, false);

    if (android.os.Build.VERSION.SDK_INT > 8) {

        StrictMode.ThreadPolicy stp = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(stp);

    }

    SharedPreferences pref = getActivity().getSharedPreferences("Login",
            Activity.MODE_PRIVATE);
    userid = pref.getString("user_id", "user_id");

    btnSlider = (Button) v.findViewById(R.id.btnSlide);
    lv = (ListView) v.findViewById(R.id.feed_ListView);
    btnSlider.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub

            try {
                Sliding.viewActionsContentView.showActions();
            } catch (Exception e) {
                // TODO: handle exception
            }

        }
    });

    try {
        if (fdp == null) {
            new FeedData().execute();
        } else {
            lv.setAdapter(fdp);
        }

    } catch (Exception e) {
        // TODO: handle exception
    }

    mPullToRefreshAttacher = new uk.co.senab.actionbarpulltorefresh.library.PullToRefreshAttacher(
            getActivity(), lv);

    // Set Listener to know when a refresh should be started
    mPullToRefreshAttacher
            .setRefreshListener((uk.co.senab.actionbarpulltorefresh.library.PullToRefreshAttacher.OnRefreshListener) this);

    ((LoadMore) lv)
            .setOnLoadMoreListener(new com.example.getconnected.LoadImage.LoadMore.OnLoadMoreListener() {
                public void onLoadMore() {
                    // Do the work to load more items at the end of list
                    // here
                    new LoadDataTask().execute();
                }
            });
    return v;
}

/*
 * @Override protected void onCreate(Bundle savedInstanceState) { // TODO
 * Auto-generated method stub super.onCreate(savedInstanceState);
 * setContentView(R.layout.feed);
 * 
 * if (Build.VERSION.SDK_INT >= 8) { getActionBar().hide(); }
 * 
 * if (android.os.Build.VERSION.SDK_INT > 8) {
 * 
 * StrictMode.ThreadPolicy stp = new StrictMode.ThreadPolicy.Builder()
 * .permitAll().build(); StrictMode.setThreadPolicy(stp);
 * 
 * }
 * 
 * try { new FeedData().execute();
 * 
 * } catch (Exception e) { // TODO: handle exception }
 * 
 * SharedPreferences pref = getSharedPreferences("Login",
 * Activity.MODE_PRIVATE); userid = pref.getString("user_id", "user_id");
 * 
 * btnSlider = (Button) findViewById(R.id.btnSlide); lv = (ListView)
 * findViewById(R.id.feed_ListView); btnSlider.setOnClickListener(new
 * OnClickListener() {
 * 
 * @Override public void onClick(View arg0) { // TODO Auto-generated method
 * stub
 * 
 * int width = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP,
 * 40, getResources() .getDisplayMetrics());
 * SlideoutActivity.prepare(getActivity(), R.id.inner_content, width);
 * startActivity(new Intent(getActivity(), MenuActivity.class));
 * getoverridePendingTransition(0, 0);
 * 
 * } });
 * 
 * mPullToRefreshAttacher = new PullToRefreshAttacher(getActivity(), lv);
 * 
 * // Set Listener to know when a refresh should be started
 * mPullToRefreshAttacher .setRefreshListener((OnRefreshListener)
 * getActivity());
 * 
 * ((LoadMore) lv) .setOnLoadMoreListener(new
 * com.example.getconnected.LoadImage.LoadMore.OnLoadMoreListener() { public
 * void onLoadMore() { // Do the work to load more items at the end of list
 * // here new LoadDataTask().execute(); } }); }
 */

public class FeedData extends AsyncTask<String, Integer, String> {

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();

        pDialog = ProgressDialog.show(getActivity(), "", "Loading..");
        pDialog.setCancelable(true);

    }

    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub

        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub

        super.onPostExecute(result);
        // data=jobj.toString();

        try {
            DefaultHttpClient httpclient = new DefaultHttpClient();
            String url = "http://www.sevenstarinfotech.com/projects/demo/GetConnected/api/feed.php?user_id="
                    + userid + "&" + "limit=" + limit;

            HttpPost httppost = new HttpPost(url);
            Log.v("Feed Url:", url);
            httppost.addHeader("Content-Type",
                    "application/x-www-form-urlencoded");
            httppost.addHeader("app-key",
                    "b51bc98b4d6fd0456f7f1b17278415fa49de57d5");

            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

            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();
                Log.v("Response is:", result);
            } catch (Exception e3) {
                Log.e("log_tag", "Error converting result " + e3.toString());
            }

            // parse json data
            try {
                JSONObject ja = new JSONObject(result);
                JSONObject jdata = ja.getJSONObject("data");

                success = jdata.getString("Success");
                message = jdata.getString("Message");
                latsId = jdata.getString("lastId");
                noMore = jdata.getString("nomore");

                JSONArray jArray = jdata.getJSONArray("Feeddetails");
                for (int i = 0; i < jArray.length(); i++) {
                    map = new HashMap<String, String>();
                    JSONObject me = jArray.getJSONObject(i);
                    map.put("sucess", success);
                    map.put("message", message);
                    map.put("latsId", latsId);
                    map.put("noMore", noMore);
                    eventType = me.getString("type");
                    feed_id = me.getString("feed_id");
                    feed_title = me.getString("feed_title");
                    category_id = me.getString("category_id");
                    feed_desc = me.getString("feed_desc");
                    timeDate = me.getString("timeposted");
                    posted = me.getString("postedby");
                    like = me.getString("likes");
                    photo = me.getString("photo");
                    commemt = me.getString("comments");
                    Feeduserid = me.getString("user_id");
                    hasLike = me.getString("hasliked");
                    map.put("eventType", eventType);
                    map.put("feed_id", feed_id);
                    map.put("feed_title", feed_title);
                    map.put("category_id", category_id);
                    map.put("feed_desc", feed_desc);
                    map.put("timeDate", timeDate);
                    map.put("posted", posted);
                    map.put("like", like);
                    map.put("photo", photo);
                    map.put("commemt", commemt);
                    map.put("Feeduserid", Feeduserid);
                    map.put("hasLike", hasLike);
                    Log.v("Data:", feed_id + "/" + "/" + "/" + Feeduserid
                            + "/" + "/" + "/" + like + "/" + "/" + "/"
                            + commemt);

                    contactList.add(map);

                }
                Log.v("Length", contactList.size() + "");

            } catch (Exception e1) {
                Log.e("log_tag",
                        "Error in http connection " + e1.toString());

            }

        } catch (Exception e) {
            // TODO: handle exception
        }
        pDialog.dismiss();
        fdp = new FeedAdapter(getActivity(), contactList);
        lv.setAdapter(fdp);
    }

}

@Override
public void onRefreshStarted(View view) {
    /**
     * Simulate Refresh with 4 seconds sleep
     */
    new AsyncTask<Void, Void, Void>() {

        @Override
        protected Void doInBackground(Void... params) {
            try {
                Thread.sleep(4000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

            // Notify PullToRefreshAttacher that the refresh has finished
            mPullToRefreshAttacher.setRefreshComplete();
        }
    }.execute();
}

private class LoadDataTask extends AsyncTask<String, Integer, String> {

    @Override
    protected String doInBackground(String... params) {

        if (isCancelled()) {
            return null;
        }

        // Simulates a background task
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
        }

        return null;
    }

    @Override
    protected void onPostExecute(String result) {

        try {
            limit += 5;
            DefaultHttpClient httpclient = new DefaultHttpClient();
            String url = "http://www.sevenstarinfotech.com/projects/demo/GetConnected/api/feed.php?user_id="
                    + userid + "&" + "limit=" + limit;

            HttpPost httppost = new HttpPost(url);
            Log.v("Feed Url:", url);
            httppost.addHeader("Content-Type",
                    "application/x-www-form-urlencoded");
            httppost.addHeader("app-key",
                    "b51bc98b4d6fd0456f7f1b17278415fa49de57d5");

            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

            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();
                Log.v("Response is:", result);
            } catch (Exception e3) {
                Log.e("log_tag", "Error converting result " + e3.toString());
            }

            // parse json data
            try {
                JSONObject ja = new JSONObject(result);
                JSONObject jdata = ja.getJSONObject("data");

                success = jdata.getString("Success");
                message = jdata.getString("Message");
                latsId = jdata.getString("lastId");
                noMore = jdata.getString("nomore");

                JSONArray jArray = jdata.getJSONArray("Feeddetails");
                for (int i = 0; i < jArray.length(); i++) {
                    map = new HashMap<String, String>();
                    JSONObject me = jArray.getJSONObject(i);
                    map.put("sucess", success);
                    map.put("message", message);
                    map.put("latsId", latsId);
                    map.put("noMore", noMore);
                    eventType = me.getString("type");
                    feed_id = me.getString("feed_id");
                    feed_title = me.getString("feed_title");
                    category_id = me.getString("category_id");
                    feed_desc = me.getString("feed_desc");
                    timeDate = me.getString("timeposted");
                    posted = me.getString("postedby");
                    like = me.getString("likes");
                    photo = me.getString("photo");
                    commemt = me.getString("comments");
                    Feeduserid = me.getString("user_id");
                    hasLike = me.getString("hasliked");
                    map.put("eventType", eventType);
                    map.put("feed_id", feed_id);
                    map.put("feed_title", feed_title);
                    map.put("category_id", category_id);
                    map.put("feed_desc", feed_desc);
                    map.put("timeDate", timeDate);
                    map.put("posted", posted);
                    map.put("like", like);
                    map.put("photo", photo);
                    map.put("commemt", commemt);
                    map.put("Feeduserid", Feeduserid);
                    map.put("hasLike", hasLike);
                    Log.v("Data:", feed_id + "/" + "/" + "/" + Feeduserid
                            + "/" + "/" + "/" + like + "/" + "/" + "/"
                            + commemt);

                    contactList.add(map);

                }

                pDialog.dismiss();
                fdp = new FeedAdapter(getActivity(), contactList);
                lv.setAdapter(fdp);

            } catch (Exception e1) {
                Log.e("log_tag",
                        "Error in http connection " + e1.toString());

            }

        } catch (Exception e) {
            // TODO: handle exception
        }

        // mListItems.add("Added after load more");

        // We need notify the adapter that the data have been changed
        fdp.notifyDataSetChanged();

        // Call onLoadMoreComplete when the LoadMore task, has finished
        ((LoadMore) lv).onLoadMoreComplete();

        super.onPostExecute(result);
    }

    @Override
    protected void onCancelled() {
        // Notify the loading more operation has finished
        ((LoadMore) lv).onLoadMoreComplete();
    }
}
}

1 个答案:

答案 0 :(得分:0)

更好的选择就是,只需在您的ROOT课程或活动中将 ADAPTER 声明为公共静态。这将使单一副本。你完成了。

假设您有以下结构。

ABC (ROOT/SPLASH) Activity -> class Feed extends Fragment

所以基本上你从 ABC 中调用 Feed 。在 ABC 内,声明为

public class ABC...{
   public static FeedAdapter fdp;
   //.. all other stuffs
}

public class Feed...{
    //.. to use that object delcared in ABC
    ABC.fdp = new FeedAdapter(...);
}