登录+注册+搜索+切换页面+数据库清空历史记录

登录包层

M层

package com.example.ruiyonghui.usercenter.DL.M;

import android.util.Log;

import com.example.ruiyonghui.usercenter.DL.P.PJieKou;
import com.example.ruiyonghui.usercenter.Untils.DL;
import com.example.ruiyonghui.usercenter.Untils.OkHttp3Util;
import com.google.gson.Gson;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * Created by ruiyonghui on 2018/1/6.
 */

public class IMoudle
{
    public void DengLu(String user, String mima, final PJieKou pJieKou)
    {
        OkHttp3Util.doGet("http://120.27.23.105/user/login?mobile=" + user + "&password=" + mima, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                      if (response.isSuccessful())
                      {
                          String string = response.body().string();
                          Log.i("TAG0000", "登录请求下来的数据: "+string);
                          Gson gson=new Gson();
                          DL dl = gson.fromJson(string, DL.class);
                          pJieKou.OnSuccess(dl);
                      }
            }
        });
    }

}


P层
package com.example.ruiyonghui.usercenter.DL.P;

import com.example.ruiyonghui.usercenter.DL.M.IMoudle;
import com.example.ruiyonghui.usercenter.DL.V.ILoginView;
import com.example.ruiyonghui.usercenter.Untils.DL;

/**
 * Created by ruiyonghui on 2018/1/6.
 */

public class IPresenter implements PJieKou
{

    ILoginView iLongView;
    IMoudle iMoudle;
    public IPresenter(ILoginView iLongView)
    {
         this.iLongView=iLongView;
         iMoudle=new IMoudle();
    }

    @Override
    public void OnSuccess( final DL dl)
    {
        iLongView.OnSuccess(dl);
    }

    public void Denglu(String user, String pass)
    {
           iMoudle.DengLu(user,pass,this);
    }
}
P层接口

package com.example.ruiyonghui.usercenter.DL.P;

import com.example.ruiyonghui.usercenter.Untils.DL;

/**
 * Created by ruiyonghui on 2018/1/6.
 */

public interface PJieKou
{
    void OnSuccess(DL dl);
}
V层 Activity
package com.example.ruiyonghui.usercenter.DL.V;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import com.example.ruiyonghui.usercenter.DL.P.IPresenter;
import com.example.ruiyonghui.usercenter.R;
import com.example.ruiyonghui.usercenter.Untils.DL;
import com.example.ruiyonghui.usercenter.Xinxi.V.XinxiActivity;
import com.example.ruiyonghui.usercenter.Zhuce.V.ZhuceActivity;

public class MainActivity extends AppCompatActivity implements ILoginView
{

    EditText et_name,et_pass;
    IPresenter iPresenter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et_name= (EditText) findViewById(R.id.et_name);
        et_pass= (EditText) findViewById(R.id.et_pass);
        iPresenter=new IPresenter(this);
    }

    public void Login(View view)
    {
        iPresenter.Denglu(et_name.getText().toString(),et_pass.getText().toString());
    }

    public void zc(View view)
    {
        Intent intent=new Intent(this, ZhuceActivity.class);
        startActivity(intent);
    }

    @Override
    public void OnSuccess(final DL dl)
    {
         runOnUiThread(new Runnable() {
             @Override
             public void run() {
                 DL.DataBean data=dl.getData();
                 Intent intent = new Intent(MainActivity.this, XinxiActivity.class);
                 Log.i("TAUDAD", "run: "+data.getUid());
                 intent.putExtra("uid",data.getUid()+"");
                 startActivity(intent);
                 finish();
                 Log.i("TAG", "登录V层接口穿回来的数据"+data.toString());

             }
         });
    }
}
V层的接口继承ILoginView
package com.example.ruiyonghui.usercenter.DL.V;
import com.example.ruiyonghui.usercenter.Untils.DL;
/**
 * Created by ruiyonghui on 2018/1/6.
 */public interface ILoginView
{
    void OnSuccess(DL dl);
}


注册
M层Moudle
package com.example.ruiyonghui.usercenter.Zhuce.M;

