0

Hello I am making a teacher assistant app, the app uses SQLite database and allows teacher to take attendance by adding updating and removing students, the student ID is generated everytime a new student is added, now here is the thing how to display error message if the input from the teacher doesn't match a student ID in database instead of making my app crash.

StudentOperations

    package com.appcreator.isa.theteacherassistantapp.Database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.appcreator.isa.theteacherassistantapp.Model.Student;
import java.util.ArrayList;
import java.util.List;

public class StudentOperations
{
    public static final String LOGTAG = "STD_MNGMNT_SYS";

    SQLiteOpenHelper dbhandler;
    SQLiteDatabase database;

    private static final String[] allColumns = {
            StudentDatabaseHandler.COLUMN_SID,
            StudentDatabaseHandler.COLUMN_EID,
            StudentDatabaseHandler.COLUMN_FIRST_NAME,
            StudentDatabaseHandler.COLUMN_LAST_NAME,
            StudentDatabaseHandler.COLUMN_STUDY,
            StudentDatabaseHandler.COLUMN_ATTENDANCE

    };

    public StudentOperations(Context context)
    {
        dbhandler = new StudentDatabaseHandler(context);
    }

    public void open()
    {
        Log.i(LOGTAG,"Database Opened");
        database = dbhandler.getWritableDatabase();
    }
    public void close()
    {
        Log.i(LOGTAG, "Database Closed");
        dbhandler.close();
    }
    public Student addStudent(Student Student)
    {
        ContentValues values  = new ContentValues();
        values.put(StudentDatabaseHandler.COLUMN_EID, Student.getEnrlomentID());
        values.put(StudentDatabaseHandler.COLUMN_FIRST_NAME,Student.getFirstname());
        values.put(StudentDatabaseHandler.COLUMN_LAST_NAME,Student.getLastname());
        values.put(StudentDatabaseHandler.COLUMN_STUDY, Student.getStudy());
        values.put(StudentDatabaseHandler.COLUMN_ATTENDANCE, Student.getAttendance());
        long insertSID = database.insert(StudentDatabaseHandler.TABLE_STUDENTS,null,values);
        Student.setStudentID(insertSID);
        return Student;
    }

    // Getting single Student
    public Student getStudent(long id)
    {
        Cursor cursor = database.query(StudentDatabaseHandler.TABLE_STUDENTS,allColumns,StudentDatabaseHandler.COLUMN_SID + "=?",new String[]{String.valueOf(id)},null,null, null, null);
        if (cursor != null)
            cursor.moveToFirst();

        Student e = new Student(Long.parseLong(cursor.getString(0)),cursor.getString(1),cursor.getString(2),cursor.getString(3),cursor.getString(4),cursor.getString(5));
        // return Student
        return e;
    }

    public List<Student> getAllStudents()
    {
        Cursor cursor = database.query(StudentDatabaseHandler.TABLE_STUDENTS,allColumns,null,null,null, null, null);

        List<Student> students = new ArrayList<>();
        if(cursor.getCount() > 0)
        {
            while(cursor.moveToNext())
            {
                Student student = new Student();
                student.setStudentID(cursor.getLong(cursor.getColumnIndex(StudentDatabaseHandler.COLUMN_SID)));
                student.setEnrlomentID(cursor.getString(cursor.getColumnIndex(StudentDatabaseHandler.COLUMN_EID)));
                student.setFirstname(cursor.getString(cursor.getColumnIndex(StudentDatabaseHandler.COLUMN_FIRST_NAME)));
                student.setLastname(cursor.getString(cursor.getColumnIndex(StudentDatabaseHandler.COLUMN_LAST_NAME)));
                student.setStudy(cursor.getString(cursor.getColumnIndex(StudentDatabaseHandler.COLUMN_STUDY)));
                student.setAttendance(cursor.getString(cursor.getColumnIndex(StudentDatabaseHandler.COLUMN_ATTENDANCE)));
                students.add(student);
            }
        }
        // return All Students
        return students;
    }




