Android SQLite - RecyclerView Web Images - Save Text ,Image URLs ,Retrieve


Android SQLite - RecyclerView Web Images - Save Text ,Image URLs ,Retrieve Tutorial.

Hello friends,today we basically discuss the following,in a practical was as we always do obviously:

  1. Download Images From the Web,in an image hosting site in my case, or anywhere for you.
  2. Save the image URLs and some text that we type in beautiful Material EditTexts. 3. Save these to our database : name and image url.Our SQLite database.
  3. Retrieve them from our database,our name and image url.
  4. Show them in our custom RecyclerView : images and text.
  5. We use the nice Picasso library to download and cache images automatically,both in memory and disk.

RecyclerView SQlite Images Project Structure RecyclerView SQlite Images Project Structure[/caption]

First make sure you add the internet permission as we shall be fetching images from online.Actually in this case I used Cloudinary to store my image. <uses-permission android:name="android.permission.INTERNET"/>    

We shall be using Picasso library to fetch our images from the cloud.So lets add its dependency in our build.gradle :  

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.3.0'
    compile 'com.android.support:design:23.3.0'
    compile 'com.android.support:cardview-v7:23.3.0'
    compile 'com.squareup.picasso:picasso:2.5.2'
}

PicassoClient.javaw

Then write a simple Picasso Client to fetch image given a url :  

package com.tutorials.hp.recyclersqliteimagestext.mPicasso;

import android.content.Context;
import android.widget.ImageView;

import com.squareup.picasso.Picasso;
import com.tutorials.hp.recyclersqliteimagestext.R;

public class PicassoClient {

    //DOWNLOAD AND CACHE IMG
    public static void loadImage(Context c,String url,ImageView img)
    {
        if(url != null && url.length()>0)
        {
            Picasso.with(c).load(url).placeholder(R.drawable.placeholder).into(img);
        }else {
            Picasso.with(c).load(R.drawable.placeholder).into(img);
        }
    }

}

Cloudinay.com Image Storage

Constants.java

Lets have all our SQLite database constants in one place.This makes them easy to reuse and in case we change something it gets reflected al over.  

package com.tutorials.hp.recyclersqliteimagestext.mDatabase;

public class Constants {
    //COLUMNS
    static final String ROW_ID="id";
    static final String NAME="name";
    static final String URL="url";

    //DB PROPERTIES
    static final String DB_NAME="cc_DB";
    static final String TB_NAME="cc_TB";
    static final int DB_VERSION=1;

    //CREATE TABLE STMT
    static final String CREATE_TB="CREATE TABLE cc_TB(id INTEGER PRIMARY KEY AUTOINCREMENT,"
            + "name TEXT NOT NULL,url TEXT NOT NULL);";

    //UPGRADE TB
    static final String DROP_TB="DROP TABLE IF EXISTS "+TB_NAME;

}

DBAdapter.java

Then here's our DBAdapter class that shall be responsible for SQlite CRUD :  

