0

My Code didn't show any error in Android Studio but when i execute program it show me message that "Unfortunate this app stop working" why? The App Crash during Execution only when SQLite code is written in Backend else it's working, Why?

When I remove this Line of Code SQLiteDatabase db = this.getWritableDatabase(); Then during execution app didn't crash but the all code is useless without this line.

Main Activity

package com.example.nooh.sqlite_deletevalues;

import android.database.Cursor;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
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 {

    EditText editid, editname, editsurname, editmarks;
    Button btn_insert;
    Button btn_viewdata;
    Button btn_update;
    Button btn_delete;
    DatabaseHelper mydb;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mydb = new DatabaseHelper(this);

        editid = (EditText) findViewById(R.id.editText4);
        editname = (EditText) findViewById(R.id.editText);
        editsurname = (EditText) findViewById(R.id.editText2);
        editmarks = (EditText) findViewById(R.id.editText3);
        btn_insert = (Button) findViewById(R.id.button);
        btn_viewdata = (Button) findViewById(R.id.button2);
        btn_update = (Button) findViewById(R.id.button3);
        btn_delete = (Button) findViewById(R.id.button4);
        AddData();
        viewAll();
        updateData();
        DeleteData();
    }

    public void AddData() {

        btn_insert.setOnClickListener(

                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        boolean isInserted = mydb.insertData(
                                editname.getText().toString(),
                                editsurname.getText().toString(),
                                editmarks.getText().toString()
                        );

                        if (isInserted == true)
                            Toast.makeText(MainActivity.this, "Data Inserted", Toast.LENGTH_SHORT).show();
                        else
                            Toast.makeText(MainActivity.this, "Data Not Inserted", Toast.LENGTH_SHORT).show();


                    }

                }

        );

    }
    public void viewAll(){

        btn_viewdata.setOnClickListener(

                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        Cursor res = mydb.getAllData();

                        if(res.getCount() == 0)
                        {
                            // Show Message
                            showMessage("Error", "There is no Data");
                            return;
                        }

                        StringBuffer buffer = new StringBuffer();
                        while(res.moveToNext())
                        {
                            buffer.append("Id : " + res.getString(0) + "/n");
                            buffer.append("Name : " + res.getString(1) + "/n");
                            buffer.append("SurName : " + res.getString(2) + "/n");
                            buffer.append("Marks : " + res.getString(3) + "/n/n");
                        }

                        // Show All Data
                        showMessage("Data", buffer.toString());
                    }
                }

        );

    }

    public void showMessage (String title, String message)
    {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setCancelable(true);
        builder.setTitle(title);
        builder.setMessage(message);
        builder.show();
    }

    public void updateData(){

        btn_update.setOnClickListener(

                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        Boolean isUpdated = mydb.updateData(editid.getText().toString(),
                                editname.getText().toString(),
                                editsurname.getText().toString(),
                                editmarks.getText().toString()
                        );
                        if(isUpdated == true)
                            Toast.makeText(MainActivity.this, "Data Updated", Toast.LENGTH_SHORT).show();
                        else
                            Toast.makeText(MainActivity.this, "Data Not Updated", Toast.LENGTH_SHORT).show();
                    }
                }

        );

    }

    public void DeleteData(){

        btn_delete.setOnClickListener(

                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        Integer deleterows = mydb.deleteData("editText4");
                        if(deleterows > 0)
                            Toast.makeText(MainActivity.this, "Data Deleted", Toast.LENGTH_SHORT).show();
                        else
                            Toast.makeText(MainActivity.this, "Data Not Deleted", Toast.LENGTH_SHORT).show();
                }


    }
        );
}

}

New Class name "DatabaseHelper.java"

package com.example.nooh.sqlite_deletevalues;


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

public class DatabaseHelper extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "Student.db";
    public static final String TABLE_NAME = "Student_table";
    public static final String COL_1 = "ID";
    public static final String COL_2 = "NAME";
    public static final String COL_3 = "SURNAME";
    public static final String COL_4 = "MARKS";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL("create table " + TABLE_NAME + "(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, SURNAME TEXT, MARKS NUMBER)");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXIST" + TABLE_NAME);
        onCreate(db);
    }

    public Boolean insertData(String name, String surname, String marks) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL_2, name);
        contentValues.put(COL_3, surname);
        contentValues.put(COL_4, marks);
        long result = db.insert(TABLE_NAME, null, contentValues);
        if (result == -1)
            return false;
        else
            return true;
    }

    public Cursor getAllData() {

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor res = db.rawQuery("select * from" + TABLE_NAME, null);
        return res;

    }

    public Boolean updateData(String id, String name, String surname, String marks) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL_1, id);
        contentValues.put(COL_2, name);
        contentValues.put(COL_3, surname);
        contentValues.put(COL_4, marks);
        db.update(TABLE_NAME, contentValues, "ID = ?", new String[]{id});
        return true;
    }

    public Integer deleteData(String id){

        SQLiteDatabase db = this.getWritableDatabase();
        return db.delete(TABLE_NAME, "ID = ?" , new String[] {id});

    }

}

What is the Problem?

Harshad Pansuriya
  • 17,218
  • 7
  • 58
  • 86

1 Answers1

0

Try to create database with method like:

 public void createDatabase() throws IOException {
    boolean dbExist = checkDataBase();

    if (dbExist) {
        Log.v("SQLiteDataHelper", "db exists");
    }
    if (!dbExist) {
        Log.d("SQLiteDataHelper", "copy db");
        this.getReadableDatabase();
        try {
            this.close();
            copyDataBase();
        } catch (IOException e) {
            throw new Error("Error copying database");
        }
    }
}

U will get log that this base is created or not

And this is constructor

 private SQLiteDataHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    this.context = context;
    try {
        createDatabase();
        openDatabase();
    }catch (IOException exception) {
        exception.printStackTrace();
    }catch (SQLException sqle) {
        sqle.printStackTrace();
    }
}

Also u can try to send instance for ur mainActivity.class with something like :

On SQL.class

public static SQLiteDataHelper getInstance(Context context) {
        if (instance == null) {
            instance = new SQLiteDataHelper(context);
        }
        return instance;
    }

and on main activity u doing something like:

myDbHelper = SQLiteDataHelper.getInstance(this);
Genehme
  • 79
  • 9