import com.example.ruiyonghui.usercenter.Untils.OkHttp3Util;
import com.example.ruiyonghui.usercenter.Zhuce.P.Onfinish;

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

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * Created by ruiyonghui on 2018/1/6.
 */

public class Moudle
{

    public void  Netinfo(String user, final String mima, final Onfinish onfinish)
     {
         OkHttp3Util.doGet("http://120.27.23.105/user/reg?mobile=" + user + "&password=" + mima, new Callback() {
             @Override
             public void onFailure(Call call, IOException e) {

             }

             @Override
             public void onResponse(Call call, Response response) throws IOException {
                  if (response.isSuccessful())
                  {
                      String  string = response.body().string();
                      try {
                          JSONObject jsonObject=new JSONObject(string);
                          String  msg=jsonObject.getString("msg");
                          if ("注册成功".equals(msg))
                          {
                              onfinish.OnSuccess(msg);
                          }
                      } catch (JSONException e)
                      {
                          e.printStackTrace();
                      }

                  }
             }
         });
     }

}

P层数据
package com.example.ruiyonghui.usercenter.Zhuce.P;

import com.example.ruiyonghui.usercenter.Zhuce.M.Moudle;
import com.example.ruiyonghui.usercenter.Zhuce.V.ZhuCeinView;

/**
 * Created by ruiyonghui on 2018/1/6.
 */

public class Presenter implements Onfinish
{
    ZhuCeinView zhuCeinView;
    Moudle moudle;

    public Presenter(ZhuCeinView zhuCeinView)
    {
        this.zhuCeinView = zhuCeinView;
        moudle = new Moudle();
    }
    public void InfoNet(String user,String pass)
    {
          moudle.Netinfo(user,pass,this);
    }
    @Override
    public void OnSuccess(String msg) {
            zhuCeinView.OnSuccess(msg);
    }
}
P层接口
package com.example.ruiyonghui.usercenter.Zhuce.P;

/**
 * Created by ruiyonghui on 2018/1/6.
 */

public interface Onfinish
{
    void OnSuccess(String msg);
}
V层里面写Activity

package com.example.ruiyonghui.usercenter.Zhuce.V;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import com.example.ruiyonghui.usercenter.R;
import com.example.ruiyonghui.usercenter.Zhuce.P.Presenter;

public class ZhuceActivity extends AppCompatActivity  implements ZhuCeinView{

    EditText et_user,et_mima;
    private Presenter presenter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_zhuce);
        et_mima= (EditText) findViewById(R.id.et_mima);
        et_user= (EditText) findViewById(R.id.et_user);
        presenter = new Presenter(this);
    }

    public void zhuce(View view)
    {
        presenter.InfoNet(et_user.getText().toString(),et_mima.getText().toString());
        finish();
    }
    public void OnSuccess(String msg)
    {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Log.i("TAG", "注册成功");
                finish();
            }
        });
    }
}

V层接口
package com.example.ruiyonghui.usercenter.Zhuce.V;

/**
 * Created by ruiyonghui on 2018/1/6.
 */

public interface ZhuCeinView
{
    void OnSuccess(String msg);
}
第三个页面随便起个包名
V层里面写这些
public class XinxiActivity extends AppCompatActivity {
    EditText et;
    private Dao dao;
    ListView lv;
    private XinxiAdapter myada;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_xinxi);
        et= (EditText) findViewById(R.id.et);
        lv= (ListView) findViewById(R.id.lv);
        et.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(XinxiActivity.this, Show.class);
                startActivityForResult(intent,2);
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

            dao = new Dao(this);
        List<String> sel = dao.sel();
        myada = new XinxiAdapter(this,sel );
            lv.setAdapter(myada);


    }
    public void clean(View view){
        dao.del();
        myada.notifyDataSetChanged();
    }
}
第三个页面的适配器
package com.example.ruiyonghui.usercenter.Untils;

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

import com.example.ruiyonghui.usercenter.R;

import java.util.List;

/**
 * Created by ruiyonghui on 2018/1/6.
 */

public class XinxiAdapter extends BaseAdapter
{

    Context context;
    List<String> sel;
    public XinxiAdapter(Context context, List<String> sel) {
        this.context = context;
        this.sel = sel;
    }

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