    // Updating Student
    public int updateStudent(Student student)
    {
        ContentValues values = new ContentValues();
        values.put(StudentDatabaseHandler.COLUMN_EID, student.getEnrlomentID());
        values.put(StudentDatabaseHandler.COLUMN_FIRST_NAME, student.getFirstname());
        values.put(StudentDatabaseHandler.COLUMN_LAST_NAME, student.getLastname());
        values.put(StudentDatabaseHandler.COLUMN_STUDY, student.getStudy());
        values.put(StudentDatabaseHandler.COLUMN_ATTENDANCE, student.getAttendance());

        // updating row
        return database.update(StudentDatabaseHandler.TABLE_STUDENTS, values,
                StudentDatabaseHandler.COLUMN_SID + "=?",new String[] { String.valueOf(student.getStudentID())});
    }

    // Deleting Student
    public void removeStudent(Student student)
    {
        database.delete(StudentDatabaseHandler.TABLE_STUDENTS, StudentDatabaseHandler.COLUMN_SID + "=" + student.getStudentID(), null);
    }



}

The Main Activity

    package com.appcreator.isa.theteacherassistantapp;

import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.appcreator.isa.theteacherassistantapp.Database.StudentDatabaseHandler;
import com.appcreator.isa.theteacherassistantapp.Database.StudentOperations;
import com.appcreator.isa.theteacherassistantapp.Model.Student;

public class MainActivity extends AppCompatActivity
{

    private Button addStudentButton;
    private Button editStudentButton;
    private Button deleteStudentButton;

    private StudentOperations studentOps;
    private static final String EXTRA_STUDENT_ID = "TEMP";
    private static final String EXTRA_ADD_UPDATE = "TEMP";
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        addStudentButton = (Button) findViewById(R.id.button_add_student);
        editStudentButton = (Button) findViewById(R.id.button_edit_student);
        deleteStudentButton = (Button) findViewById(R.id.button_delete_student);




        addStudentButton.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Intent i = new Intent(MainActivity.this,AddUpdateStudent.class);
                i.putExtra(EXTRA_ADD_UPDATE, "Add");
                startActivity(i);
            }
        });
        editStudentButton.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v) {
                getStudentIDAndUpdateStudent();
            }
        });
        deleteStudentButton.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v) {
                getStudentIDAndRemoveStudent();
            }
        });

    }


    public void getStudentIDAndUpdateStudent()
    {

        LayoutInflater li = LayoutInflater.from(this);
        View getStudentIdView = li.inflate(R.layout.dialog_get_student_id, null);

        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        // set dialog_get_student_id.xml to alertdialog builder
        alertDialogBuilder.setView(getStudentIdView);

        final EditText userInput = (EditText) getStudentIdView.findViewById(R.id.editTextDialogUserInput);

        // set dialog message
        alertDialogBuilder
                .setCancelable(false)
                .setPositiveButton("OK",new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int id)
                    {
                        if (userInput.getText().toString().trim().length() > 0)
                        {
                                // get user input and set it to result
                                // edit text
                                Intent i = new Intent(MainActivity.this,AddUpdateStudent.class);
                                i.putExtra(EXTRA_ADD_UPDATE, "Update");
                                i.putExtra(EXTRA_STUDENT_ID, Long.parseLong(userInput.getText().toString()));
                                startActivity(i);
                        }
                        else
                        {
                            Toast.makeText(MainActivity.this, "Input is invalid", Toast.LENGTH_SHORT).show();
                        }
                    }
                }).create()
                .show();
    }


    public void getStudentIDAndRemoveStudent(){

        LayoutInflater li = LayoutInflater.from(this);
        View getStudentIdView = li.inflate(R.layout.dialog_get_student_id, null);

        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        // set dialog_get_student_id.xml to alertdialog builder
        alertDialogBuilder.setView(getStudentIdView);

        final EditText userInput = (EditText) getStudentIdView.findViewById(R.id.editTextDialogUserInput);

        // set dialog message
        alertDialogBuilder
                .setCancelable(false)
                .setPositiveButton("OK",new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int id)
                    {
                        if (userInput.getText().toString().trim().length() > 0)
                        {
                                // get user input and set it to result
                                // edit text
                                //studentOps = new StudentOperations(MainActivity.this); disabled because placing it here causes error
                                studentOps.removeStudent(studentOps.getStudent(Long.parseLong(userInput.getText().toString())));
                                Toast.makeText(MainActivity.this, "Student has been removed successfully", Toast.LENGTH_SHORT).show();
                        }
                        else
                        {
                            Toast.makeText(MainActivity.this, "Input is invalid", Toast.LENGTH_SHORT).show();
                        }
                    }
                }).create()
                .show();
    }
