2

I want to ask that how could we populate the recyclerview from SQLite database in my android app. Actually, the data is coming from a remote server through json and my task is to populate recyclerview from making API calls when Internet is available and if it is not available then I have to save that remote server response into local SQLite database so I could fetch the saved result and populate the list in absence of Internet too

public class SQLiteHandler extends SQLiteOpenHelper {

private static final String TAG = SQLiteHandler.class.getSimpleName();

// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "image_api";

// Login table name
private static final String TABLE_LIST = "images";

// Login Table Columns names
public static final String KEY_ID = "id";
public static final String KEY_TITLE = "title";
public static final String KEY_ALBUMID = "albumid";
public static final String KEY_THUMBNAILURL = "thumbnailurl";
public static final String KEY_IMAGE = "image";

SQLiteHandler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}


@Override
public void onCreate(SQLiteDatabase db) {

    String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_LIST + "("
            + KEY_ID + " INTEGER PRIMARY KEY," + KEY_TITLE + " TEXT,"
            + KEY_ALBUMID + " TEXT UNIQUE," + KEY_THUMBNAILURL + " TEXT,"
            + KEY_IMAGE + " TEXT" + ")";
    db.execSQL(CREATE_LOGIN_TABLE);

    Log.d(TAG, "Database tables created");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    db.execSQL("DROP TABLE IF EXISTS " + TABLE_LIST);

    // Create tables again
    onCreate(db);

}

/**
 * Storing user details in database
 * */
void addUser(String Id, String title, String albumid, String thumbnailurl, String image) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_ID, Id); // Name
    values.put(KEY_TITLE, title); // Email
    values.put(KEY_ALBUMID, albumid); // Email
    values.put(KEY_THUMBNAILURL, thumbnailurl);
    values.put(KEY_IMAGE, image);// Created At

    // Inserting Row
    long id = db.insert(TABLE_LIST, null, values);
    db.close(); // Closing database connection

    Log.d(TAG, "New user inserted into sqlite: " + id);
}

/**
 * Getting user data from database
 * */
public HashMap<String, String> getUserDetails() {
    HashMap<String, String> user = new HashMap<String, String>();
    String selectQuery = "SELECT  * FROM " + TABLE_LIST;

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    // Move to first row
    cursor.moveToFirst();
    if (cursor.getCount() > 0) {
        user.put("Id", cursor.getString(1));
        user.put("title", cursor.getString(2));
        user.put("albumid", cursor.getString(3));
        user.put("thumbnailurl", cursor.getString(4));
        user.put("image", cursor.getString(5));
    }
    cursor.close();
    db.close();
    // return user
    Log.d(TAG, "Fetching user from Sqlite: " + user.toString());

    return user;
}

long getProfilesCount() {
    SQLiteDatabase db = this.getReadableDatabase();
    long count = DatabaseUtils.queryNumEntries(db, TABLE_LIST);
    db.close();
    return count;
}


public Cursor getAllPersons() {
    SQLiteDatabase db = this.getReadableDatabase();
    return db.rawQuery( "SELECT * FROM " + TABLE_LIST, null );
}


 }

This is my mainActivity

public class MainActivity extends AppCompatActivity {

private List<Movie> movieList;
private RecyclerView.Adapter adapter;
private SQLiteHandler db;
long profile_counts;
//private ArrayList noList;


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

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    RecyclerView mList = findViewById(R.id.main_list);
    db = new SQLiteHandler(getApplicationContext());
    profile_counts = db.getProfilesCount();

    movieList = new ArrayList<>();
    adapter = new MovieAdapter(getApplicationContext(), movieList);


    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
    linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(mList.getContext(), linearLayoutManager.getOrientation());

    mList.setHasFixedSize(true);
    mList.setLayoutManager(linearLayoutManager);
    mList.addItemDecoration(dividerItemDecoration);
    mList.setAdapter(adapter);

