MainActivity - Java, Students Info

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

import android.os.

Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {


private DatabaseHelper dbHelper;
private ListView listView;
private ArrayAdapter<Student> adapter;
private ArrayList<Student> students;

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

dbHelper = new DatabaseHelper(this);


listView = findViewById(R.id.listView);
students = new ArrayList<>();
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,
students);
listView.setAdapter(adapter);

Button addButton = findViewById(R.id.addButton);


addButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
addStudent();
}
});

populateStudentList();
}

private void addStudent() {


EditText rollNoEditText = findViewById(R.id.rollNoEditText);
EditText nameEditText = findViewById(R.id.nameEditText);

String rollNo = rollNoEditText.getText().toString();


String name = nameEditText.getText().toString();

if (rollNo.isEmpty() || name.isEmpty()) {
Toast.makeText(this, "Please enter roll no. and name",
Toast.LENGTH_SHORT).show();
return;
}

SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DatabaseHelper.STUDENT_COLUMN_ROLL_NO,
Integer.parseInt(rollNo));
values.put(DatabaseHelper.STUDENT_COLUMN_NAME, name);
long result = db.insert(DatabaseHelper.STUDENT_TABLE_NAME, null, values);

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

private void populateStudentList() {


students.clear();
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor cursor = db.query(DatabaseHelper.STUDENT_TABLE_NAME, null, null,
null, null, null, null);

while (cursor.moveToNext()) {
int rollNo =
cursor.getInt(cursor.getColumnIndex(DatabaseHelper.STUDENT_COLUMN_ROLL_NO));
String name =
cursor.getString(cursor.getColumnIndex(DatabaseHelper.STUDENT_COLUMN_NAME));
students.add(new Student(rollNo, name));
}

adapter.notifyDataSetChanged();
}
}

You might also like