Android 用Retrofit进行网络获取数据,recyclerview进行展示在Fragment里,并存入到GreenDao数据库中

MainActivity的代码

package wangyetian.bwie.com.myapplication.activity;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.RadioButton;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import wangyetian.bwie.com.myapplication.R;
import wangyetian.bwie.com.myapplication.fragment.HomePageFragment;
import wangyetian.bwie.com.myapplication.fragment.IdeaFragment;
import wangyetian.bwie.com.myapplication.fragment.InformFragment;
import wangyetian.bwie.com.myapplication.fragment.MarketFragment;
import wangyetian.bwie.com.myapplication.fragment.MoreFragment;

public class MainActivity extends AppCompatActivity {

    @Bind(R.id.homepage)
    RadioButton homepage;
    @Bind(R.id.idea)
    RadioButton idea;
    @Bind(R.id.market)
    RadioButton market;
    @Bind(R.id.inform)
    RadioButton inform;
    @Bind(R.id.more)
    RadioButton more;
    @Bind(R.id.Fragment)
    FrameLayout Fragment;
    private HomePageFragment homePageFragment;
    private IdeaFragment ideaFragment;
    private InformFragment informFragment;
    private MarketFragment marketFragment;
    private MoreFragment moreFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        homePageFragment = new HomePageFragment();
        ideaFragment = new IdeaFragment();
        informFragment = new InformFragment();
        marketFragment = new MarketFragment();
        moreFragment = new MoreFragment();

        getSupportFragmentManager().beginTransaction().add(R.id.Fragment, homePageFragment).commit();
        getSupportFragmentManager().beginTransaction().add(R.id.Fragment, ideaFragment).commit();
        getSupportFragmentManager().beginTransaction().add(R.id.Fragment, informFragment).commit();
        getSupportFragmentManager().beginTransaction().add(R.id.Fragment, marketFragment).commit();
        getSupportFragmentManager().beginTransaction().add(R.id.Fragment, moreFragment).commit();
        getSupportFragmentManager().beginTransaction().show(homePageFragment).commit();
        getSupportFragmentManager().beginTransaction().hide(ideaFragment).commit();
        getSupportFragmentManager().beginTransaction().hide(informFragment).commit();
        getSupportFragmentManager().beginTransaction().hide(marketFragment).commit();
        getSupportFragmentManager().beginTransaction().hide(moreFragment).commit();

    }
    
    //网络判断
//    public boolean isNetworkConnected(Context context) {
//        if (context != null) {
//            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
//                    .getSystemService(Context.CONNECTIVITY_SERVICE);
//            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
//            if (mNetworkInfo != null) {
//                Toast.makeText(context, "有网", Toast.LENGTH_SHORT).show();
//                EventBus.getDefault().postSticky("0");
//                return mNetworkInfo.isAvailable();
//            }else{
//                Toast.makeText(context, "无网", Toast.LENGTH_SHORT).show();
//                EventBus.getDefault().postSticky("1");
//            }
//        }
//        return false;
//    }


    @OnClick({R.id.homepage, R.id.idea, R.id.market, R.id.inform, R.id.more})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.homepage:
                getSupportFragmentManager().beginTransaction().show(homePageFragment).commit();
                getSupportFragmentManager().beginTransaction().hide(ideaFragment).commit();
                getSupportFragmentManager().beginTransaction().hide(informFragment).commit();
                getSupportFragmentManager().beginTransaction().hide(marketFragment).commit();
                getSupportFragmentManager().beginTransaction().hide(moreFragment).commit();
                break;
            case R.id.idea:
                getSupportFragmentManager().beginTransaction().hide(homePageFragment).commit();
                getSupportFragmentManager().beginTransaction().show(ideaFragment).commit();
                getSupportFragmentManager().beginTransaction().hide(informFragment).commit();
                getSupportFragmentManager().beginTransaction().hide(marketFragment).commit();
                getSupportFragmentManager().beginTransaction().hide(moreFragment).commit();
                break;
            case R.id.market:
                getSupportFragmentManager().beginTransaction().hide(homePageFragment).commit();
                getSupportFragmentManager().beginTransaction().hide(ideaFragment).commit();
                getSupportFragmentManager().beginTransaction().show(informFragment).commit();
                getSupportFragmentManager().beginTransaction().hide(marketFragment).commit();
                getSupportFragmentManager().beginTransaction().hide(moreFragment).commit();
                break;
            case R.id.inform:
                getSupportFragmentManager().beginTransaction().hide(homePageFragment).commit();
                getSupportFragmentManager().beginTransaction().hide(ideaFragment).commit();
                getSupportFragmentManager().beginTransaction().hide(informFragment).commit();
                getSupportFragmentManager().beginTransaction().show(marketFragment).commit();
                getSupportFragmentManager().beginTransaction().hide(moreFragment).commit();
                break;
            case R.id.more:
                getSupportFragmentManager().beginTransaction().hide(homePageFragment).commit();
                getSupportFragmentManager().beginTransaction().hide(ideaFragment).commit();
                getSupportFragmentManager().beginTransaction().hide(informFragment).commit();
                getSupportFragmentManager().beginTransaction().hide(marketFragment).commit();
                getSupportFragmentManager().beginTransaction().show(moreFragment).commit();
                break;
            default:
                break;
        }
    }
}


