Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

import android.database.sqlite.

SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

private EditText nameEditText, ageEditText, emailEditText;


private Button addButton;

private SQLiteDatabase database;


private SQLiteOpenHelper dbHelper;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Initialize the views


nameEditText = findViewById(R.id.nameEditText);
ageEditText = findViewById(R.id.ageEditText);
emailEditText = findViewById(R.id.emailEditText);
addButton = findViewById(R.id.addButton);

// Create an instance of your SQLiteOpenHelper class


dbHelper = new MyDatabaseHelper(this);

// Set an onClickListener for the button


addButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Get the data from the input fields
String name = nameEditText.getText().toString();
String age = ageEditText.getText().toString();
String email = emailEditText.getText().toString();

// Open the database in write mode


database = dbHelper.getWritableDatabase();

// Insert the data into the table


ContentValues values = new ContentValues();
values.put("name", name);
values.put("age", age);
values.put("email", email);
long result = database.insert("your_table", null, values);

// Close the database


database.close();

// Clear the input fields


nameEditText.setText("");
ageEditText.setText("");
emailEditText.setText("");

// Show a toast message indicating success or failure


if (result != -1) {
Toast.makeText(MainActivity.this, "Data added successfully!",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Failed to add data!",
Toast.LENGTH_SHORT).show();
}
}
});
}

// Your SQLiteOpenHelper class


public class MyDatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "your_database.db";
private static final int DATABASE_VERSION = 1;

public MyDatabaseHelper(Context context) {


super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
// Create your table here
String createTableQuery = "CREATE TABLE your_table (id INTEGER PRIMARY
KEY AUTOINCREMENT, name TEXT, age INTEGER, email TEXT)";
db.execSQL(createTableQuery);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Handle database upgrade if needed
db.execSQL("DROP TABLE IF EXISTS your_table");
onCreate(db);
}
}
}

You might also like