To insert data into an SQLite database in Android, you can use the SQLiteDatabase
class and the ContentValues
class.
Here is an example of how to insert data into an SQLite database in Android:
import android.content.ContentValues; import android.database.sqlite.SQLiteDatabase; public class MainActivity extends AppCompatActivity { private static final String TABLE_NAME = "users"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Open the database SQLiteDatabase db = openOrCreateDatabase("app.db", MODE_PRIVATE, null); // Create the table if it doesn't exist db.execSQL("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)"); // Create a new ContentValues object ContentValues values = new ContentValues(); // Insert data into the table values.put("id", 1); values.put("name", "John Smith"); values.put("age", 30); long rowId = db.insert(TABLE_NAME, null, values); // Close the database db.close(); } }
In this example, the SQLiteDatabase
class is used to open or create an SQLite database. The execSQL()
method is used to create a table if it doesn't exist, and the ContentValues
class is used to store the data to be inserted. The insert()
method is then used to insert the data into the table.
For more information on working with SQLite databases in Android, you can refer to the Android documentation.