SoFunction
Updated on 2025-04-07

How to use SQLite in Android Studio

Introduction to sqlite

I am writing a small Android project recently. I used the sqlite that comes with Android during the development of the app. This article mainly introduces SQLite image operations. Other operations such as text storage are the same as ordinary databases. As we all know, SQLite is a light database. Let’s briefly introduce SQLite to lay the foundation for the subsequent situation. Those who have knowledge can skip this part:

SQLite is a lightweight, embedded relational database management system. It provides a set of programming interfaces in the form of a library that can run on various operating systems, such as Windows, Linux, Mac OS, etc., and is widely used in mobile devices and embedded systems. SQLite's data is stored in a single file and does not require a dedicated server process or background process. It supports most SQL syntax and can handle the data storage and management needs of most small and medium-sized applications.

The main advantages of SQLite are as follows:

Easy to use: SQLite is very easy to install and use, you only need to introduce a single library file to start developing using the API it provides.

Small and flexible: Because SQLite is designed to be a lightweight database management system, its library files are very small and suitable for use in embedded devices and mobile terminals.

Zero configuration: SQLite does not require any special configuration or installation process. Users only need to introduce their API into the program to use, greatly simplifying the deployment and maintenance work.

Strong compatibility: SQLite supports most standard SQL syntax, and can also use custom functions and AGGREGATE aggregation functions through plug-ins or extensions.

The disadvantages of SQLite are also quite obvious:

Not suitable for large-scale data storage: Because SQLite's data is stored in a single file, it is not suitable for handling large-scale data storage needs, and the performance of handling large-scale data queries and update operations may be poor.

Difficult to extend: SQLite's features and limitations are fixed in the library file, so it is difficult to refactor or extend it, and cannot meet the needs of highly customized.

In general, SQLite is a very lightweight database management system, which is very suitable for small application development and mobile development, but it is not effective in application scenarios that deal with large-scale data storage and high concurrent operations.

Insert picture

Going to the topic, when using sqlite, I encountered the problem of failing to insert pictures. After checking a lot of information, I realized that sqlite cannot be directly stored in .jpg and .png, and needs to be stored in sqlite in binary form. This is why the above mentioned sqlite is not suitable for large-scale data storage and is a lightweight database. I'll use the following code to explain further

Methods to be used and some noun descriptions:

Bitmap is one of the most important classes of image processing in Android system. Use it to obtain image file information, perform image cutting, rotation, scaling and other operations, and can save image files in a specified format.

(?,?) This method with two parameters: the first parameter is the object containing the bitmap resource file you want to load (usually it will be OK if you write it as getResources()); the second time you need to load the bitmap resource ID.

Bitmap introduction: The Bitmap format cannot be said to be a very common format (from the perspective of our daily usage frequency, it is far inferior to .jpg .png .gif, etc.), because its data is not compressed, or at most it only uses RLE, run-length encoding for mild lossless data compression.

This is a well-written call statement and method. Insertdb() is a well-written method. You can add a little modification to your Activity page or fragment page. The call statement is as shown in the figure

//Your picture exists in android studio and is int type//The id stored in the database is designed when defining the database by yourself. You can refer to my database code 
insertdb( .Your picture name,Saved in the databaseid);
 
//s refers to your image resource, int type, that is, your image nameprivate void insertdb(int s,int id){
 
        //Convert your image resources into bitmaps        Bitmap bitmap = ((), s);
 
        //Mysql is a database class written by itself and needs to be written by itself. The following two sentences are to instantiate a sqlite database object        Mysql mySqlLite = new Mysql(this);
        SQLiteDatabase database = ();
        
        //Set a size to compress image files        int size = () * () * 4;
 
        //ByteArrayOutputStream (byte array output stream) class that writes byte type data, belongs to the memory operation stream        ByteArrayOutputStream baos= new ByteArrayOutputStream(size);
 
        //Compress bitmap bitmap        (, 100, baos);
 
        //Define an array of byte type bytedata to store the byte array converted into byte byte stream bytes        byte[] bytedata = ();
 
        //The sql statement is written according to your needs, do not copy it according to the        ("update Your table name set image=? where _id=?",new Object[] {bytedata,id});
    }

//
package Your bag name;
 
import ;
import ;
import ;
import ;
 
 
public class Mysql extends SQLiteOpenHelper {
 
    private static final String DB_NAME="";
    private static final int DB_VERSION=1;
 
    public Mysql(Context context){
        super(context,DB_NAME,null,DB_VERSION);
    }
 