    if (isNetworkAvailable()) {
        getData();
    }

    else

        {

            Toast.makeText(MainActivity.this,"No Internet",Toast.LENGTH_LONG).show();



    }


}


private void getData() {
    final ProgressDialog progressDialog = new ProgressDialog(this);
    progressDialog.setMax(100);
    progressDialog.setMessage("Its loading....");
    progressDialog.setTitle("Imageview Example");
    progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    progressDialog.show();

    String url = "http://jsonplaceholder.typicode.com/photos";
    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
        @Override
        public void onResponse(JSONArray response) {
            for (int i = 0; i < response.length(); i++) {
                try {
                    JSONObject jsonObject = response.getJSONObject(i);

                    Movie movie = new Movie();
                    movie.setTitle(jsonObject.getString("title"));
                    movie.setId(jsonObject.getInt("id"));
                    movie.setImage(jsonObject.getString("url"));
                    movie.setAlbumid(jsonObject.getString("albumId"));
                    movie.setThumbnailurl(jsonObject.getString("thumbnailUrl"));


                    movieList.add(movie);

                    String Title = jsonObject.getString("title");
                    String Id = jsonObject.getString("id");
                    String Image = jsonObject.getString("url");
                    String Album = jsonObject.getString("albumId");
                    String Thumbnail = jsonObject.getString("thumbnailUrl");


                    Log.e("List Loaded", "imagesList");
                    Log.i("Title", Title);
                    Log.i("Id", Id);
                    Log.i("Image", Image);
                    Log.i("Album", Album);
                    Log.i("Thumbnail", Thumbnail);

                    db.addUser(Id, Title, Album, Thumbnail, Image);
                    Log.d("number of elements", String.valueOf(profile_counts));


                } catch (JSONException e) {
                    e.printStackTrace();
                    progressDialog.dismiss();
                }
            }
            adapter.notifyDataSetChanged();
            progressDialog.dismiss();
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("Volley", error.toString());
            progressDialog.dismiss();
        }
    });
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(jsonArrayRequest);
}


private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager
            = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = null;
    if (connectivityManager != null) {
        activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    }
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

 }

Now I just want to know how do I populate the recyclerview from SQLite database, so far I have been able to get the data from remote server and save it in the SQLite database with the help of SqliteHandler class.This is my adapter class

public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.ViewHolder> {

private Context context;
private List<Movie> list;
private String link;
private imageDownload image;

MovieAdapter(Context context, List<Movie> list) {
    this.context = context;
    this.list = list;

}


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

    View v = LayoutInflater.from(context).inflate(R.layout.list, parent, false);
    return new ViewHolder(v);

}

@Override
public void onBindViewHolder(@NonNull final MovieAdapter.ViewHolder holder,  int position) {

    Movie movie = list.get(position);


    holder.textTitle.setText(movie.getTitle());
    holder.textId.setText(String.valueOf(movie.getId()));
    holder.textThumb.setText(movie.getThumbnailurl());
    holder.textAlbum.setText(String.valueOf(movie.getAlbumid()));

    Picasso.with(context).load(movie.getImage())
            .into(holder.photo);


    holder.photo.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            link = list.get(holder.getAdapterPosition()+1).getImage();
            image = new imageDownload(context, holder.photo);
            image.execute(link);
            Log.e("image link", link);
            Toast.makeText(context, "image clicked: " + holder.getAdapterPosition(), Toast.LENGTH_LONG).show();
        }
    });

}


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


class ViewHolder extends RecyclerView.ViewHolder {
    TextView textTitle, textId, textThumb, textAlbum;
    ImageView photo;

    ViewHolder(View itemView) {
        super(itemView);

        textTitle = itemView.findViewById(R.id.title_1);
        textId = itemView.findViewById(R.id.id_1);
        textThumb = itemView.findViewById(R.id.thumbnailurl_1);
        textAlbum = itemView.findViewById(R.id.albumid_1);
        photo = itemView.findViewById(R.id.imageview);


    }
}


