会话失效和PullToRefreshListView

今天碰到一个一个会话失效的问题,从网上找了个方法可以处理http://blog.csdn.net/aa7704/article/details/50611588#comments

还有list的下拉刷新和上拉加载的完成程序的例子

如下是代码

先看下登录保存定义保存的Cookie

package com.examle.hello.util;

import com.lidroid.xutils.util.PreferencesCookieStore;

import android.app.Application;

public class MyApplication extends Application {
    /**
     * 用PreferencesVookisStore持久化cookie到本地
     */
    public static PreferencesCookieStore presCookieStore;
    public static String jsesionid = "";// 保存sessionid

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        presCookieStore = new PreferencesCookieStore(getApplicationContext());
    }
}

package com.examle.hello.text;

import java.util.List;

import org.apache.http.client.CookieStore;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import com.examle.hello.util.MyApplication;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

/**
 * 用户的登录界面
 * @author zh
 *
 */
public class MainActivity extends Activity implements OnClickListener {

    private Button btn_login;
    private EditText userName;
    private EditText pwd;
    private String userNameString;
    private String pwdString;
    private ProgressDialog pDialog;

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

    private void initData() {
        // TODO Auto-generated method stub
        SharedPreferences sPreferences = getSharedPreferences("info",
                MODE_PRIVATE);
        this.userName.setText(sPreferences.getString("name", ""));
        this.pwd.setText(sPreferences.getString("password", ""));
    }

    private void initView() {
        // TODO Auto-generated method stub
        userName = (EditText) findViewById(R.id.userNameEdit);
        pwd = (EditText) findViewById(R.id.pwdEdit);
        btn_login = (Button) findViewById(R.id.loginBtn);
        btn_login.setOnClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub
        switch (arg0.getId()) {
        // login
        case R.id.loginBtn:
            userNameString = userName.getText().toString().trim();
            pwdString = pwd.getText().toString().trim();
            if (TextUtils.isEmpty(userNameString)
                    || TextUtils.isEmpty(pwdString)) {
                Toast.makeText(MainActivity.this, "用户名或密码不能为空",
                        Toast.LENGTH_SHORT).show();
                return;
            }
            Login();
            break;

        default:
            break;
        }
    }

    /**
     * 登录
     */
    private void Login() {
        // TODO Auto-generated method stub
        String urlString = "http://111.39.245.157:9527/cmppbs/appLogin.action";
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("正在登录...");
        pDialog.show();
        final HttpUtils utils = new HttpUtils();
        utils.configCurrentHttpCacheExpiry(100);
        RequestParams requestParams = new RequestParams();
        requestParams.addBodyParameter("user_name", userNameString);
        requestParams.addBodyParameter("pwd", pwdString);
        utils.send(HttpMethod.POST, urlString, requestParams,
                new RequestCallBack<String>() {

                    @Override
                    public void onFailure(HttpException arg0, String arg1) {
                        // TODO Auto-generated method stub
                        pDialog.dismiss();
                        Toast.makeText(MainActivity.this, "登录失败",
                                Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> arg0) {
                        // TODO Auto-generated method stub
                        pDialog.dismiss();
                        Log.d("jiejie", arg0.result);
                        if (arg0.result != null) {
                            try {
                                JSONObject object = new JSONObject(arg0.result);
                                int flg = object.getInt("flg");
                                String msg = object.getString("msg");
                                // 登录成功
                                if (flg == 0) {
                                    keepLogin();

                                    Toast.makeText(MainActivity.this, msg,
                                            Toast.LENGTH_SHORT).show();
                                    startActivity(new Intent(MainActivity.this,
                                            MainHome.class));
                                    finish();
                                    /**
                                     * 得到cookie seesionid 并持久化到本地的核心代码
                                     */
                                    DefaultHttpClient defaultHttpClient = (DefaultHttpClient) utils
                                            .getHttpClient();
                                    CookieStore cookieStore = defaultHttpClient
                                            .getCookieStore();
                                    List<Cookie> cookies = cookieStore
                                            .getCookies();
                                    for (Cookie cookie : cookies) {
                                        if ("JSESSIONID".equals(cookie
                                                .getName())) {
                                            MyApplication.jsesionid = cookie
                                                    .getValue();// 得到sessionid
                                        }
                                        MyApplication.presCookieStore
                                                .addCookie(cookie);// 将cookie保存在本地
                                    }

                                } else {
                                    Toast.makeText(MainActivity.this, msg,
                                            Toast.LENGTH_SHORT).show();
                                }
                            } catch (Exception e) {
                                // TODO: handle exception
                            }
                        }

                    }
                });
    }

    /**
     * 保存用户的密码和账号 以便下次登录可以直接使用 采用 SharedPreferences来存储
     */
    private void keepLogin() {
        SharedPreferences sPreferences = getSharedPreferences("info",
                MODE_PRIVATE);
        SharedPreferences.Editor editor = sPreferences.edit();
        editor.putString("name", userNameString);
        editor.putString("password", pwdString);
        editor.commit();
    }

}

下面是PullToRefreshListView的使用  代码在适配器 getview的方法重复调用了多次我没有想到处理的方法

package com.examle.hello.text;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

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

import com.examle.hello.adapter.ReceiveListAdapter;
import com.examle.hello.util.MyApplication;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

/**
 * 短信接收的界面
 * @author zh
 *
 */
public class MainReceiveFragment extends Fragment {
    private PullToRefreshListView listView;
    private ReceiveListAdapter adpter;
    private int j ;
    private List<JSONObject> dataList = new ArrayList<JSONObject>();
    private String urlString = "http://111.39.245.157:9527/cmppbs/getCmpp30DeliverList.action";
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        return inflater.inflate(R.layout.receivefragment, null, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);
        initView();

    }