    @Override
    public Object getItem(int position) {
        return null;
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        viehwodler vh;
        if(convertView==null){
            convertView=View.inflate(context, R.layout.list,null);
            vh=new viehwodler();
            vh.tv=convertView.findViewById(R.id.list_tv);
            convertView.setTag(vh);
        }else {
            vh= (viehwodler) convertView.getTag();
        }
        vh.tv.setText(sel.get(position));
        return convertView;
    }
    class viehwodler {
        TextView tv;
    }
}



自定义控件流逝布局
package com.example.ruiyonghui.usercenter.Xinxi;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

/**
 * Created by ruiyonghui on 2018/1/6.
 */

public class Zingdiying extends ViewGroup {
    public Zingdiying(Context context) {
        this(context,null);
    }

    public Zingdiying(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public Zingdiying(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int wid=0;
        int hei=0;

        int childCount = getChildCount();
        for (int i=0;i<childCount;i++){
            View childAt = getChildAt(i);

            int measuredHeight = childAt.getMeasuredHeight();
            int measuredWidth = childAt.getMeasuredWidth();

            childAt.layout(wid,hei,wid+measuredWidth,hei+measuredHeight);

            wid=wid+measuredWidth+20;
            hei=hei+measuredHeight-measuredHeight;
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        measureChildren(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
    }
}

工具类
数据库增删改查
package com.example.ruiyonghui.usercenter.Untils;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.List;

/**
 * 插入数据的操作
 * Created by Administrator on 2018\1\6 0006.
 */

public class Dao {
    private MyHolper holper;
    private SQLiteDatabase db;
    private SQLiteDatabase d;

    public Dao(Context context){
        holper = new MyHolper(context);
    }

    /**
     * 插入数据的操作
     */
    public int insertJson(String json){

        SQLiteDatabase database = holper.getWritableDatabase();
        //再去添加
        ContentValues values = new ContentValues();
        values.put("json",json);
        database.insert("shuju1",null,values);
        //关闭
        database.close();
        return 1;
    }

    public List<String> sel(){
        d = holper.getReadableDatabase();

        List<String> list=new ArrayList<>();
        Cursor cursor = d.rawQuery("select * from shuju1", null);

        while (cursor.moveToNext()){
            String s = cursor.getString(1);
            list.add(s);
        }
        return list;
    }

    /**
     * 删除数据
     */
    public void del(){

       db = holper.getWritableDatabase();
        db.execSQL("delete from shuju1");
    }

    public int delyi(String i){
        db = holper.getWritableDatabase();
        db.execSQL("delete from shuju1 where json=?",new String[]{i});
        return 1;
    }
}
创建DL(解析数据)

//数据库创建表
package com.example.ruiyonghui.usercenter.Untils;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * 数据库
 * Created by Administrator on 2018\1\6 0006.
 */

public class MyHolper extends SQLiteOpenHelper{
    public MyHolper(Context context) {
        super(context, "sss.db", null, 2);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        //创建表
        db.execSQL("create table shuju1(id integer primary key autoincrement, json text not null)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int i, int i1) {

    }
}
Ok工具类

package com.example.ruiyonghui.usercenter.Untils;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Dash on 2017/12/8.
 */
public class OkHttp3Util {

    /**
     * 懒汉 安全 加同步
     * 私有的静态成员变量 只声明不创建
     * 私有的构造方法
     * 提供返回实例的静态方法
     */
    private static OkHttpClient okHttpClient = null;


    private OkHttp3Util() {
    }

    public static OkHttpClient getInstance() {
        if (okHttpClient == null) {
            //加同步安全
            synchronized (OkHttp3Util.class) {
                if (okHttpClient == null) {
                    //okhttp可以缓存数据....指定缓存路径
                    File sdcache = new File(Environment.getExternalStorageDirectory(), "cache");
                    //指定缓存大小
                    int cacheSize = 10 * 1024 * 1024;

                    okHttpClient = new OkHttpClient.Builder()//构建器
                            .connectTimeout(15, TimeUnit.SECONDS)//连接超时
                            .writeTimeout(20, TimeUnit.SECONDS)//写入超时
                            .readTimeout(20, TimeUnit.SECONDS)//读取超时

                            //.addInterceptor(new CommonParamsInterceptor())//添加的是应用拦截器...公共参数
                            //.addNetworkInterceptor(new CacheInterceptor())//添加的网络拦截器

                            .cache(new Cache(sdcache.getAbsoluteFile(), cacheSize))//设置缓存
                            .build();
                }
            }

        }

        return okHttpClient;
    }

    /**
     * get请求
     * 参数1 url
     * 参数2 回调Callback
     */

    public static void doGet(String oldUrl, Callback callback) {

        //要添加的公共参数...map
        Map<String,String> map = new HashMap<>();
        map.put("source","android");

        StringBuilder stringBuilder = new StringBuilder();//创建一个stringBuilder

        stringBuilder.append(oldUrl);

        if (oldUrl.contains("?")){
            //?在最后面....2类型
            if (oldUrl.indexOf("?") == oldUrl.length()-1){

            }else {
                //3类型...拼接上&
                stringBuilder.append("&");
            }
        }else {
            //不包含? 属于1类型,,,先拼接上?号
            stringBuilder.append("?");
        }

        //添加公共参数....
        for (Map.Entry<String,String> entry: map.entrySet()) {
            //拼接
            stringBuilder.append(entry.getKey())
                    .append("=")
                    .append(entry.getValue())
                    .append("&");
        }

        //删掉最后一个&符号
        if (stringBuilder.indexOf("&") != -1){
            stringBuilder.deleteCharAt(stringBuilder.lastIndexOf("&"));
        }

        String newUrl = stringBuilder.toString();//新的路径


        //创建OkHttpClient请求对象
        OkHttpClient okHttpClient = getInstance();
        //创建Request
        Request request = new Request.Builder().url(newUrl).build();
        //得到Call对象
        Call call = okHttpClient.newCall(request);
        //执行异步请求
        call.enqueue(callback);


    }

    /**
     * post请求
     * 参数1 url
     * 参数2 Map<String, String> params post请求的时候给服务器传的数据
     *      add..("","")
     *      add()
     */

    public static void doPost(String url, Map<String, String> params, Callback callback) {
        //要添加的公共参数...map
        Map<String,String> map = new HashMap<>();
        map.put("source","android");


        //创建OkHttpClient请求对象
        OkHttpClient okHttpClient = getInstance();
        //3.x版本post请求换成FormBody 封装键值对参数

        FormBody.Builder builder = new FormBody.Builder();
        //遍历集合
        for (String key : params.keySet()) {
            builder.add(key, params.get(key));

        }

        //添加公共参数
        for (Map.Entry<String,String> entry: map.entrySet()) {
            builder.add(entry.getKey(),entry.getValue());
        }

        //创建Request
        Request request = new Request.Builder().url(url).post(builder.build()).build();

        Call call = okHttpClient.newCall(request);
        call.enqueue(callback);

    }

    /**
     * post请求上传文件....包括图片....流的形式传任意文件...
     * 参数1 url
     * file表示上传的文件
     * fileName....文件的名字,,例如aaa.jpg
     * params ....传递除了file文件 其他的参数放到map集合
     *
     */
    public static void uploadFile(String url, File file, String fileName,Map<String,String> params) {
        //创建OkHttpClient请求对象
        OkHttpClient okHttpClient = getInstance();

        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);

        //参数
        if (params != null){
            for (String key : params.keySet()){
                builder.addFormDataPart(key,params.get(key));
            }
        }
        //文件...参数name指的是请求路径中所接受的参数...如果路径接收参数键值是fileeeee,此处应该改变
        builder.addFormDataPart("file",fileName,RequestBody.create(MediaType.parse("application/octet-stream"),file));

        //构建
        MultipartBody multipartBody = builder.build();

        //创建Request
        Request request = new Request.Builder().url(url).post(multipartBody).build();

        //得到Call
        Call call = okHttpClient.newCall(request);
        //执行请求
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("upload",e.getLocalizedMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //上传成功回调 目前不需要处理
                if (response.isSuccessful()){
                    String s = response.body().string();
                    Log.e("upload","上传--"+s);
                }
            }
        });

    }

    /**
     * Post请求发送JSON数据....{"name":"zhangsan","pwd":"123456"}
     * 参数一:请求Url
     * 参数二:请求的JSON
     * 参数三:请求回调
     */
    public static void doPostJson(String url, String jsonParams, Callback callback) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonParams);
        Request request = new Request.Builder().url(url).post(requestBody).build();
        Call call = getInstance().newCall(request);
        call.enqueue(callback);

    }

    /**
     * 下载文件 以流的形式把apk写入的指定文件 得到file后进行安装
     * 参数er:请求Url
     * 参数san:保存文件的文件夹....download
     */
    public static void download(final Activity context, final String url, final String saveDir) {
        Request request = new Request.Builder().url(url).build();
        Call call = getInstance().newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //com.orhanobut.logger.Logger.e(e.getLocalizedMessage());
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {

                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                try {
                    is = response.body().byteStream();//以字节流的形式拿回响应实体内容
                    //apk保存路径
                    final String fileDir = isExistDir(saveDir);
                    //文件
                    File file = new File(fileDir, getNameFromUrl(url));

                    fos = new FileOutputStream(file);
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                    }

                    fos.flush();

                    context.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(context, "下载成功:" + fileDir + "," + getNameFromUrl(url), Toast.LENGTH_SHORT).show();
                        }
                    });

                    //apk下载完成后 调用系统的安装方法
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
                    context.startActivity(intent);


                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (is != null) is.close();
                    if (fos != null) fos.close();


                }
            }
        });

    }

    /**
     * 判断下载目录是否存在......并返回绝对路径
     *
     * @param saveDir
     * @return
     * @throws IOException
     */
    public static String isExistDir(String saveDir) throws IOException {
        // 下载位置
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {

            File downloadFile = new File(Environment.getExternalStorageDirectory(), saveDir);
            if (!downloadFile.mkdirs()) {
                downloadFile.createNewFile();
            }
            String savePath = downloadFile.getAbsolutePath();
            Log.e("savePath", savePath);
            return savePath;
        }
        return null;
    }

    /**
     * @param url
     * @return 从下载连接中解析出文件名
     */
    private static String getNameFromUrl(String url) {
        return url.substring(url.lastIndexOf("/") + 1);
    }

    /**
     * 公共参数拦截器
     */
    private static class CommonParamsInterceptor implements Interceptor{

        //拦截的方法
        @Override
        public Response intercept(Chain chain) throws IOException {

            //获取到请求
            Request request = chain.request();
            //获取请求的方式
            String method = request.method();
            //获取请求的路径
            String oldUrl = request.url().toString();

            Log.e("---拦截器",request.url()+"---"+request.method()+"--"+request.header("User-agent"));

            //要添加的公共参数...map
            Map<String,String> map = new HashMap<>();
            map.put("source","android");

            if ("GET".equals(method)){
                // 1.http://www.baoidu.com/login                --------? key=value&key=value
                // 2.http://www.baoidu.com/login?               --------- key=value&key=value
                // 3.http://www.baoidu.com/login?mobile=11111    -----&key=value&key=value

                StringBuilder stringBuilder = new StringBuilder();//创建一个stringBuilder

                stringBuilder.append(oldUrl);

                if (oldUrl.contains("?")){
                    //?在最后面....2类型
                    if (oldUrl.indexOf("?") == oldUrl.length()-1){

                    }else {
                        //3类型...拼接上&
                        stringBuilder.append("&");
                    }
                }else {
                    //不包含? 属于1类型,,,先拼接上?号
                    stringBuilder.append("?");
                }

               //添加公共参数....
                for (Map.Entry<String,String> entry: map.entrySet()) {
                    //拼接
                    stringBuilder.append(entry.getKey())
                            .append("=")
                            .append(entry.getValue())
                            .append("&");
                }

                //删掉最后一个&符号
                if (stringBuilder.indexOf("&") != -1){
                    stringBuilder.deleteCharAt(stringBuilder.lastIndexOf("&"));
                }

                String newUrl = stringBuilder.toString();//新的路径

                //拿着新的路径重新构建请求
                request = request.newBuilder()
                        .url(newUrl)
                        .build();


            }else if ("POST".equals(method)){
                //先获取到老的请求的实体内容
                RequestBody oldRequestBody = request.body();//....之前的请求参数,,,需要放到新的请求实体内容中去

                //如果请求调用的是上面doPost方法
                if (oldRequestBody instanceof FormBody){
                    FormBody oldBody = (FormBody) oldRequestBody;

                    //构建一个新的请求实体内容
                    FormBody.Builder builder = new FormBody.Builder();
                    //1.添加老的参数
                    for (int i=0;i<oldBody.size();i++){
                        builder.add(oldBody.name(i),oldBody.value(i));
                    }
                    //2.添加公共参数
                    for (Map.Entry<String,String> entry:map.entrySet()) {

                        builder.add(entry.getKey(),entry.getValue());
                    }

                    FormBody newBody = builder.build();//新的请求实体内容

                    //构建一个新的请求
                    request = request.newBuilder()
                            .url(oldUrl)
                            .post(newBody)
                            .build();
                }


            }


            Response response = chain.proceed(request);

            return response;
        }
    }

    /**
     * 网络缓存的拦截器......注意在这里更改cache-control头是很危险的,一般客户端不进行更改,,,,服务器端直接指定
     *
     * 没网络取缓存的时候,一般都是在数据库或者sharedPerfernce中取出来的
     *
     *
     *
     */
    /*private static class CacheInterceptor implements Interceptor{

        @Override
        public Response intercept(Chain chain) throws IOException {
            //老的响应
            Response oldResponse = chain.proceed(chain.request());

            *//*if (NetUtils.isNetworkConnected(DashApplication.getAppContext())){
                int maxAge = 120; // 在线缓存在2分钟内可读取

                return oldResponse.newBuilder()
                        .removeHeader("Pragma")
                        .removeHeader("Cache-Control")
                        .header("Cache-Control", "public, max-age=" + maxAge)
                        .build();
            }else {
                int maxStale = 60 * 60 * 24 * 14; // 离线时缓存保存2周
                return oldResponse.newBuilder()
                        .removeHeader("Pragma")
                        .removeHeader("Cache-Control")
                        .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                        .build();
            }*//*

        }
    }*/
}
手动创建获取成功登录信息Superclass解析

