• ① Add okHTTP-based network request encapsulation framework OKHttpFinal
    • ② Initialize okHttpFinal
    • ③ Create the entity class (for clarity, separate the inner classes ResultBean and DataBean).
    • ④ Define the network listening callback interface
    • ⑤ Define the interface class to obtain network data, and define the method to obtain data
    • Creating an implementation class that gets the network data interface, NetTask, actually gets the data
    • Define a View layer interface with Presenter, for view and module layer interaction
    • ⑧ Contract interface
    • ⑨ Implements Presenter interface
    • ⑩ Add fragment to the tool method in Acvitity
    • Fragment implements the View interface, which is used to receive the IpinfoPresenter callback and update the interface
    • 12, the implementation of acvitity

① Add okHTTP-based network request encapsulation framework OKHttpFinal

Implementation 'cn. Finalteam: okhttpfinal: 2.0.7'Copy the code

② Initialize okHttpFinal

 @Override
    public void onCreate() {
        super.onCreate();
        OkHttpFinalConfiguration.Builder builder=new OkHttpFinalConfiguration.Builder();
        OkHttpFinal.getInstance().init(builder.build());
    }
Copy the code

③ Create the entity class (for clarity, separate the inner classes ResultBean and DataBean).

. private String reason; private ResultBean result; private int error_code; .Copy the code

④ Define the network listening callback interface

public interface LoadTasksCallBack<T> {
    void onStart();

    void onFinish();

    void onSuccess(T t);

    void onFailed();

}
Copy the code

⑤ Define the interface class to obtain network data, and define the method to obtain data

public interface NetTask<T> {
    void execute(T data,LoadTasksCallBack callBack);
}
Copy the code

Creating an implementation class that gets the network data interface, NetTask, actually gets the data

package com.gradle.ytf.mvpapplication.api; import com.gradle.ytf.mvpapplication.module.TitleData; import cn.finalteam.okhttpfinal.BaseHttpRequestCallback; import cn.finalteam.okhttpfinal.HttpRequest; / * * * 6 to create access to the network data interface NetTask implementation class to get actual data, determine the generic string * IpInfoTask depending on the type of data returned is a singleton class, through okhttpfinal access to data in the execute method, @author YTF */ public class IpInfoTask implements NetTask<String> { private IpInfoTask() { } public static IpInfoTask getInstance() { return SingletonHolder.sInstance; } private static class SingletonHolder { private static final IpInfoTask sInstance = new IpInfoTask(); } @Override public void execute(final String url, final LoadTasksCallBack callBack) { HttpRequest.get(url, new BaseHttpRequestCallback<TitleData>() { @Override public void onStart() { super.onStart(); callBack.onStart(); } @Override protected void onSuccess(TitleData ipInfo) { super.onSuccess(ipInfo); callBack.onSuccess(ipInfo); } @Override public void onFinish() { super.onFinish(); callBack.onFinish(); } @Override public void onFailure(int errorCode, String msg) { super.onFailure(errorCode, msg); callBack.onFailed(); }}); }}Copy the code

Define a View layer interface with Presenter, for view and module layer interaction

package com.gradle.ytf.mvpapplication.view; /** * define a view layer interface with presenter for view and module interaction. * @param <T> */ public interface BaseView<T> {void setPresenter(T presenter); }Copy the code

⑧ Contract interface

