Android SQLite : ListView Web Images – Save Text,Image URLs,Load

Android SQLite : ListView Web Images – Save Text,Image URLs,Load







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.
4.Retrieve them from our database,our name and image url.
5. 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.

 

SQLite Images Project Structure

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"/>

 

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;
/**
 * Created by Oclemmy on 4/29/2016 for ProgrammingWizards Channel and http://www.Camposha.com.
 */
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);
        }
    }
}

 

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;
/**
 * Created by Oclemmy on 4/29/2016 for ProgrammingWizards Channel and http://www.Camposha.com.
 */
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

Cloudinary Image Source

 

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;
/**
 * Created by Oclemmy on 4/29/2016 for ProgrammingWizards Channel and http://www.Camposha.com.
 */
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

Material Dialog Insert Data

 

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;
/**
 * Created by Oclemmy on 4/29/2016 for ProgrammingWizards Channel and http://www.Camposha.com.
 */
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;
    }
}

 

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

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.

Android SQLite Database 05 : ListView Web Images - Save Text and Image URLs,Load them

 

 



  • saravanan says:

    It’s really easy to understand but I need a help here, I need android code for I am having some URL in ArrayList and I have to loaded in list view and image URL number will increase or decrease dynamically. I can download one image but don’t know how to download multiple images.

    the code i used is private class LoadImage extends AsyncTask {
    @Override
    protected void onPreExecute() {
    super.onPreExecute();
    pDialog = new ProgressDialog(CpanelFinalAnswer.this);
    pDialog.setMessage(“Loading Image ….”);
    pDialog.show();
    }
    protected Bitmap doInBackground(String… args) {
    try {
    bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).getContent());
    } catch (Exception e) {
    e.printStackTrace();
    }
    return bitmap;
    }
    protected void onPostExecute(Bitmap image) {
    if(image != null){
    img.setImageBitmap(image);
    pDialog.dismiss();
    }else{
    pDialog.dismiss();
    Toast.makeText(CpanelFinalAnswer.this, “Image Does Not exist or Network Error”, Toast.LENGTH_SHORT).show();
    }

    //loadNext();
    }
    }

Leave a Reply

Your email address will not be published. Required fields are marked *

five × 5 =

COMMENTS