搜索展示数据页面
主页面Activity

package com.example.ruiyonghui.usercenter.Show;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.EditText;

import com.example.ruiyonghui.usercenter.R;
import com.example.ruiyonghui.usercenter.Show.P.ShowPersenter;
import com.example.ruiyonghui.usercenter.Show.V.ShowIView;
import com.example.ruiyonghui.usercenter.Untils.Dao;
import com.example.ruiyonghui.usercenter.Untils.ShowAdapter;
import com.example.ruiyonghui.usercenter.Untils.ShowdataBean;
import com.jcodecraeer.xrecyclerview.XRecyclerView;

import java.util.ArrayList;
import java.util.List;

public class Show extends AppCompatActivity implements ShowIView{
    EditText et_keyname;
    int page=1;
    XRecyclerView xrecy;
    List<ShowdataBean.DataBean> list=new ArrayList<>();
    private ShowPersenter showPersenter;
    ShowAdapter showAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show);
        et_keyname= (EditText) findViewById(R.id.et_keyname);
        xrecy= (XRecyclerView) findViewById(R.id.xrecy);

        xrecy.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                showPersenter.Showdata(et_keyname.getText().toString(),1);
                showAdapter.notifyDataSetChanged();
                xrecy.refreshComplete();
            }

            @Override
            public void onLoadMore() {
                showPersenter.Showdata(et_keyname.getText().toString(),page++);
                showAdapter.notifyDataSetChanged();
                xrecy.refreshComplete();
            }
        });

    }

    public void Showdata(View view){
        showPersenter = new ShowPersenter(this);
        showPersenter.Showdata(et_keyname.getText().toString(),page);
        Dao dao=new Dao(this);
        dao.insertJson(et_keyname.getText().toString());
        Intent intent = getIntent();
        intent.putExtra("zhi",et_keyname.getText().toString());
        setResult(2,intent);

    }
    boolean flag=true;
    public void qiehuan(View view){
        if(flag){
            xrecy.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL, flag));
            flag=false;
        }else{
            xrecy.setLayoutManager(new GridLayoutManager(Show.this, 2, LinearLayoutManager.VERTICAL, false));
            flag=true;
        }
    }

    @Override
    public void OnSuccess(final ShowdataBean showdataBean) {
        runOnUiThread(new Runnable() {



            @Override
            public void run() {
                List<ShowdataBean.DataBean> data = showdataBean.getData();
                list.addAll(data);
                showAdapter = new ShowAdapter(Show.this, list);
                xrecy.setLayoutManager(new GridLayoutManager(Show.this, 2, LinearLayoutManager.VERTICAL, false));
                xrecy.setAdapter(showAdapter);
            }
        });
    }
}