Fragmeng里的代码

package wangyetian.bwie.com.myapplication.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.List;

import wangyetian.bwie.com.myapplication.R;
import wangyetian.bwie.com.myapplication.activity.IApplication;
import wangyetian.bwie.com.myapplication.adapter.MyAdapter;
import wangyetian.bwie.com.myapplication.bean.NetDataBean;
import wangyetian.bwie.com.myapplication.bean.NewslistBean;
import wangyetian.bwie.com.myapplication.presenter.MyPresenter;
import wangyetian.bwie.com.myapplication.view.IView;

public class HomePageFragment extends Fragment implements IView {

    private MyPresenter presenter;
    private RecyclerView recyclerView;
    private LinearLayoutManager manager;
    private MyAdapter adapter;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = View.inflate(getActivity(), R.layout.home_page_fragment, null);

        recyclerView = view.findViewById(R.id.recyclerview);

        presenter = new MyPresenter(this);
        presenter.get();

        manager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        adapter = new MyAdapter(getActivity());
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(manager);

        IApplication.session.getNewslistBeanDao().loadAll();
//        EventBus.getDefault().register(this);

        List list1 = presenter.getdb();
        if(list1 == null || list1.size() == 0){
            presenter.get();
        }else {
            adapter.addList(list1);
        }

        return view;
    }

    @Override
    public void onSuccess(NetDataBean bean) {
        adapter.addData(bean);
    }

    @Override
    public void onFailure(Exception e) {

    }

//    @Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
//    public void getEventBus(String i){
//        if (i.equals("0")){
//            return;
//        }else{
//            List datalist = IApplication.session.getNewslistBeanDao().loadAll();
//            MyAdapter myAdapter = new MyAdapter(getActivity(),datalist);
//            recyclerView.setAdapter(myAdapter);
//
//        }
//
//    }

//    @Override
//    public void onDestroyView() {
//        super.onDestroyView();
//        EventBus.getDefault().unregister(this);
//    }
}

retrofit网络获取代码

package wangyetian.bwie.com.myapplication.activity;

import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Query;
import wangyetian.bwie.com.myapplication.bean.NetDataBean;

/**
 * Created by hp on 2017/12/2.
 */
public interface IGetDataBase {

    @GET("/nba/?")
    Call get(@Query("key") String key,@Query("num") int num);

    @FormUrlEncoded
    @POST("/nba/?")
    Call post(@Field("key") String key,@Query("num") int num);

}


初始化类的代码

package wangyetian.bwie.com.myapplication.activity;

import android.app.Application;

import com.facebook.drawee.backends.pipeline.Fresco;

import org.greenrobot.greendao.database.Database;

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import wangyetian.bwie.com.myapplication.dao.DaoMaster;
import wangyetian.bwie.com.myapplication.dao.DaoSession;

/**
 * Created by hp on 2017/12/2.
 */
public class IApplication extends Application {

    public static IGetDataBase iGetDataBase;
    public static DaoSession session;

    @Override
    public void onCreate() {
        super.onCreate();
        Fresco.initialize(this);

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://api.tianapi.com")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        iGetDataBase = retrofit.create(IGetDataBase.class);

        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this,"tests");
        Database database = helper.getWritableDb();
        session = new DaoMaster(database).newSession();

    }
}

adapter适配器代码

package wangyetian.bwie.com.myapplication.adapter;

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

import com.facebook.drawee.view.SimpleDraweeView;

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

import wangyetian.bwie.com.myapplication.R;
import wangyetian.bwie.com.myapplication.bean.NetDataBean;
import wangyetian.bwie.com.myapplication.bean.NewslistBean;

/**
 * Created by hp on 2017/12/2.
 */
public class MyAdapter extends RecyclerView.Adapter {

    private Context context;
    private List list;

    public void addData(NetDataBean bean) {
        if (list == null) {
            list = new ArrayList<>();
        }
        list.addAll(bean.getNewslist());
        notifyDataSetChanged();
    }

    public void addList(List bean) {
        if (list == null) {
            list = new ArrayList<>();
        }
        list.addAll(bean);
        notifyDataSetChanged();
    }

