Android SQLite Database - ListView Web Images - Save Text,Image URLs,Load.

Working with SQLite and images from the web.

Now people we discuss Android SQLite database and Internet images .Our purpose is simple : get image urls from the web and maybe some text,save them in SQlite database,Load the images from the internet,of course URLs from SQlite database. Basically this is what we do here :

  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 ListView: images and text. 6.We use the nice Picasso library to download and cache images automatically,both in memory and disk.  

What You Will Leanr From This Tutorial

  1. How to save both text and web image urls in SQLite database.
  2. How to retrieve text and image urls from sqlite database and render them in custom listview with text and images.
  3. Custom ListView with CardViews filled from SQLite.
  4. How to use SQLiteDatabase and SQLiteOpenHelper classes.
  5. How to use Picasso to load and cache images with urls coming from SQLite.

SQLite Images Project Structure

Obviously we are loading images from online so we need to add internet permission in our androidmanifest.xml :   <uses-permission android:name="android.permission.INTERNET"/>  

PicassoClient

We shall be using Picasso to download our images,so lets write a basic Picasso client :  

package com.tutorials.hp.listviewsqliteimages.mPicasso;

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

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

public class PicassoClient {

    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);
        }
    }

}

Constants

  We have three database classes,Constants,DBHelper and DBAdapter. Constants to hold SQLite database constants.DBHelperr to upgrade our SQLite database table and DBAdapter to perform CRUD SQlite operations. Here's our Constants :  

package com.tutorials.hp.listviewsqliteimages.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="dd_DB";
    static final String TB_NAME="dd_TB";
    static final int DB_VERSION=1;

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

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

}

Cloudinary Image Source

DBAdapter

Then here's our DBAdapter :  

package com.tutorials.hp.listviewsqliteimages.mDatabase;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
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 DB
    public DBAdapter openDB()
    {
        try {
            db=helper.getWritableDatabase();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return this;
    }

    //CLOSE DB
    public void closeDB()
    {
        try {
            helper.close();
        } catch (SQLException 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 Data

CustomAdapter

We have our CustomAdapter class that will bind data to ListView :  

package com.tutorials.hp.listviewsqliteimages.mListView;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

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

import java.util.ArrayList;

public class CustomAdapter extends BaseAdapter {

    Context c;
    ArrayList<TVShow> tvShows;
    LayoutInflater inflater;

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

    @Override
    public int getCount() {
        return tvShows.size();
    }

    @Override
    public Object getItem(int position) {
        return tvShows.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if(inflater==null)
        {
           inflater= (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        if(convertView==null)
        {
            convertView=inflater.inflate(R.layout.model,parent,false);
        }

        //BIND DATA
        MyHolder holder=new MyHolder(convertView);
        holder.nameTxt.setText(tvShows.get(position).getName());
        PicassoClient.loadImage(c,tvShows.get(position).getImageUrl(),holder.img);

        return convertView;
    }
}

MainActivity

  Here's our MainActivity class :  

package com.tutorials.hp.listviewsqliteimages;

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.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import com.tutorials.hp.listviewsqliteimages.mDataObject.TVShow;
import com.tutorials.hp.listviewsqliteimages.mDatabase.DBAdapter;
import com.tutorials.hp.listviewsqliteimages.mListView.CustomAdapter;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    ListView lv;
    CustomAdapter 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);

        lv= (ListView) findViewById(R.id.lv);
        adapter=new CustomAdapter(this,tvShows);

        //lv.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();
        }

        //REFRESH
        retrieve();
    }

    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);
        }

        db.closeDB();
        if(tvShows.size()>0)
        {
            lv.setAdapter(adapter);
        }

    }

}

SQLite ListView CardView Images and Text

Hey,look,everything is in the Source code download above.Some classes like ViewHolder,TVShow,DBHelper are there.Just download it and import to your android studio.    

If you prefer more explanations as well as well as demo please check the below video tutorial.Please don't mind the audio quality. http://www.youtube.com/watch?v=7zipXNhcV-o

Download

Also check our video tutorial it's more detailed and explained in step by step and will guide you through how setup our free Cloudinary account where we store images. However note that it is not mandatory to use Cloud services to store images. Your images can come from anywhere,

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