M层Moudle
package com.example.ruiyonghui.usercenter.Show.M;

import com.example.ruiyonghui.usercenter.Show.P.ShowIPersenter;
import com.example.ruiyonghui.usercenter.Untils.OkHttp3Util;
import com.example.ruiyonghui.usercenter.Untils.ShowdataBean;
import com.google.gson.Gson;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * Created by ruiyonghui on 2018/1/6.
 */

public class ShowMoudle {
    public void ShowData(String keyname, int page, final ShowIPersenter showIPersenter){
        OkHttp3Util.doGet("http://120.27.23.105/product/searchProducts?keywords="+keyname+"&page="+page+"&source=android", new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if(response.isSuccessful()){
                    String string = response.body().string();
                    Gson gson=new Gson();
                    ShowdataBean showdataBean = gson.fromJson(string, ShowdataBean.class);
                    showIPersenter.OnSuccess(showdataBean);
                }
            }
        });
    }
}
P层
package com.example.ruiyonghui.usercenter.Show.P;

import com.example.ruiyonghui.usercenter.Show.M.ShowMoudle;
import com.example.ruiyonghui.usercenter.Show.V.ShowIView;
import com.example.ruiyonghui.usercenter.Untils.ShowdataBean;

/**
 * Created by ruiyonghui on 2018/1/6.
 */