@Override
    protected void onResume()
    {
        super.onResume();
        studentOps = new StudentOperations(MainActivity.this);
        studentOps.open();
    }

    @Override
    protected void onPause()
    {
        super.onPause();
        studentOps.close();
    }
}

Logcat

10-17 03:42:09.750 11105-11105/com.appcreator.isa.theteacherassistantapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.appcreator.isa.theteacherassistantapp, PID: 11105
android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
    at android.database.AbstractCursor.checkPosition(AbstractCursor.java:460)
    at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
    at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
    at com.appcreator.isa.theteacherassistantapp.Database.StudentOperations.getStudent(StudentOperations.java:71)
    at com.appcreator.isa.theteacherassistantapp.MainActivity$5.onClick(MainActivity.java:144)
    at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:167)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:241)
    at android.app.ActivityThread.main(ActivityThread.java:6274)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

Updated Main Activity

    package com.appcreator.isa.theteacherassistantapp;

import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.appcreator.isa.theteacherassistantapp.Database.StudentDatabaseHandler;
import com.appcreator.isa.theteacherassistantapp.Database.StudentOperations;
import com.appcreator.isa.theteacherassistantapp.Model.Student;

public class MainActivity extends AppCompatActivity
{

    private Button addStudentButton;
    private Button editStudentButton;
    private Button deleteStudentButton;
    private StudentOperations studentOps;
    private static final String EXTRA_STUDENT_ID = "TEMP";
    private static final String EXTRA_ADD_UPDATE = "TEMP";

    private static final String TAG = "Student Exits";