    private void initView() {
        // TODO Auto-generated method stub
        listView =(PullToRefreshListView) getActivity().findViewById(R.id.expand_list);        

        listView.setMode(Mode.BOTH);
        setHttp();
        OnRefreshListener2<ListView> mListener2 = new OnRefreshListener2<ListView>() {

            @Override
            public void onPullDownToRefresh(
                    PullToRefreshBase<ListView> refreshView) {
                // TODO Auto-generated method stub
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                String date = simpleDateFormat.format(new Date());
                refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(date);
                new UpFresh().execute();
            }

            @Override
            public void onPullUpToRefresh(
                    PullToRefreshBase<ListView> refreshView) {
                // TODO Auto-generated method stub
                new MyTask().execute();
            }
        };
        listView.setOnRefreshListener(mListener2);
        j=2;
    }

    /**
     * 进行网络的请求默认加载第一页
     */
    private void setHttp(){
         HttpUtils httpUtils = new HttpUtils();
        RequestParams requestParams = new RequestParams();
        httpUtils.configCurrentHttpCacheExpiry(100);
        httpUtils.configCookieStore(MyApplication.presCookieStore);
        requestParams.addBodyParameter("page", "1");
        requestParams.addBodyParameter("rows", "3");
        requestParams.addBodyParameter("order", "desc");
        httpUtils.send(HttpMethod.POST, urlString, requestParams, new RequestCallBack<String>() {

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                // TODO Auto-generated method stub
                Log.d("jiejie", arg0.result);
                if(arg0.result !=null){
                    try {
                        JSONObject object=new JSONObject(arg0.result);
                        JSONArray array = object.getJSONArray("rows");
                        for (int i = 0; i < array.length(); i++) {
                            JSONObject dataJsonObject =array.getJSONObject(i);
                            dataList.add(dataJsonObject);
                        }
                        ListView listView2 = listView.getRefreshableView();
                        adpter = new ReceiveListAdapter(getActivity(),dataList);
                        listView2.setAdapter(adpter);
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }

        });
    }
    /**
     * 上拉加载
     * @author zh
     *
     */
    class MyTask extends AsyncTask<Void, Void, String[]>{

        @Override
        protected String[] doInBackground(Void... arg0) {
            // TODO Auto-generated method stub
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return null;
        }
        @Override
        protected void onPostExecute(String[] result) {
            // TODO Auto-generated method stub
            RequestParams requestParams = new RequestParams();
            requestParams.addBodyParameter("page", j+"");
            requestParams.addBodyParameter("rows", "3");
            requestParams.addBodyParameter("order", "desc");
            HttpUtils httpUtils = new HttpUtils();
            httpUtils.configCurrentHttpCacheExpiry(100);
            httpUtils.configCookieStore(MyApplication.presCookieStore);
            httpUtils.send(HttpMethod.POST, urlString, requestParams, new RequestCallBack<String>() {

                @Override
                public void onFailure(HttpException arg0, String arg1) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onSuccess(ResponseInfo<String> arg0) {
                    // TODO Auto-generated method stub
                    Log.d("jiejie", arg0.result);
                    if(arg0.result!=null){
                        try {
                            JSONObject object=new JSONObject(arg0.result);
                            JSONArray list=object.getJSONArray("rows");
                            JSONObject data;
                            for (int i = 0; i < list.length(); i++) {
                                data = list.getJSONObject(i);
                                dataList.add(data);
                                /*Toast.makeText(getActivity(), dataList.get(0).toString(), Toast.LENGTH_LONG).show();*/
                            }
                            adpter.notifyDataSetChanged();
                            listView.onRefreshComplete();
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
            });
            super.onPostExecute(result);
            j++;
        }
    }

    class UpFresh extends AsyncTask<Void, Void, String[]>{

        @Override
        protected String[] doInBackground(Void... arg0) {
            // TODO Auto-generated method stub
            return null;
        }
        @Override
        protected void onPostExecute(String[] result) {
            // TODO Auto-generated method stub
            String url3="http://111.39.245.157:9527/cmppbs/getCmpp30DeliverList.action";
            RequestParams requestParams = new RequestParams();
            requestParams.addBodyParameter("page", "1");
            requestParams.addBodyParameter("rows", "3");
            requestParams.addBodyParameter("order", "desc");
            HttpUtils httpUtilss = new HttpUtils();
            httpUtilss.configCurrentHttpCacheExpiry(100);
            httpUtilss.configCookieStore(MyApplication.presCookieStore);
            httpUtilss.send(HttpMethod.POST, url3, requestParams, new RequestCallBack<String>() {

                @Override
                public void onFailure(HttpException arg0, String arg1) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onSuccess(ResponseInfo<String> arg0) {
                    // TODO Auto-generated method stub
                    dataList.clear();
                    if(arg0.result !=null){
                        try {
                            JSONObject object = new JSONObject(arg0.result);
                            JSONArray list = object.getJSONArray("rows");
                            JSONObject data;
                            for(int i =0;i<list.length();i++){
                                data = list.getJSONObject(i);
                                dataList.add(data);
                            }
                            adpter.notifyDataSetChanged();
                            listView.onRefreshComplete();
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
            });
            super.onPostExecute(result);
        }
    }

}
package com.examle.hello.adapter;

import java.util.List;

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

import com.examle.hello.text.R;

import android.content.Context;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

/**
 * 短信接收的适配器
 * @author zh
 *
 */
public class ReceiveListAdapter extends BaseAdapter {
    private Context context;
    private List<JSONObject> dataList;

    public ReceiveListAdapter(Context context, List<JSONObject> dataList) {
        this.context = context;
        this.dataList = dataList;
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return dataList.size();
    }

    @Override
    public Object getItem(int arg0) {
        // TODO Auto-generated method stub
        return arg0;
    }

    @Override
    public long getItemId(int arg0) {
        // TODO Auto-generated method stub
        return arg0;
    }

    @Override
    public View getView(int arg0, View arg1, ViewGroup arg2) {
        // TODO Auto-generated method stub
        ViewHolder holder = null;
        if(arg1 == null){
            holder = new ViewHolder();
            arg1 = View.inflate(context, R.layout.notereceive, null);
            holder.tv_item_r_yewu=(TextView)arg1.findViewById(R.id.item_r_yewu);
            holder.tv_item_r_phone=(TextView)arg1.findViewById(R.id.item_r_phone);
            holder.tv_item_r_content=(TextView)arg1.findViewById(R.id.item_r_content);
            holder.tv_item_r_time=(TextView)arg1.findViewById(R.id.item_r_time);
            arg1.setTag(holder);
        }else {
            holder = (ViewHolder) arg1.getTag();
        }
        try {
            Log.d("jiejie", "数据"+dataList);
            holder.tv_item_r_content.setText(dataList.get(arg0).getString("msgContent"));
            holder.tv_item_r_phone.setText(dataList.get(arg0).getString("srcTerminalId"));
            holder.tv_item_r_time.setText(dataList.get(arg0).getString("moDate"));
            holder.tv_item_r_yewu.setText(dataList.get(arg0).getString("tpPid"));
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return arg1;
    }
    static class ViewHolder{
        TextView tv_item_r_yewu;
        TextView tv_item_r_phone;
        TextView tv_item_r_content;
        TextView tv_item_r_time;
    }
}
时间: 2024-10-20 01:17:26

会话失效和PullToRefreshListView的相关文章

【分布式】Zookeeper会话

一.前言 前面分析了Zookeeper客户端的细节,接着继续学习Zookeeper中的一个非常重要的概念:会话. 二.会话 客户端与服务端之间任何交互操作都与会话息息相关,如临时节点的生命周期.客户端请求的顺序执行.Watcher通知机制等.Zookeeper的连接与会话就是客户端通过实例化Zookeeper对象来实现客户端与服务端创建并保持TCP连接的过程. 2.1 会话状态 在Zookeeper客户端与服务端成功完成连接创建后,就创建了一个会话,Zookeeper会话在整个运行期间的生命周期

集群增量会话管理器——DeltaManager

DeltaManager会话管理器是tomcat默认的集群会话管理器,它主要用于集群中各个节点之间会话状态的同步维护,由于相关内容涉及到集群,可能会需要一些集群通信相关知识,如果有疑问可结合集群相关章节. 集群增量会话管理器的职责是将某节点的会话该变同步到集群内其他成员节点上,它属于全节点复制模式,所谓全节点复制是指集群中某个节点的状态变化后需要同步到集群中剩余的节点,非全节点方式可能只是同步到其中某个或若干节点.在集群中全节点会话复制的一个大致步骤如下图所示,客户端发起一个请求,假设通过一定的

ZooKeeper的“会话终止”是这么出现的

转载请注明出处: jiq?钦's technical Blog 经过我的测试,得出关于会话终止的下列结论: 客户端创建ZooKeeper实例连接到ZooKeeper服务端,设置会话超时时间为10s. (1)若强制关闭ZooKeeper服务端(模拟其崩溃),客户端立马收到Disconnected连接断开事件,等待半个小时,再次启动ZooKeeper服务端,客户端收到SyncConnected连接建立事件,在这之前注册的watcher仍然有效,推测临时节点也一样有效. (2)若断开客户端与服务端的网

使用Spring Session做分布式会话管理

在Web项目开发中,会话管理是一个很重要的部分,用于存储与用户相关的数据.通常是由符合session规范的容器来负责存储管理,也就是一旦容器关闭,重启会导致会话失效.因此打造一个高可用性的系统,必须将session管理从容器中独立出来.而这实现方案有很多种,下面简单介绍下: 第一种是使用容器扩展来实现,大家比较容易接受的是通过容器插件来实现,比如基于Tomcat的tomcat-redis-session-manager,基于Jetty的jetty-session-redis等等.好处是对项目来说

ZooKeeper 会话超时

1.会话概述 在ZooKeeper中,客户端和服务端建立连接后,会话随之建立,生成一个全局唯一的会话ID(Session ID).服务器和客户端之间维持的是一个长连接,在SESSION_TIMEOUT时间内,服务器会确定客户端是否正常连接(客户端会定时向服务器发送heart_beat,服务器重置下次SESSION_TIMEOUT时间).因此,在正常情况下,Session一直有效,并且ZK集群所有机器上都保存这个Session信息.在出现网络或其它问题情况下(例如客户端所连接的那台ZK机器挂了,或

【转】ZooKeeper 会话超时

原文链接 http://www.chepoo.com/zookeeper-session-timeout.html 1.会话概述 在ZooKeeper中,客户端和服务端建立连接后,会话随之建立,生成一个全局唯一的会话ID(Session ID). 服务器和客户端之间维持的是一个长连接,在SESSION_TIMEOUT时间内,服务器会确定客户端是否 正常连接(客户端会定时向服务器发送heart_beat,服务器重置下次SESSION_TIMEOUT时间). 因此,在正常情况下,Session一直有

会话跟踪技术——Session

一.什么是Session Session从用户访问页面开始,到断开与网站连接为止,形成一个会话的生命周期.在会话期间,分配客户唯一的一个SessionID,用来标识当前用户,与其他用户进行区分. Session会话时,SessionID会分别保存在客户端和服务器端两个位置,对于客户端使用临时的Cookie保存(Cookie名称为PHPSESSID)或者通过URL字符串传递,服务器端也以文本文件形式保存在指定的Session目录中. Session通过ID接受每一个访问请求,从而识别当前用户.跟踪

Django 1.10 中文文档------3.3.8 会话sessions

django支持匿名会话.它将数据存放在服务器端,并抽象cookies的发送和接收过程.cookie包含一个会话ID而不是数据本身(除非你使用的是基于后端的cookie). 3.3.8.1 启用会话 Django通过一个中间件来实现会话功能.要启用会话就要先启用该中间件.编辑MIDDLEWARE设置,确保存在django.contrib.sessions.middleware.SessionMiddleware这一行.默认情况在新建的项目中它是存在的. 如果你不想使用会话功能,那么在settin

4.会话管理(Session)

1.会话管理的概念和基本原理: 会话管理概念: 会话的实现过程: 2.使用Cookie.隐藏域.URL重写实现会话管理 创建并向客户端发送Cookie; 从客户端读取Cookies Cookie的方法: Cookie的优缺点: 使用隐藏的表单域: 使用URL重写: Session会话管理的原理和技术实现: 使用Session对象: 会话失效: Session 与URL重写 Session的方法: 原文地址:https://www.cnblogs.com/Firesun/p/9655479.htm