    public MyAdapter(Context context) {
        this.context = context;
    }

    @Override
    public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = View.inflate(context,R.layout.item,null);
        return new MyHolder(view);
    }

    @Override
    public void onBindViewHolder(MyHolder holder, int position) {
        holder.simpleDraweeView.setImageURI(list.get(position).getPicUrl());
        holder.tv_title.setText(list.get(position).getTitle());
        holder.tv_source.setText(list.get(position).getCtime());

    }

        @Override
        public int getItemCount() {
            return list == null?0:list.size();
        }

        static class MyHolder extends RecyclerView.ViewHolder{

            SimpleDraweeView simpleDraweeView;
            TextView tv_title,tv_source;
        public MyHolder(View itemView) {
            super(itemView);
            simpleDraweeView = itemView.findViewById(R.id.simpledraweeview);
            tv_title = itemView.findViewById(R.id.tv_title);
            tv_source = itemView.findViewById(R.id.tv_source);
        }
    }
}

MVP的View层代码

package wangyetian.bwie.com.myapplication.view;

import wangyetian.bwie.com.myapplication.bean.NetDataBean;

/**
 * Created by hp on 2017/12/2.
 */
public interface IView {
    public void onSuccess(NetDataBean bean);
    public void onFailure(Exception e);
}

MVP的Model层接口代码

package wangyetian.bwie.com.myapplication.model;

import wangyetian.bwie.com.myapplication.bean.NetDataBean;

/**
 * Created by hp on 2017/12/2.
 */
public interface IModel {
    public void onSuccess(NetDataBean bean);
    public void onFailure(Exception e);
}

MVP的Model层代码

package wangyetian.bwie.com.myapplication.model;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import wangyetian.bwie.com.myapplication.activity.IApplication;
import wangyetian.bwie.com.myapplication.bean.NetDataBean;
import wangyetian.bwie.com.myapplication.bean.NewslistBean;
import wangyetian.bwie.com.myapplication.dao.DaoSession;

/**
 * Created by hp on 2017/12/2.
 */
public class MyModel {

    public void getData(final IModel callback){
        Call call = IApplication.iGetDataBase.get("11ebce8ebe253e019b886ae1547b07d7",10);

        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                NetDataBean bean = response.body();
                callback.onSuccess(bean);
                IApplication.session.getNewslistBeanDao().insertInTx(bean.getNewslist());
            }

            @Override
            public void onFailure(Call call, Throwable t) {
                callback.onFailure(new Exception(""));
            }
        });

    }

    public void postDat(final IModel callback){
        Call call = IApplication.iGetDataBase.post("11ebce8ebe253e019b886ae1547b07d7",10);

        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                NetDataBean bean = response.body();
                callback.onSuccess(bean);
            }

            @Override
            public void onFailure(Call call, Throwable t) {
                callback.onFailure(new Exception(""));
            }
        });

    }

    public List getdb(DaoSession session){
        List list = session.getNewslistBeanDao().loadAll();
        return list;
    }

}

MVP的Presente层r的代码
package wangyetian.bwie.com.myapplication.presenter;

import java.util.List;

import wangyetian.bwie.com.myapplication.activity.IApplication;
import wangyetian.bwie.com.myapplication.bean.NetDataBean;
import wangyetian.bwie.com.myapplication.bean.NewslistBean;
import wangyetian.bwie.com.myapplication.model.IModel;
import wangyetian.bwie.com.myapplication.model.MyModel;
import wangyetian.bwie.com.myapplication.view.IView;

/**
 * Created by hp on 2017/12/2.
 */
public class MyPresenter {

    private IView view;
    private MyModel model;

    public MyPresenter(IView view) {
        this.view = view;
        this.model = new MyModel();
    }

    public List getdb(){
        List list = model.getdb(IApplication.session);
        return list;
    }

    public void get(){
        model.getData(new IModel() {
            @Override
            public void onSuccess(NetDataBean bean) {
                if (view != null){
                    view.onSuccess(bean);
                }
            }

            @Override
            public void onFailure(Exception e) {
                if (view != null){
                    view.onFailure(e);
                }
            }
        });
    }

    public void post(){
        model.postDat(new IModel() {
            @Override
            public void onSuccess(NetDataBean bean) {
                if (view != null){
                    view.onSuccess(bean);
                }
            }

            @Override
            public void onFailure(Exception e) {
                if (view != null){
                    view.onFailure(e);
                }
            }
        });
    }

}

MainActivity的布局




    
    
    
        
            

            

            

            

            

        
    



recyclerview的布局自行定义,bean类自己定义

greendao的集成和使用可以去这个网址查看:http://www.jianshu.com/p/853401a7d02b

你可能感兴趣的:(Android)