public class ShowPersenter implements ShowIPersenter {

    ShowMoudle showMoudle;
    ShowIView showIView;

    public ShowPersenter(ShowIView showIView) {
        this.showIView = showIView;
        showMoudle=new ShowMoudle();
    }
    public void Showdata(String keyname,int page){
        showMoudle.ShowData(keyname, page,this);
    }


    @Override
    public void OnSuccess(ShowdataBean showdataBean) {
        showIView.OnSuccess(showdataBean);
    }
}
P层接口
package com.example.ruiyonghui.usercenter.Show.P;

import com.example.ruiyonghui.usercenter.Untils.ShowdataBean;

/**
 * Created by ruiyonghui on 2018/1/6.
 */

public interface ShowIPersenter {
    void OnSuccess(ShowdataBean showdataBean);
}
V层接口
package com.example.ruiyonghui.usercenter.Show.V;

import com.example.ruiyonghui.usercenter.Untils.ShowdataBean;

/**
 * Created by ruiyonghui on 2018/1/6.
 */

public interface ShowIView  {

    void OnSuccess(ShowdataBean showdataBean);
}

展示数据适配器
package com.example.ruiyonghui.usercenter.Untils;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.ruiyonghui.usercenter.R;

import java.util.List;

/**
 * Created by ruiyonghui on 2018/1/6.
 */