package com.tutorials.hp.recyclersqliteimagestext.mDatabase;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class DBAdapter {

    Context c;
    SQLiteDatabase db;
    DBHelper helper;

    public DBAdapter(Context c) {
        this.c = c;
        helper=new DBHelper(c);
    }
    //OPEN
    public DBAdapter openDB()
    {
        try {
            db=helper.getWritableDatabase();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return this;
    }

    //CLOSE
    public void closeDB()
    {
        try {
            helper.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //SAVE
    public long add(String name,String url)
    {
        try {
            ContentValues cv=new ContentValues();
            cv.put(Constants.NAME,name);
            cv.put(Constants.URL, url);

            db.insert(Constants.TB_NAME, Constants.ROW_ID, cv);

            return 1;

        } catch (Exception e) {
            e.printStackTrace();
        }

        return 0;
    }

    //RETRIEVE
    public Cursor getTVShows()
    {
        String[] columns={Constants.ROW_ID,Constants.NAME,Constants.URL};

        return db.query(Constants.TB_NAME,columns,null,null,null,null,null);
    }
}

Material Dialog Insert SQLite data

MyAdapter.java

We also have our RecyclerView adapter class to bind our dataset to RecyclerView.The class is a child of RecyclerView.Adapter :  

package com.tutorials.hp.recyclersqliteimagestext.mRecycler;

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

import com.tutorials.hp.recyclersqliteimagestext.R;
import com.tutorials.hp.recyclersqliteimagestext.mDataObject.TVShow;
import com.tutorials.hp.recyclersqliteimagestext.mPicasso.PicassoClient;

import java.util.ArrayList;

public class MyAdapter  extends RecyclerView.Adapter<MyHolder> {

   Context c;
    ArrayList<TVShow> tvShows;

    public MyAdapter(Context c, ArrayList<TVShow> tvShows) {
        this.c = c;
        this.tvShows = tvShows;
    }

    //INITIALIZE VH
    @Override
    public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.model,parent,false);
        MyHolder holder=new MyHolder(v);

        return holder;
    }

    //BIND DATA
    @Override
    public void onBindViewHolder(MyHolder holder, int position) {
         holder.nameTxt.setText(tvShows.get(position).getName());
        PicassoClient.loadImage(c,tvShows.get(position).getImageUrl(),holder.img);
    }

    //TOTAL NUM TVSHOWS
    @Override
    public int getItemCount() {
        return tvShows.size();
    }
}

MainActivity.java

Here's our MainActivity class :  

package com.tutorials.hp.recyclersqliteimagestext;

import android.app.Dialog;
import android.database.Cursor;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.tutorials.hp.recyclersqliteimagestext.mDataObject.TVShow;
import com.tutorials.hp.recyclersqliteimagestext.mDatabase.DBAdapter;
import com.tutorials.hp.recyclersqliteimagestext.mRecycler.MyAdapter;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    RecyclerView rv;
    MyAdapter adapter;
    EditText nameEditText,urlEditText;
    ArrayList<TVShow> tvShows=new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);

        //RECYCLERVIEW
        rv= (RecyclerView) findViewById(R.id.myRecyclerID);
        rv.setLayoutManager(new LinearLayoutManager(this));
        rv.setItemAnimator(new DefaultItemAnimator());

        //ADAPTER
        adapter=new MyAdapter(this,tvShows);

//        rv.setAdapter(adapter);

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                displayDialog();
            }
        });
    }

    private void displayDialog()
    {
        Dialog d=new Dialog(this);
        d.setTitle("Save To DB");
        d.setContentView(R.layout.dialog_layout);

        nameEditText= (EditText) d.findViewById(R.id.nameEditTxt);
        urlEditText= (EditText) d.findViewById(R.id.urlEditTxt);
        Button saveBtn= (Button) d.findViewById(R.id.saveBtn);
        Button retrieveBtn= (Button) d.findViewById(R.id.retrieveBtn);

        saveBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                save(nameEditText.getText().toString(),urlEditText.getText().toString());
            }
        });
        retrieveBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                 retrieve();
            }
        });

        d.show();

    }

    private void save(String name,String url)
    {
        DBAdapter db=new DBAdapter(this);
        db.openDB();
        long result=db.add(name,url);
        if(result==1)
        {
            nameEditText.setText("");
            urlEditText.setText("");

        }else
        {
            Snackbar.make(nameEditText,"Unable to save",Snackbar.LENGTH_SHORT).show();
        }

        db.closeDB();
    }

    private void retrieve()
    {
        tvShows.clear();
        DBAdapter db=new DBAdapter(this);
        db.openDB();
        Cursor c=db.getTVShows();
        while (c.moveToNext())
        {
            String name=c.getString(1);
            String url=c.getString(2);

            TVShow tv=new TVShow();
            tv.setName(name);
            tv.setImageUrl(url);

            tvShows.add(tv);
        }

        if(tvShows.size()>0)
        {
            rv.setAdapter(adapter);
        }

        db.closeDB();
    }

}

RecyclerView CardViews SQLite Images and Text

Download

Look all the source code is above just a download away.There some classes we have not included here but are in the source code.Download it,extract and import to your android studio.          

Below is the video tutorial.If you prefer more explanations and demo visit it.

No. Location Link
1. GitHub Direct Download)
2. GitHub Browse
3. YouTube Video Tutorial
4. YouTube Our YouTube Channel

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think


Previous Post Next Post