class imageDownload extends AsyncTask<String, Integer, Bitmap> {
    Context context;
    ImageView imageView;
    Bitmap bitmap;
    InputStream in = null;

    //constructor.
    imageDownload(Context context, ImageView imageView) {
        this.context = context;
        this.imageView = imageView;
    }

    @Override
    protected void onPreExecute() {


    }

    @Override
    protected Bitmap doInBackground(String... params) {
        HttpURLConnection httpURLConnection = null;
        try {
            URL url = new URL(params[0]);
            httpURLConnection = (HttpURLConnection) url.openConnection();

            httpURLConnection.connect();


            in = httpURLConnection.getInputStream();
            BufferedInputStream bufferedInputStream = new 
            BufferedInputStream(in);
            bitmap = BitmapFactory.decodeStream(in);
            in.close();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }
        }
        return bitmap;
    }

    @Override
    protected void onPostExecute(Bitmap data) {

        imageView.setImageBitmap(data);
        try {
            try {
                saveImage(data);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // System.out.print(Log.e("Image Data",data.toString()));
    }

    private void saveImage(Bitmap data) throws FileNotFoundException, MalformedURLException {

        File createFolder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "test");

        File saveImage = new File(createFolder, "downloadedImage.jpg");
        try {
            OutputStream outputStream = new FileOutputStream(saveImage);
            data.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }




}

}
 }

Movie.class

public class Movie {


public String title;

public String getAlbumid() {
    return albumid;
}

public void setAlbumid(String albumid) {
    this.albumid = albumid;
}

public String getThumbnailurl() {
    return thumbnailurl;
}

public void setThumbnailurl(String thumbnailurl) {
    this.thumbnailurl = thumbnailurl;
}

public String albumid;
public String thumbnailurl;

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

String getImage() {
    return image;
}

public void setImage(String image) {
    this.image = image;
}

private int id;
private String image;

public  Movie() {

}

public Movie(String title, String image, int id) {
    this.title = title;
    this.image = image;
    this.id = id;
}

public String getTitle() {
    return title;
}

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



}
5
  • i have uploaded my complete code and you can see that i have already made an adapter which holds data which comes from the remote server but now i want something that would contain the sqlite database in order to populate that inside the recyclerview ... Commented Jun 14, 2018 at 7:19
  • I hope i have made sense Commented Jun 14, 2018 at 7:20
  • So what basically i need to do in the above code to get that stored data inside an adapter and then in the recyclerview Commented Jun 14, 2018 at 7:21
  • Everything is working fine till now , the data is populating from the remote server and it is also been saved in the sqlite database Commented Jun 14, 2018 at 7:22
  • Ok , let me do so i will reply you after Commented Jun 14, 2018 at 7:23

1 Answer 1

3

The Below Code is simple example of getting datas from Sqlite DB and showing it in a Recycler view

private List<Movie> movieList;
private RecyclerView mRecyclerView;
private MovieAdapter adapter;
private SQLiteHandler db;


     Cursor cursor = db.getUserDetails();

                    if (cursor.moveToFirst()) {
                        do {
                            movieList.add(new Movie(
                                    cursor.getInt(0),
                                    cursor.getString(1),
                                    cursor.getString(2),
                                    cursor.getString(3),
                                    cursor.getDouble(4)
                            ));
                        } while (cursor.moveToNext());


                        MovieAdapter adapter = new MovieAdapter(this, movieList);
                        mRecyclerView.setAdapter(adapter);
    }
Sign up to request clarification or add additional context in comments.

12 Comments

thanks for the answer, i will try it and tell u in sometime
Hey, where do i implement this code and what is the employeelist
Would you please elaborate the answer in my context
Please Check the Edited Answer@VipulSingh
do i need to post this code inside if-else block of the MainActivity
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.