public class ShowAdapter extends RecyclerView.Adapter<ShowAdapter.viewholder> {
    Context context;
    List<ShowdataBean.DataBean> list;

    public ShowAdapter(Context context, List<ShowdataBean.DataBean> list) {
        this.context = context;
        this.list = list;
    }

    @Override
    public ShowAdapter.viewholder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view= LayoutInflater.from(context).inflate(R.layout.item,parent,false);
        viewholder viewholder=new viewholder(view);
        return viewholder;
    }

    @Override
    public void onBindViewHolder(ShowAdapter.viewholder holder, int position) {
        holder.tv1.setText("¥"+list.get(position).getBargainPrice());
        String[] split = list.get(position).getImages().split("\\|");
        Glide.with(context).load(split[0]).into(holder.iv);
    }

    @Override
    public int getItemCount() {
        return list.size();
    }
    class viewholder extends RecyclerView.ViewHolder {
        ImageView iv;
        TextView tv1;
        public viewholder(View itemView) {
            super(itemView);
            iv=(ImageView) itemView.findViewById(R.id.item_img);
            tv1=(TextView) itemView.findViewById(R.id.item_text);
        }
    }
}

展示数据的解析类(ShowAdapter)查询成功

//登录页面
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@drawable/img_nature1"
    tools:context="com.example.ruiyonghui.usercenter.DL.V.MainActivity">

    <TextView
        android:id="@+id/login"
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:layout_alignParentEnd="true"
        android:layout_alignParentStart="true"
        android:background="@android:color/holo_orange_dark"
        android:gravity="center"
        android:text="登录"
        android:textSize="18dp" />

    <EditText
        android:id="@+id/et_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入手机号" />

    <EditText
        android:id="@+id/et_pass"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入密码" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        >

        <Button
            android:id="@+id/button3"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@android:color/holo_orange_dark"
            android:onClick="Login"
            android:text="登录"
            android:layout_margin="5dp"
            />

        <Button
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:onClick="zc"
            android:text="注册"
            android:background="@android:color/holo_orange_dark"
            android:layout_margin="5dp"
            />
    </LinearLayout>