    @Override
    public void onCreate(SQLiteDatabase db) {
        (
                "CREATE TABLE INFORMATION(" +
                        "_id INTEGER PRIMARY KEY AUTOINCREMENT,"
                        +"NAME TEXT,"
                        +"TITLE TEXT,"
                        +"image blob,"
                        +"TEXTS TEXT);"
        );
 
    
        insertTest(db, "programmer", "Programmer.exe is not responding","Have a nice day");
        insertTest(db, "programmer", "Stopped","Never use sqlite in the next life");
 
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
 
    }
 
    public void insertTest(SQLiteDatabase db,String name,String title,String texts){
        ContentValues value=new ContentValues();
        ("NAME",name);
        ("TITLE",title);
        ("TEXTS",texts);
        ("INFORMTION",null,value);
    }
}

Read pictures

I have inserted pictures into the database, and now I can read the pictures. Here I am using a cursor

package Your bag name;
 
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
 
public class SearchResult extends AppCompatActivity implements  {
 
    //Define cursor    private Cursor cursor;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        (savedInstanceState);
        setContentView(.activity_search_result);
 
        Intent rit = getIntent();
        String text = ("key");
 
        ListView listview=findViewById();
 
        //The helper and manager are two old friends, instantiating the database object        SQLiteOpenHelper helper=new Mydb(this);
        SQLiteDatabase db=();
 
        //Cursor reads the database        cursor=("select * from KNOW where name like '%"+text+"%'",null);
        ();
 
        //The database's simple cursor adapter is a bridge to fill the content into the template.        SimpleCursorAdapter mAdapter=new SimpleCursorAdapter(this,.item_list,
                cursor,new String[]{"NAME","image","TITLE"},new int[]{.iv1,.iv2,.iv3},0);//The name of your own xml component.iv1,.iv2, and.iv3 corresponds to the database field names "NAME", "image", "TITLE". Check more usage by yourself 
        //The simple cursor adapter above cannot read pictures. Here comes the point, ViewBinder is used here         binder=new () {
            @Override
            public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
 
        //Judge whether it is an ImageView. This judgment is very critical. You can press ctr to find the ViewBinder in detail, and go to the document to read it. Don’t look for other information. If you really want to understand it, you must read it!                if (view instanceof ImageView) {
                    ImageView imageView = (ImageView) view;
 
           (readImageFromDb((("_id"))));//Configure the image corresponding to the id for imageView                    return true;
                }
                return false;
            }
        };
 
        //Configure ViewBinder        (binder);
        //Configure the adapter        (mAdapter);
        //Click the listener        (this);
 
   }
 
    //
    @SuppressLint("Range")
    private Bitmap readImage(String id) {
 
    //As for the reason why it needs to be instantiated, it is because SQLite cannot be used at the same time, and the terminology is not professional. In short, it needs to be re-instified, otherwise it will report an error        Mysql mySqlLite2 = new Mysql(this);
        SQLiteDatabase database2 = ();
 
        Bitmap image= null;
        byte[] bytes;
        Cursor cursor = ( "SELECT * FROM INFORMATION WHERE _id = ?", new String[]{id});
        if (()) {
            if ((bytes = (("image"))) != null) {
                image= (bytes, 0, );
            }
        }
        ();
        return image;
    }
 
 
    //listview click event    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        // Write a click event here, I use it to pass the value and jump to the page        Intent it=new Intent(this, );
        ("ID",(int)id-1);
        startActivity(it);
        finish();
    }
}

Problems that may arise

The key here! There is only one big problem I have encountered at present, that is, the row is too large, which makes the database unable to be read. The reason is that the picture I put in is too large, about 1MB, and the size of my other pictures is generally around 200KB to 500KB. The 1MB picture is too large, which causes the binary data stream converted by the bitmap to be too large, and the database cannot be read at once, which will cause the program to crash directly. The solution is not to store too large pictures. After all, it is just a "child-smashing". SQLite is a lightweight database. Don't store too large pictures.

Summarize

I encountered many problems during the process of writing code. Thank you to all the Internet experts for sending reference materials. Because I have referenced a lot of materials and documents, and because I wrote it too fast at that time, I didn’t remember the blog and articles of the big guy. I deeply apologize. After the subsequent improvement of this project, I will also post it to GitHub to make an open source small project for your reference. I am currently a sophomore program student, and I hope to grow and move forward with you.

This is the end of this article about how to use SQLite in Android Studio. For more related content on using SQLite in Android Studio, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!