How can I store JSON Data into Realm and show it into recyclerview

Viewed 5677

In my app, I have implemented a recyclerview. I have an api in json foramt which contains the user information of an institute. Now initially I want to store data into Realm DB and them populate my recyclerview with those data. Hence I am trying to get some working document of this procedure. But I have not found any clear explanation realted to this. I am not sure about the correct procedure of it. Do I need to fetch all data using Httpurlconnection and then store it to Realm. Or is there any alterantive way to do that.

Edit Question

After getting some sugesstion I have tried with the follwing code.I am using Retrofit 1.9. because I was not able to fetch data using Retrofit 2+ version. As I am getting result from retrofit 1.9. I want to keep my code based on that. But now have confusion on how to set adapter based on realm. because I have seperate model class for json api and realm. I want to store data into realm at first and then populate it to recaclerview. at thisi moment the recyclerview is populated direct with server data.

After getting instruction from the answer I have edited my question as below

Json response

    [
    {
    "_id": "fhfh49879787989",
    "dn": "CN=9879798789",
    "whenChanged": "20170704065349.0Z",
    "name": "Student",
    "mail": "student@mail.com",
    "updated_at": "2017-07-04T18:22:43.624Z"
  },
  {
    "_id": "595bdcf32c67a3f9ee6c2a25",
    "dn": "CN=dsfdsfsdfsf",
    "givenName": "Accounting Office",
    "whenChanged": "20170801114732.0Z",
    "name": "Accounting",
    "mail": "accounting@mail.com",
    "updated_at": "2017-07-04T18:22:43.641Z"
  },
  {
    "_id": "584ab3b4122d13e1b0d1578d",
    "dn": "CN=sfdfsfsdfl",
    "sn": "Abels",
    "title": "Student",
    "givenName": "Gardrut",
    "whenChanged": "20170807150844.0Z",
    "department": "PMO",
    "company": "Multi Lmited",
    "name": "Mike Lizz",
    "mail": "mail@yahoo.com",
    "mobile": "+1321646498",
    "updated_at": "2016-12-09T13:37:56.175Z"
  },
  {
    "_id": "584ab3b3122d13e1b0d15735",
    "dn": "CN=xdfsdfsfsdf",
    "sn": "Acsdff",
    "title": "Software Engineer",
    "givenName": "Olin",
    "whenChanged": "20170810064841.0Z",
    "department": "Head",
    "company": "Private limited",
    "name": "James Oliver",
    "mail": "mail@gmail.com",
    "mobile": "+41228",
    "updated_at": "2016-12-09T13:37:55.813Z"
  },
  ....
 ]

My Model Class

    public class ColleagueModel {

    @Expose
    private String _id;
    @Expose
    private String dn;
    @Expose
    private String givenName;
    @Expose
    private String whenChanged;
    @Expose
    private String name;
    @Expose
    private String mail;
    @Expose
    private String updatedAt;
    @Expose
    private String sn;
    @Expose
    private String title;
    @Expose
    private String department;
    @Expose
    private String company;
    @Expose
    private String mobile;

    public ColleagueModel(){

    }
    //getter and setter

   }

The library I use

compile 'com.squareup.retrofit:retrofit:1.9.0'
compile 'com.squareup.okhttp:okhttp:2.3.0'
compile 'com.google.code.gson:gson:2.3'
compile 'com.squareup.picasso:picasso:2.5.2'

ApiService

public interface ColleagueApiService {

@GET("/api/users")

void getColleague(Callback<String> flowers);

RestManagerClass

    public class ColleagueRestManager {

    public ColleagueApiService mColleagueApi;


    public ColleagueApiService getColleagueApi() {

        if (mColleagueApi == null) {
            GsonBuilder gson = new GsonBuilder();
            gson.registerTypeAdapter( String.class, new StringDeserializer() );

            mColleagueApi = new RestAdapter.Builder()
                    .setEndpoint( Constants.HTTP.BASE_URL )
                    .setConverter( new GsonConverter( gson.create() ) )
                    .build()
                    .create( ColleagueApiService.class );
        }
        return mColleagueApi;
    }
}

Adapter Class

public class MyColleaguesAdapter extends RecyclerView.Adapter<MyColleaguesAdapter.ColleagueHolder>/{

public static String TAG = MyColleaguesAdapter.class.getSimpleName();

private List<ColleagueModel> mColleague;

private Context context;

public interface ColleagueListListener {
}

public MyColleaguesAdapter(List<ColleagueModel> colleagues,Context context) 
{
    this.context=context;
    mColleague = colleagues;
}
public void addColleague(ColleagueModel colleague) {
    //Log.d(TAG,colleague.name);
    mColleague.add(colleague);
    notifyDataSetChanged();
}



@Override
public ColleagueHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.colleage_row_layout,parent,false);
    return new ColleagueHolder(view);
}
@Override
public void onBindViewHolder(ColleagueHolder holder, int position) {

    final ColleagueModel currentColleague = mColleague.get(position);
    Picasso.with(holder.itemView.getContext());
    holder.colleagueName.setText(currentColleague.getName());
    holder.companyName.setText(currentColleague.getCompany());
    holder.jobTitle.setText(currentColleague.getTitle());

    holder.colleaguePicture.setImageResource( R.drawable.profile_image );
    Picasso.with(holder.itemView.getContext()).load( Constants.HTTP.PHOTO_URL + currentColleague.getMail()).into(holder.colleaguePicture);

    holder.cardView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent i=new Intent(context,DetailMyColleague.class);
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            i.putExtra("IMAGE_URL",Constants.HTTP.PHOTO_URL + currentColleague.getMail());
            i.putExtra("name",currentColleague.getName());
            i.putExtra("title",currentColleague.getTitle());
            i.putExtra("company",currentColleague.getCompany());
            i.putExtra("mobile",currentColleague.getMobile());
            i.putExtra("mail",currentColleague.getMail());
            i.putExtra("department",currentColleague.getDepartment());
            context.startActivity(i);
        }
    });


}