</LinearLayout>
注册的页面
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.ruiyonghui.usercenter.Zhuce.V.ZhuceActivity">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/et_user"
        android:hint="请输入账号"
        />
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/et_mima"
        android:hint="请输入密码"
        />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="zhuce"
        android:text="注册"
        />
</LinearLayout>
第三个页面
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.ruiyonghui.usercenter.Xinxi.V.XinxiActivity"
    android:orientation="vertical"
    >
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    >

    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="取消"/>

    <EditText
        android:id="@+id/et"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="9" />
</LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        >

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="热搜"
            android:textColor="@android:color/black"
            android:textSize="20sp"
            />
        <com.example.ruiyonghui.usercenter.Xinxi.Zingdiying
            android:layout_width="wrap_content"
            android:layout_height="80dp"
            >
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="生活"
                android:background="@android:color/darker_gray"
                />
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="性爱"
                android:background="@android:color/darker_gray"
                />
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="无奈"
                android:background="@android:color/darker_gray"
                />
        </com.example.ruiyonghui.usercenter.Xinxi.Zingdiying>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:text="历史记录"
            android:textSize="20sp"

            android:textColor="@android:color/black"
            />

        <ListView
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:id="@+id/lv"
            android:layout_weight="8"></ListView>

        <Button
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:text="消除历史记录"
            android:onClick="clean"
            />
    </LinearLayout>
</LinearLayout>
展示的页面
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.ruiyonghui.usercenter.Show.Show"
    android:orientation="vertical"
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        >
        <EditText
            android:layout_width="0dp"
            android:layout_weight="8"
            android:id="@+id/et_keyname"
            android:layout_height="wrap_content" />

        <TextView
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="搜索"
            android:onClick="Showdata"
            />
        <TextView
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="切换"
            android:onClick="qiehuan"
            />
    </LinearLayout>

    <com.jcodecraeer.xrecyclerview.XRecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/xrecy"
        ></com.jcodecraeer.xrecyclerview.XRecyclerView>
</LinearLayout>

流逝式布局item
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <ImageView
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:id="@+id/item_img"
        />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/item_text"
        />
</LinearLayout>
展示数据list
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/list_tv"
        />
</LinearLayout>


依赖
compile 'com.squareup.okio:okio:1.11.0'
compile 'com.google.code.gson:gson:2.8.2'
compile 'com.github.bumptech.glide:glide:3.6.1'
testCompile 'junit:junit:4.12'

compile 'com.jcodecraeer:xrecyclerview:1.3.2'

网络权限
<uses-permission android:name="android.permission.INTERNET" />












评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值