Abhijith Surendran
Abhijith Surendran

Reputation: 41

Error in creating and inserting into SQLite database using Android Studio.The App is crashing on launch

I am new to Android and is not so thorough in java language either. So please provide a solution to this problem.I want to display the name of registered users in MainActivity and the registration activity is used to obtain the details from the user.I want to learn how to create a database using DBhelper. Any information regarding that would be really appreciated. If anyone could provide details regarding how to create a database and how to insert and delete from that, it would be of great help. Thanks in advance

MainActivity.java

Context context;
DBHelper dbHelper;
ListView listView;
ArrayList nameList;


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

    listView = (ListView) findViewById(R.id.listView);
    ArrayList<String> nameList = new ArrayList<String>();
    dbHelper = new DBHelper(this);
    ArrayList<StoreDetails> arrayList = dbHelper.getAllContacts();
    for (StoreDetails sd : arrayList) {
        nameList.add(sd.getName());
    }
    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, nameList);
    listView.setAdapter(arrayAdapter);

}

@Override
protected void onResume() {
    super.onResume();

    Button addContact = (Button) findViewById(R.id.button);
    addContact.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent registerIntent = new Intent(MainActivity.this, RegisterDetails.class);
            startActivity(registerIntent);
        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}

DBhelper.java

static final String DATABASE_NAME = "MySqldatabase.db";
static final String CONTACT_TABLE_NAME = "Contacts";
static final String CONTACT_COLUMN_ID = "Id";
static final String CONTACT_COLUMN_NAME = "Name";
static final String CONTACT_COLUMN_PHONE = "Phone";
StoreDetails sd = new StoreDetails();
Cursor res;

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

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("create table Contacts" + "(Id integer primary key,Name text,Phone text)");

}

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

public void insertContact(StoreDetails storeDetails) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(CONTACT_COLUMN_NAME, sd.getName());
    contentValues.put(CONTACT_COLUMN_PHONE, sd.getPhone_number());
    db.insert(CONTACT_TABLE_NAME, null, contentValues);
    db.close();

}

public Cursor getData(int id) {
    SQLiteDatabase db = this.getReadableDatabase();
    res = db.rawQuery("Select * from Contacts where Id=" + id + "", null);
    return res;

}

public Integer deleteData(Integer id) {
    SQLiteDatabase db = this.getWritableDatabase();
    return db.delete("Contacts", "Id?=", new String[]{Integer.toString(id)});
}

public ArrayList<StoreDetails> getAllContacts() {

    ArrayList<StoreDetails> arrayList = new ArrayList<StoreDetails>();
    SQLiteDatabase db = this.getReadableDatabase();

    res = db.rawQuery("Select * from Contacts", null);
    if (res.moveToFirst()) {
        do {
            StoreDetails contact = new StoreDetails();
            contact.setId(res.getString(res.getColumnIndex(CONTACT_COLUMN_ID)));
            contact.setName(res.getString(res.getColumnIndex(CONTACT_COLUMN_NAME)));
            contact.setPhone_number(res.getString(res.getColumnIndex(CONTACT_COLUMN_PHONE)));
            arrayList.add(contact);
        }
        while (res.moveToNext());
    }return arrayList;
}

}

RegisterDetails.java

Button submit;
EditText user_name, phone_number;
StoreDetails sd = new StoreDetails();
DBHelper dbHelper=new DBHelper(this);

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

    submit = (Button) findViewById(R.id.button2);
    user_name = (EditText) findViewById(R.id.editText);
    phone_number = (EditText) findViewById(R.id.editText2);
    submit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            sd.setName(user_name.getText().toString());
            sd.setPhone_number(phone_number.getText().toString());
            dbHelper.insertContact(sd);
            Toast.makeText(getApplicationContext(),"Contact added successfully",Toast.LENGTH_LONG).show();
            Intent registeredIntent=new Intent(RegisterDetails.this,MainActivity.class);
            startActivity(registeredIntent);
        }
    });
}

@Override
protected void onResume() {
    super.onResume();
}

}

StoreDetails.java

String name, phone_number, id;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getPhone_number() {
    return phone_number;
}

public void setPhone_number(String phone_number) {
    this.phone_number = phone_number;
}

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

}

Upvotes: 0

Views: 1875

Answers (1)

Sahdev
Sahdev

Reputation: 11

You can have a look at the below links for more details on SQLite in Android.

http://www.vogella.com/tutorials/AndroidSQLite/article.html

http://hmkcode.com/android-simple-sqlite-database-tutorial/

From my personal experience, the onUpgrade() method needs to be better handled. Currently for any database upgrade it will drop contacts table and create a new one. This is not a great idea specially when you have users already using your previous application version(s).

For the error that you are receiving, can you share the error logs for a more detailed response.

Upvotes: 1

Related Questions