你的位置:首页 > 操作系统

[操作系统]会话失效和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();  }}

View Code

下面是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;  }}