MVP框架

//主页

package com.example.mvp02.Activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.mvp02.Bean.UserBean;
import com.example.mvp02.Presenter.IPresenterImpl;
import com.example.mvp02.R;
import com.example.mvp02.VIew.IView;

public class MainActivity extends AppCompatActivity implements IView,View.OnClickListener {
    private EditText main_moblie,edit_pwd;
    private Button button_login;
    private IPresenterImpl mIPresenter;
    private String mUrl = "http://www.xieast.com/api/user/login.php?username=%s&password=%s";
    private String m;
    private String s;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        edit_pwd = findViewById(R.id.pwd);
        main_moblie = findViewById(R.id.moblie);
        button_login = findViewById(R.id.login);
        mIPresenter = new IPresenterImpl(this);
        button_login.setOnClickListener(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mIPresenter!= null){
            mIPresenter.onDetach();
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.login:
                m = main_moblie.getText().toString();
                s = edit_pwd.getText().toString();

                checkPermission();
                break;
            default:
                break;
        }
    }
    private void checkPermission(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
            if (ContextCompat.checkSelfPermission(this,Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED){
                ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.INTERNET},100);
            }else {
                startReqset();
            }
        }else {
            startReqset();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 100 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
            startReqset();
        }
    }
    /**
     * 调用presenter方法,开始请求数据
     */
    private void startReqset() {
        mIPresenter.startRequest(String.format(mUrl,m,s));
    }

    @Override
    public void showResponseData(Object data) {
        UserBean userBean = (UserBean) data;
        if (userBean.getCode() == 100){
            Toast.makeText(this,""+userBean.getMsg(),Toast.LENGTH_LONG).show();
            startActivity(new Intent(MainActivity.this,ShowActivity.class));
        }else {
            Toast.makeText(this,""+userBean.getMsg(),Toast.LENGTH_LONG).show();
        }
    }
}

//主页布局

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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=".Activity.MainActivity">

    <EditText
        android:id="@+id/moblie"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入手机号码"
        />
    <EditText
        android:id="@+id/pwd"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入手机密码"
        app:layout_constraintTop_toBottomOf="@id/moblie"
        />
    <Button
        android:id="@+id/login"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toBottomOf="@+id/pwd"
        android:text="登录"
        />
</android.support.constraint.ConstraintLayout>

//View 层 接口

package com.example.mvp02.VIew;
//抽取实现类的接口
public interface IView<T> {
   //请求成功返回的数据
    void showResponseData(T data);
}

//Presenter 层接口

public interface IPresenter {
    void startRequest(String url);
    void startNewsRequest(String newUrl);
}

//Presenter 实现类

package com.example.mvp02.Presenter;

import com.example.mvp02.Bean.NewsBean;
import com.example.mvp02.IModel.IModelImpl;
import com.example.mvp02.MyCallBack.MyCallback;
import com.example.mvp02.Bean.UserBean;
import com.example.mvp02.VIew.IView;

public class IPresenterImpl implements IPresenter {

    private IModelImpl model;
    private IView iView;

    public IPresenterImpl(IView iView){
        this.iView = iView;
        model = new IModelImpl();
    }

    @Override
    public void startRequest(String url) {
        model.requestData(url,new MyCallback<UserBean>() {
            @Override
            public void setData(UserBean data) {
                iView.showResponseData(data);
            }
        });
    }

    @Override
    public void startNewsRequest(String newUrl) {
        model.requestNewsData(newUrl, new MyCallback<NewsBean>() {
            @Override
            public void setData(NewsBean data) {
                iView.showResponseData(data);
            }
        });
    }
    public void onDetach(){
        if (model != null){
            model = null;
        }
        if (iView != null){
            iView = null;
        }
    }
}

//Model 层 实现类

 public interface IModel {
    void requestData(String url, MyCallback callback);
    void requestNewsData(String url, MyCallback callback);
} 

//Model 层 实现类

public class IModelImpl implements IModel {

    private MyCallback callback;

    @Override
    public void requestData(String url, final MyCallback callback) {
        HttpUtil.getInstance().getRequsert(url, UserBean.class, new HttpUtil.Callbak<UserBean>() {
            @Override
            public void onSuccess(UserBean userBean) {
                callback.setData(userBean);
            }
        });
    }

    @Override
    public void requestNewsData(String url, final MyCallback callback) {
        HttpUtil.getInstance().getRequsert(url, NewsBean.class, new HttpUtil.Callbak<NewsBean>() {
            @Override
            public void onSuccess(NewsBean newsBean) {
                callback.setData(newsBean);
            }
        });
    }
}

//CAllBack 接口

public interface MyCallback<T> {
    void setData(T data);
}

//账号密码 Bean类

package com.example.mvp02.Bean;

public class UserBean<T> {


    private String msg;
    private int code;
    private T data;

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}

//show 展示类

package com.example.mvp02.Activity;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.GridView;
import android.widget.ListView;

import com.example.mvp02.Adapter.NewsAdapter;
import com.example.mvp02.Bean.NewsBean;
import com.example.mvp02.Presenter.IPresenter;
import com.example.mvp02.Presenter.IPresenterImpl;
import com.example.mvp02.R;
import com.example.mvp02.VIew.IView;

import java.util.List;