    @Override
    protected void onCreate(Bundle savedInstanceState)
    {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        addStudentButton = (Button) findViewById(R.id.button_add_student);
        editStudentButton = (Button) findViewById(R.id.button_edit_student);
        deleteStudentButton = (Button) findViewById(R.id.button_delete_student);




        addStudentButton.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Intent i = new Intent(MainActivity.this,AddUpdateStudent.class);
                i.putExtra(EXTRA_ADD_UPDATE, "Add");
                startActivity(i);
            }
        });
        editStudentButton.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v) {
                getStudentIDAndUpdateStudent();
            }
        });
        deleteStudentButton.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v) {
                getStudentIDAndRemoveStudent();
            }
        });

    }

    public boolean check_existence(String stud_id)
    {
        SQLiteOpenHelper db = new StudentDatabaseHandler(this);
        SQLiteDatabase database = db.getWritableDatabase();

        String select = "SELECT * FROM students WHERE studentID =" + stud_id;

        Cursor c = database.rawQuery(select, null);

        if (c.moveToFirst())
        {
            Log.d(TAG,"Student Exists");
            return true;
        }

        if(c!=null)
        {
            c.close();
        }
        database.close();
        return false;
    }

    public void getStudentIDAndUpdateStudent()
    {

        LayoutInflater li = LayoutInflater.from(this);
        final View getStudentIdView = li.inflate(R.layout.dialog_get_student_id, null);

        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        // set dialog_get_student_id.xml to alertdialog builder
        alertDialogBuilder.setView(getStudentIdView);

        final EditText userInput = (EditText) getStudentIdView.findViewById(R.id.editTextDialogUserInput);

        // set dialog message
        alertDialogBuilder
                .setCancelable(false)
                .setPositiveButton("OK",new DialogInterface.OnClickListener()
                {
                    public void onClick(DialogInterface dialog,int id)
                    {
                        if (userInput.getText().toString().isEmpty())
                        {
                            Toast.makeText(MainActivity.this, "Input is invalid", Toast.LENGTH_SHORT).show();
                        }
                        else
                        {
                                // get user input and set it to result
                                // edit text
                                if (check_existence(userInput.getText().toString()) == true)
                                {
                                    Intent i = new Intent(MainActivity.this,AddUpdateStudent.class);
                                    i.putExtra(EXTRA_ADD_UPDATE, "Update");
                                    i.putExtra(EXTRA_STUDENT_ID, Long.parseLong(userInput.getText().toString()));
                                    startActivity(i);
                                }
                                else
                                {
                                    Toast.makeText(MainActivity.this, "Input is invalid", Toast.LENGTH_SHORT).show();
                                }

                        }
                    }
                }).create()
                .show();
    }


    public void getStudentIDAndRemoveStudent()
    {

        LayoutInflater li = LayoutInflater.from(this);
        View getStudentIdView = li.inflate(R.layout.dialog_get_student_id, null);

        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        // set dialog_get_student_id.xml to alertdialog builder
        alertDialogBuilder.setView(getStudentIdView);

        final EditText userInput = (EditText) getStudentIdView.findViewById(R.id.editTextDialogUserInput);


        // set dialog message
        alertDialogBuilder
                .setCancelable(false)
                .setPositiveButton("OK",new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int id)
                    {
                        if (userInput.getText().toString().isEmpty())
                        {
                            Toast.makeText(MainActivity.this, "Invalid Input", Toast.LENGTH_SHORT).show();
                        }
                        else
                        {
                            if(check_existence(userInput.getText().toString()) == true)
                            {
                                // get user input and set it to result
                                // edit text
                                //studentOps = new StudentOperations(MainActivity.this); disabled because placing it here causes error
                                studentOps.removeStudent(studentOps.getStudent(Long.parseLong(userInput.getText().toString())));
                                Toast.makeText(MainActivity.this, "Student has been removed successfully", Toast.LENGTH_SHORT).show();
                            }
                            else
                            {
                                Toast.makeText(MainActivity.this, "Invalid Input" , Toast.LENGTH_SHORT).show();
                            }
                        }
                    }
                }).create()
                .show();
    }



    @Override
    protected void onResume()
    {
        super.onResume();
        studentOps = new StudentOperations(MainActivity.this);
        studentOps.open();
    }

    @Override
    protected void onPause()
    {
        super.onPause();
        studentOps.close();
    }
}
Isa
  • 46
  • 4
  • Simply you can get all the data stored in databse an comper it to edittext value – Vinesh Chauhan Oct 16 '18 at 04:09
  • if value doesnt mathc then show toast message with id not found or somthing else – Vinesh Chauhan Oct 16 '18 at 04:09
  • @Isa did my answer solve your problem? – PradyumanDixit Oct 16 '18 at 16:43
  • @PradyumanDixit I am having trouble with SQLiteDatabase db = this.getWritableDatabase(); it gives cannot resolve method getWritableDatabase(); Please bear in mind I am still self learning and that I am a beginner :S – Isa Oct 16 '18 at 17:55
  • @PradyumanDixit I need to implement your code inside the Student Operations ? then create a verification method inside the main activity then on click of the button call the verification method ? – Isa Oct 16 '18 at 18:27
  • @Isa, you just have to make this method and call it with the student Id you want to check in your database and if you get false, student Id is NOT present in the database and if the method returns true, it is present in your database. – PradyumanDixit Oct 17 '18 at 03:41
  • @PradyumanDixit Ok buddy I fixed it here is updated code above thanks ! – Isa Oct 17 '18 at 16:12
  • Great, glad to help. Cheers! :) – PradyumanDixit Oct 17 '18 at 16:29

1 Answers1

1

You can make a new method to do the work with boolean data type and if it returns false, you might want to display it to the user via Toast or anything like that.

It may look like this in code:

public boolean check_existence(String stud_id) {

        SQLiteDatabase db = this.getWritableDatabase();
        String select = "SELECT * FROM table_name WHERE column_name ='" + stud_id;

        Cursor c = db.rawQuery(select, null);

        if (c.moveToFirst()) {

            Log.d(TAG,"User exits");
            return true;
        }

        if(c!=null) {

            c.close();
        }
        db.close();
        return false;
}

You can now just call the method and if it returns false you may just display what you want using Toast.

PradyumanDixit
  • 2,372
  • 2
  • 12
  • 20
  • I can't get your code to work I am having trouble with SQLiteDatabase db = this.getWritableDatabase(); It says cannot resolve method getWritableDatabase(); – Isa Oct 17 '18 at 00:54
  • @Isa to know more about `getWritableDatabase()` please refer this answer https://stackoverflow.com/questions/6597277/getwritabledatabase-vs-getreadabledatabase – PradyumanDixit Oct 17 '18 at 03:40