package com.gradle.ytf.mvpapplication.contract; import com.gradle.ytf.mvpapplication.module.TitleData; import com.gradle.ytf.mvpapplication.view.BaseView; /** * the contract interface is mainly used to store the same business of the Presenter and View interface, easy to find and maintain. */ public interface IpInfoContract {/** * interface Presenter {void getIpInfo(String URL); } /** * the isActive method extends BaseView<Presenter> {void setIpInfo(TitleData ipData); void showLoading(); void hideLoading(); void showError(); boolean isActivie(); }}Copy the code

⑨ Implements Presenter interface

package com.gradle.ytf.mvpapplication.presenter; import com.gradle.ytf.mvpapplication.api.LoadTasksCallBack; import com.gradle.ytf.mvpapplication.api.NetTask; import com.gradle.ytf.mvpapplication.contract.IpInfoContract; import com.gradle.ytf.mvpapplication.module.TitleData; /** * ⑨ Implements the Presenter interface: * Presenter is essentially a middleman that retrieves and stores data via NetTask (Model layer) and updates the interface via View. The interface is defined so that there is no interaction between the View and Model. */ public class IpInfoPresenter implements IpInfoContract.Presenter, LoadTasksCallBack<TitleData> {/** * IpInfoPresenter contains instances of NetTask and InfoContract.View, And implements the LoadTasksCallBack interface * mnettask.execute (IP, this) to fetch data and call back to InInfoPresenter, After calling back to InInfoPresenter, interact with the page through mAddTaskView to change the interface. */ private NetTask mNetTask; private IpInfoContract.View mAddTaskView; public IpInfoPresenter(NetTask netTask, IpInfoContract.View addTaskView) { mNetTask = netTask; mAddTaskView = addTaskView; } @Override public void onStart() { if (mAddTaskView.isActivie()) { mAddTaskView.showLoading(); } } @Override public void onFinish() { if (mAddTaskView.isActivie()) { mAddTaskView.hideLoading(); } } @Override public void onSuccess(TitleData titleData) { if (mAddTaskView.isActivie()) { mAddTaskView.setIpInfo(titleData); } } @Override public void onFailed() { if (mAddTaskView.isActivie()) { mAddTaskView.showError(); mAddTaskView.hideLoading(); } } @Override public void getIpInfo(String url) { mNetTask.execute(url, this); }}Copy the code

⑩ Add fragment to the tool method in Acvitity

package com.gradle.ytf.mvpapplication.util; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; Public class ActivityUtils {public static void addFragmentToActivity(FragmentManager fragmentManager, Fragment fragment, int frameId) { FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.add(frameId, fragment); fragmentTransaction.commit(); }}Copy the code

Fragment implements the View interface, which is used to receive the IpinfoPresenter callback and update the interface

package com.gradle.ytf.mvpapplication.view; import android.app.ProgressDialog; import android.content.Context; import android.net.Uri; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.gradle.ytf.mvpapplication.R; import com.gradle.ytf.mvpapplication.contract.IpInfoContract; import com.gradle.ytf.mvpapplication.module.DataBean; import com.gradle.ytf.mvpapplication.module.TitleData; import java.util.List; /** * 11, fragment implement view interface, */ public class IpInfoFragment extends Fragment implements ipInfoContract. View {private Button mBt_ipinfo; private TextView mNews; private ProgressDialog mProgressDialog; private IpInfoContract.Presenter mPresenter; private static final String URL = "http://v.juhe.cn/toutiao/index?type=top&key=cc651913ae067cf88c7d9ec710fe5b3a"; public static IpInfoFragment newInstance() { return new IpInfoFragment(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View root = inflater.inflate(R.layout.fragment_ip_info, container, false); mNews = (TextView) root.findViewById(R.id.tv_news); mBt_ipinfo = (Button) root.findViewById(R.id.bt_ipinfo); return root; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mProgressDialog = new ProgressDialog(getActivity()); Mprogressdialog.settitle (" getting data "); mBt_ipinfo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mPresenter.getIpInfo(URL); }}); } /** * getIpInfo: Override public void setIpInfo(TitleData ipInfo) {if (TitleData ipInfo! = null && ipInfo.getResult().getData() ! = null) { List<DataBean> data = ipInfo.getResult().getData(); mNews.setText(data.get(0).getTitle()); } } @Override public void showLoading() { mProgressDialog.show(); } @Override public void hideLoading() { if (mProgressDialog.isShowing()) { mProgressDialog.dismiss(); }} @override public void showError() {toast.maketext (getActivity(), toast.length_short).show(); } @Override public boolean isActivie() { return isAdded(); } /** * the setPresenter method injects IpInfoPresenter. * @param presenter */ @Override public void setPresenter(IpInfoContract.Presenter presenter) { mPresenter = presenter; }}Copy the code

12, the implementation of acvitity

package com.gradle.ytf.mvpapplication.view; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import com.gradle.ytf.mvpapplication.R; import com.gradle.ytf.mvpapplication.api.IpInfoTask; import com.gradle.ytf.mvpapplication.presenter.IpInfoPresenter; import com.gradle.ytf.mvpapplication.util.ActivityUtils; /** * @author YTF */ public class MainActivity extends AppCompatActivity { private IpInfoPresenter ipInfoPresenter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); IpInfoFragment IpInfoFragment = (IpInfoFragment) getSupportFragmentManager().findFragmentById(R.id.contentFrame); if (ipInfoFragment == null) { ipInfoFragment = IpInfoFragment.newInstance(); ActivityUtils.addFragmentToActivity(getSupportFragmentManager(), ipInfoFragment, R.id.contentFrame); } // Inject Presenter into a Fragment IpInfoTask IpInfoTask = ipInfotask.getInstance (); // Inject Presenter into a Fragment IpInfoTask IpInfoTask = ipInfotask.getInstance (); ipInfoPresenter = new IpInfoPresenter(ipInfoTask, ipInfoFragment); ipInfoFragment.setPresenter(ipInfoPresenter); }}Copy the code

Finally, don’t forget to add network request permissions

Effect:



Git address:Gitee.com/ytfunny_sit…