@Override
public int getItemCount() {
    return mColleague.size();
}

public class ColleagueHolder extends RecyclerView.ViewHolder{

    public CardView cardView;
    public ImageView colleaguePicture;
    public TextView  colleagueName;
    public TextView  companyName;
    public TextView  jobTitle;

    public ColleagueHolder(View itemView) {
        super(itemView);
        colleaguePicture= itemView.findViewById(R.id.colleague_picture);
        colleagueName= itemView.findViewById(R.id.colleague_name);
        companyName= itemView.findViewById(R.id.company_name);
        jobTitle= itemView.findViewById(R.id.job_title);
        cardView= itemView.findViewById(R.id.cardview_user);

      }
    }
 }

Controller Class

    public class Controller {

    private static final String TAG = Controller.class.getSimpleName();
    private UserCallbackListener mListener;
    private ColleagueRestManager mApiManager;

    public Controller(UserCallbackListener listener) {
        mListener = listener;
        mApiManager = new ColleagueRestManager();
    }

    public void startFetching(){

        mApiManager.getColleagueApi().getColleague(new Callback<String>() {
            @Override
            public void success(String s, Response response) {
                Log.d(TAG, "JSON :: " + s);

                try {
                    JSONArray array = new JSONArray(s);

                    for(int i = 0; i < array.length(); i++) {
                        JSONObject object = array.getJSONObject(i);

                        ColleagueModel colleague = new ColleagueModel();
                        colleague.setName( object.optString( "name" ) );
                        colleague.setCompany(object.optString("company"));
                        colleague.setTitle(object.optString("title"));
                        colleague.setMail( object.optString("mail"));
                        colleague.setMobile(object.optString("mobile"));
                        colleague.setDepartment(object.optString("department"));

                        mListener.onFetchProgress(colleague);

                    }

                } catch (JSONException e) {
                    mListener.onFetchFailed();
                }


                mListener.onFetchComplete();
            }

            @Override
            public void failure(RetrofitError error) {
                Log.d(TAG, "Error :: " + error.getMessage());
                mListener.onFetchComplete();
            }
        });

    }
    public interface UserCallbackListener{
        void onFetchStart();
        void onFetchProgress(ColleagueModel user);
        void onFetchProgress(List<ColleagueModel> userList);
        void onFetchComplete();
        void onFetchFailed();
    }

}

Main Activity

public class MyColleaguesPage extends AppCompatActivity implements Controller.UserCallbackListener/*MyColleaguesAdapter.ColleagueListListener*/ {

private RecyclerView recyclerView;
private MyColleaguesAdapter adapter;
private List<ColleagueModel> mColleagueList = new ArrayList<>();
private Controller mController;

private Realm colleagueRealm;

private LinearLayoutManager layoutManager;

private RealmResults<MyColleagueModel> colleagueResult;

private List<MyColleagueModel> filteredModelList;
private RealmChangeListener realmListener;
private static final String DIALOG_TAG = "EmployeeDialog";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mycolleagues_layout);

    configViews();

    mController = new Controller(MyColleaguesPage.this);
    mController.startFetching();

    colleagueRealm = Realm.getDefaultInstance();


}

private void configViews() {
    recyclerView = this.findViewById(R.id.colleagues_recycler);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(MyColleaguesPage.this));
    recyclerView.setRecycledViewPool(new RecyclerView.RecycledViewPool());

    adapter = new MyColleaguesAdapter(mColleagueList,getApplicationContext());
    recyclerView.setAdapter(adapter);
}

}

RealmApplication Class

public class Application extends Application {

@Override
public void onCreate() {
    super.onCreate();

    Realm.init(this);
    RealmConfiguration realmConfiguration = new RealmConfiguration.Builder()
            .deleteRealmIfMigrationNeeded()
            .build();
    Realm.setDefaultConfiguration(realmConfiguration);
  }

Realm Model

public class RealmUserModel extends RealmObject{
public static final String ID = "id";

private String id;
private String dn;
private String givenName;
private String whenChanged;
private String name;
private String mail;
private String updatedAt;
private String sn;
private String title;
private String department;
private String company;
private String mobile;

//getter and setter
}
1 Answers
Related