Click here to Skip to main content
14,739,784 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I'm new to android and not much aware about it. I need to connect the android studio to SQLite , in the android studio i made an app that take a text field and insert the data SQLite ,I wrote the following code in the main activity

 package com.example.helloworld;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;




import java.text.BreakIterator;

public class MainActivity extends AppCompatActivity {

    BreakIterator lst = null;        BreakIterator studentid = null;        BreakIterator studentname = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void loadStudents(View view) {
        MyDBHandler dbHandler = new MyDBHandler(this, null, null, 1);

        lst.setText(dbHandler.loadHandler());
        studentid.setText("");
        studentname.setText("");
    }

    public void addStudent(View view) {
        MyDBHandler dbHandler = new MyDBHandler(this, null, null, 1);
        int id = Integer.parseInt(studentid.getText().toString());
        String name = studentname.getText().toString();
        Student student = new Student(id,name);
        dbHandler.addHandler(student);
        studentid.setText("");
        studentname.setText("");

    }

    public void findStudent(View view) {
        MyDBHandler dbHandler = new MyDBHandler(this, null, null, 1);
        Student student = dbHandler.findHandler(studentname.getText().toString());
        if (student != null) {
            lst.setText(student.getID() + " " + student.getStudentName() + System.getProperty("line.separator"));
            // lst  = findViewById(R.id.lst);
            studentid.setText("");
            studentname.setText("");
        }else {
            lst.setText("No Match Found");
            studentid.setText("");
            studentname.setText("");
        }
    }


    public void removeStudent(View view) {
        MyDBHandler dbHandler = new MyDBHandler(this, null, null, 1);
        Boolean result = dbHandler.deleteHandler(Integer.parseInt(studentid.getText().toString()));
        if (result) {
            studentid.setText("");
            studentname.setText("");
            lst.setText("Record Deleted");
        } else
            studentid.setText("No Match Found");
    }

    public void updateStudent(View view) {
        MyDBHandler dbHandler = new MyDBHandler(this, null, null, 1);
        Boolean result = dbHandler.updateHandler(Integer.parseInt(studentid.getText().toString()), studentname.getText().toString());
        if (result) {
            studentid.setText("");
            studentname.setText("");
            lst.setText("Record Updated");
        } else
            studentid.setText("No Match Found");
    }
}
`

**and this is the db adapter**

package com.example.sqliteoperations;

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


public class myDbAdapter {
    myDbHelper myhelper;
    public myDbAdapter(Context context)
    {
        myhelper = new myDbHelper(context);
    }

    public long insertData(String name, String pass)
    {
        SQLiteDatabase dbb = myhelper.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(myDbHelper.NAME, name);
        contentValues.put(myDbHelper.MyPASSWORD, pass);
        long id = dbb.insert(myDbHelper.TABLE_NAME, null , contentValues);
        return id;
    }

    public String getData()
    {
        SQLiteDatabase db = myhelper.getWritableDatabase();
        String[] columns = {myDbHelper.UID,myDbHelper.NAME,myDbHelper.MyPASSWORD};
        Cursor cursor =db.query(myDbHelper.TABLE_NAME,columns,null,null,null,null,null);
        StringBuffer buffer= new StringBuffer();
        while (cursor.moveToNext())
        {
            int cid =cursor.getInt(cursor.getColumnIndex(myDbHelper.UID));
            String name =cursor.getString(cursor.getColumnIndex(myDbHelper.NAME));
            String  password =cursor.getString(cursor.getColumnIndex(myDbHelper.MyPASSWORD));
            buffer.append(cid+ "   " + name + "   " + password +" \n");
        }
        return buffer.toString();
    }

    public  int delete(String uname)
    {
        SQLiteDatabase db = myhelper.getWritableDatabase();
        String[] whereArgs ={uname};

        int count =db.delete(myDbHelper.TABLE_NAME ,myDbHelper.NAME+" = ?",whereArgs);
        return  count;
    }

    public int updateName(String oldName , String newName)
    {
        SQLiteDatabase db = myhelper.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(myDbHelper.NAME,newName);
        String[] whereArgs= {oldName};
        int count =db.update(myDbHelper.TABLE_NAME,contentValues, myDbHelper.NAME+" = ?",whereArgs );
        return count;
    }

    static class myDbHelper extends SQLiteOpenHelper
    {
        private static final String DATABASE_NAME = "myDatabase";    // Database Name
        private static final String TABLE_NAME = "myTable";   // Table Name
        private static final int DATABASE_Version = 1;   // Database Version
        private static final String UID="_id";     // Column I (Primary Key)
        private static final String NAME = "Name";    //Column II
        private static final String MyPASSWORD= "Password";    // Column III
        private static final String CREATE_TABLE = "CREATE TABLE "+TABLE_NAME+
                " ("+UID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+NAME+" VARCHAR(255) ,"+ MyPASSWORD+" VARCHAR(225));";
        private static final String DROP_TABLE ="DROP TABLE IF EXISTS "+TABLE_NAME;
        private Context context;

        public myDbHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_Version);
            this.context=context;
        }

        public void onCreate(SQLiteDatabase db) {

            try {
                db.execSQL(CREATE_TABLE);
            } catch (Exception e) {
                Message.message(context,""+e);
            }
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            try {
                Message.message(context,"OnUpgrade");
                db.execSQL(DROP_TABLE);
                onCreate(db);
            }catch (Exception e) {
                Message.message(context,""+e);
            }
        }
    }
}

**and this is student class**

   

package com.example.helloworld;

public class Student {
    // fields
    private int studentID;
    private String studentName;
    // constructors
    public Student() {}
    public Student(int id, String studentname){
        this.studentID=id;
        this.studentName = studentname;
    }
    // properties
    public void setlD(int id){
        this.studentID=id;
    }
    public int getID(){
        return this.studentID;
    }
    public void setStudentName(String studentname){
        this.studentName = studentname;
    }
    public String getStudentName(){
        return this.studentName;
    }
}   


the thing is when i run the app its work but when i insert in the text field and press on of the button the app will crash and its will not transfer the data to SQLite

What I have tried:

https://stackoverflow.com/questions/64470143/android-crash-when-connecting-to-sqlite[^]
Posted
Updated 7-Nov-20 6:55am
v2
Comments
David Crow 21-Oct-20 23:10pm
   
"...but when i insert in the text field and press on of the button..."

What text field? What button? What code is being executed as the result of the "press?"

"...the app will crash..."

Where? Is an exception being thrown?

After the "press", have you stepped through the code using the debugger?
Richard MacCutchan 7-Nov-20 11:35am
   
"I'm new to android and not much aware about it."
And yet you managed to write a fairly complex application. Or was this code written by someone else?

1 solution

The only thing that would happen in the app you've shown is that the Main Activity would load and display something due to the OnCreate being called:

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


Since OnCreate() only calls the setContentView() and nothing else, then none of the methods you show below that are even called.

So either there is code missing or the app is crashing from something completely unrelated.

You need to look in the Logcat and see what errors you see. The crash will tell you exactly what Exception occurred and which line of your code it happened on.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900