public class ShowActivity extends AppCompatActivity implements IView {
        private GridView show_gridView;
        private IPresenterImpl iPresenter;
    private NewsAdapter adapter;
    private String strurl="http://api.tianapi.com/meinv/?key=605fa0a929c8d8b116424df0510c6b2a&num=35";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show);
        show_gridView = findViewById(R.id.show_gridView);
        adapter = new NewsAdapter(ShowActivity.this);
        show_gridView.setAdapter(adapter);

        iPresenter = new IPresenterImpl(this);
        iPresenter.startNewsRequest(strurl);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        iPresenter.onDetach();
    }

    @Override
    public void showResponseData(Object data) {
        NewsBean newsBean = (NewsBean) data;
        List<NewsBean.NewslistBean> newslistBeans = newsBean.getNewslist();
        adapter.setData(newslistBeans);
    }
}

//新闻的 Bean 类

package com.example.mvp02.Bean;

import java.util.List;

public class NewsBean {

    private int code;
    private String msg;
    private List<NewslistBean> newslist;

    public int getCode() {

        return code;
    }

    public void setCode(int code) {

        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public List<NewslistBean> getNewslist() {
        return newslist;
    }

    public void setNewslist(List<NewslistBean> newslist) {
        this.newslist = newslist;
    }

    public static class NewslistBean {

        private String title;
        private String picUrl;

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public String getPicUrl() {
            return picUrl;
        }

        public void setPicUrl(String picUrl) {
            this.picUrl = picUrl;
        }
    }
}

//新闻 ADAPTER

package com.example.mvp02.Adapter;

import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

import com.example.mvp02.Bean.NewsBean;
import com.example.mvp02.R;
import com.nostra13.universalimageloader.core.ImageLoader;

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

public class NewsAdapter extends BaseAdapter {

    private Context context;
    private List<NewsBean.NewslistBean> list;

    public NewsAdapter(Context context) {
        this.context = context;
        list = new ArrayList<>();
    }

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

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

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null){
            holder = new ViewHolder();
            convertView = View.inflate(context,R.layout.item_view,null);
            holder.picUrl = convertView.findViewById(R.id.priUrl);
            convertView.setTag(holder);
        }else{
            holder = (ViewHolder) convertView.getTag();
        }
            ImageLoader.getInstance().displayImage(list.get(position).getPicUrl(),holder.picUrl);
        return convertView;
    }

    public void setData(List<NewsBean.NewslistBean> newslistBeans) {
        list = newslistBeans;
        notifyDataSetChanged();
    }

    class ViewHolder{
        ImageView picUrl;
    }
}

//image_loader

package com.example.mvp02.App;

import android.app.Application;
import android.graphics.Bitmap;

import com.example.mvp02.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

public class App extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        ImageLoader.getInstance().init(
                new ImageLoaderConfiguration.Builder(this)
                        .memoryCacheSizePercentage(10)
                        .diskCacheSize(50*1024*1024)
                        .defaultDisplayImageOptions(new DisplayImageOptions.Builder()
                                .cacheInMemory(true)
                                .cacheOnDisk(true)
                                .bitmapConfig(Bitmap.Config.RGB_565)
                                .showImageForEmptyUri(R.drawable.ic_launcher_background)
                                .showImageOnFail(R.drawable.ic_launcher_background)
                                .showImageOnLoading(R.drawable.ic_launcher_background)
                                .build())
                        .build()

        );
    }
}

//工具类

package com.example.mvp02.NetUtil;

import android.os.AsyncTask;

import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpUtil {

    private Gson gson;

    //单例
    private static HttpUtil instance;

    //创建私有构造
    private HttpUtil(){
        gson = new Gson();
    }
    //提供静态方法
    public static HttpUtil getInstance(){
        if (instance == null){
            instance = new HttpUtil();
        }
        return instance;
    }
    //定义一个接口
    public interface Callbak<T>{
        void onSuccess(T t);
    }
    //提供一个接口
    public void  getRequsert(final String urlStr,final Class clazz,final Callbak callbak){
        new AsyncTask<String,Void,Object>(){

            @Override
            protected Object doInBackground(String... strings) {
                return getRequsert(urlStr,clazz);
            }

            @Override
            protected void onPostExecute(Object a) {
                callbak.onSuccess(a);
            }
        }.execute(urlStr);
    }

    //创建GSon解析的方法
    public <T> T getRequsert(String urlStr,Class clazz){
        return (T) gson.fromJson(getRequsert(urlStr),clazz);
    }

    //创建网络请求的方法
    public String getRequsert(String urlStr){
        String result = "";
        try {
            URL url = new URL(urlStr);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setReadTimeout(5000);
            urlConnection.setConnectTimeout(5000);
            urlConnection.setRequestMethod("GET");
            int responseCode = urlConnection.getResponseCode();
            if (responseCode == 200){
                result = stream2String(urlConnection.getInputStream());
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
    private  String stream2String(InputStream inputStream) throws IOException {
        InputStreamReader is  =new InputStreamReader(inputStream);
        BufferedReader br = new BufferedReader(is);
        StringBuilder sb = new StringBuilder();
        for (String tmp = br.readLine(); tmp != null; tmp = br.readLine()){
            sb.append(tmp);
        }
        return sb.toString();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值