Search code examples
androidkotlinandroid-sqliteretrofit2

Getting data using Retrofit and inserting to SQLite Database


I have just started working with Kotlin. I have successfully got data from an API using Retrofit. I have to insert that data in SQLite. But I am not able to get a particular data from the response.

Here is my code:

apiInterface.enqueue( object : Callback<List<Movie>> {
        override fun onResponse(call: Call<List<Movie>>?, response: Response<List<Movie>>?) {

            if(response?.body() != null)
                recyclerAdapter.setMovieListItems(response.body()!!)

            response?.let {
                for (i:Int in response.body()!!) {
                    recyclerAdapter.setMovieListItems(response.body()!!)
                    val myMovieList = response.body()

                    val myMovie = myMovieList!!.get(i)


                    var movie = MovieDatabase(myMovie.title, myMovie.image)
                    db.insertMovieData(movie)
                }
            }

        }


        override fun onFailure(call: Call<List<Movie>>?, t: Throwable?) {

        }
    })
}

Here is my insert method:

fun insertMovieData(movie: MovieDatabase) {
    val db = this.writableDatabase
    var cv = ContentValues()
    cv.put(COL_FIRST_NAME, movie.name)
    cv.put(COL_LAST_NAME, movie.image)

    var result = db.insert(TABLE_NAME_MOVIE, null, cv)

    if (result == -1.toLong())
        Toast.makeText(context, "Failed", Toast.LENGTH_SHORT).show()
    else
        Toast.makeText(context, "Success", Toast.LENGTH_SHORT).show()
}

Solution

  • If you've successfully, got back List<Movie> from the response body, just put the response into a List<Movie> myList.

    List<Movie> myMovieList = response.body();

    Then loop over it to get the values you need.

    Movie myMovie = myList.get(0); //To get first Movie in list and so on

    Then as per your Movie class use the getter methods to fetch further details of the movie; For example:

    String imgURL = myMovie.getImage();
    String movieName = myMovie.getTitle();
    

    Build a SQLite DB from Room Persistence Library (it's simpler and easier than directly using SQLite database) and add the movie information there. Read - Save data in a local database using Room. Or, continue with your SQLite database, and call the respective insert method and query you've built with the data you got in imgURL and movieName.

    You can also have a special method in your database handler class which could take entire myMovieList in one go and iterate over it inserting the values into database one by one.

    My code examples are in Java, but, you should be able to write your Kotlin equivalent ones.

    Here's the official documentation on Room Persistence Library.