Android Development - Null Pointer Exception on Database Insert - java

OK, well I've been working on a simple app that allows users to save notes to contacts. It lists the contacts from the phone. User clicks on a contact and the notes entries that are related to the contact based on the contact ID are shown. The user can then add a new note by Menu>Add note. I can get all the way through the app but it wont save the data entered in the form to the database. When I try to save, I get a Null Pointer Exception. Nothing crashes, it just returns to the previous activity and doesn't do anything. I am kind of new to programming and have been teaching myself android for the past week and a half, so it could be something really simple. I have been digging around the web and frequently come to Stack Overflow to check for answers but cant seem to find anything on this one. Also, I'm not sure what code is needed so I'm just going to post the code for my form activity and my dbadapter. Thanks in advance for any help!
This is the activity used to enter the data:
package com.onyx.formapp23;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.onyx.formapp23.MyDbAdapter;
public class FormsNewNote extends Activity {
String mIntentString;
int contactId;
EditText contactIdEdit, titleEdit, bodyEdit;
long dateTimeValue;
Button submitBtn, discardBtn;
private MyDbAdapter db = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.forms_newnote);
Bundle extras = getIntent().getExtras();
mIntentString = extras.getString("contactId");
db = new MyDbAdapter(this);
contactIdEdit = (EditText) findViewById(R.id.noteFormContactId);
contactIdEdit.setText(mIntentString);
contactId = Integer.parseInt(mIntentString);
titleEdit = (EditText) findViewById(R.id.noteFormTitle);
bodyEdit = (EditText) findViewById(R.id.noteFormBody);
dateTimeValue = java.lang.System.currentTimeMillis();
submitBtn = (Button) findViewById(R.id.noteFormSave);
discardBtn = (Button) findViewById(R.id.noteFormDiscard);
submitBtn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
try{
String titleInsert = titleEdit.getText().toString();
String bodyInsert = bodyEdit.getText().toString();
db.createNote(contactId, titleInsert, bodyInsert, dateTimeValue);
} catch (Exception e) {
String titleInsert = titleEdit.getText().toString();
String bodyInsert = bodyEdit.getText().toString();
e.printStackTrace();
Context context = getApplicationContext();
CharSequence text = "SQL Exception Thrown: " + e + "\nTitle: " + titleInsert + "\nBody: " + bodyInsert;
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
finish();
}
});
}
}
This is my Db adapter class:
package com.onyx.formapp23;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class MyDbAdapter {
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
public static final String KEY_TITLE = "title";
public static final String KEY_BODY = "body";
public static final String KEY_CONTACTID = "contactId";
public static final String KEY_ROWID = "_id";
public static final String KEY_DATETIME = "datetime";
private static final String TAG = "MyDbAdapter";
private static final String DATABASE_CREATE =
"create table contactNotes (_id integer primary key autoincrement, contactId integer, title text not null, body text not null, datetime long);";
private static final String DATABASE_NAME = "OnyxDatabase";
private static final String DATABASE_TABLE = "contactNotes";
private static final int DATABASE_VERSION = 1;
private final Context mCtx;
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS notes");
onCreate(db);
}
}
public MyDbAdapter(Context ctx) {
this.mCtx = ctx;
}
public MyDbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
mDbHelper.close();
}
public long createNote(int contactId, String title, String body, long datetime) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_CONTACTID, contactId);
initialValues.put(KEY_TITLE, title);
initialValues.put(KEY_BODY, body);
initialValues.put(KEY_DATETIME, datetime);
return mDb.insertOrThrow(DATABASE_TABLE, null, initialValues);
}
public void createNote2(int contactId, String title, String body) {
mDb.execSQL("insert into " + DATABASE_TABLE + " (" + KEY_CONTACTID + ", " + KEY_TITLE + ", " + KEY_BODY + ", " + KEY_DATETIME + ") values(" + contactId + ", " +
title + ", " + body + ", " + java.lang.System.currentTimeMillis() + ");");
}
public boolean deleteNote(long rowId) {
return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
public Cursor fetchAllNotes() {
return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_TITLE, KEY_CONTACTID,
KEY_BODY, KEY_DATETIME}, null, null, null, null, null);
}
public Cursor fetchNotesForContact(String contactId) {
return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_CONTACTID, KEY_TITLE, KEY_BODY, KEY_DATETIME}, KEY_CONTACTID + " = " + contactId, null, null, null, new String (KEY_DATETIME +
" COLLATE LOCALIZED ASC"));
}
public Cursor fetchNote(long rowId) throws SQLException {
Cursor mCursor =
mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
KEY_TITLE, KEY_BODY}, KEY_ROWID + "=" + rowId, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public boolean updateNote(long rowId, String title, String body) {
ContentValues args = new ContentValues();
args.put(KEY_TITLE, title);
args.put(KEY_BODY, body);
return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
}
}
And here is the Trace from the Eclipse Debug:
Thread [<1> main] (Suspended (entry into method createNote in MyDbAdapter))
MyDbAdapter.createNote(int, String, String, long) line: 58
FormsNewNote$1.onClick(View) line: 43
Button(View).performClick() line: 2447
View$PerformClick.run() line: 9025
ViewRoot(Handler).handleCallback(Message) line: 587
ViewRoot(Handler).dispatchMessage(Message) line: 92
Looper.loop() line: 123
ActivityThread.main(String[]) line: 4628
Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method]
Method.invoke(Object, Object...) line: 521
ZygoteInit$MethodAndArgsCaller.run() line: 870
ZygoteInit.main(String[]) line: 628
NativeStart.main(String[]) line: not available [native method]

Doesn't look like you are calling MyDbAdapter.open() anywhere so in createNote() mDb is null.

Related

Application keeps crashing when trying to save appointment information?

I'm building an application for a barber shop and im on a part now where I am creating an appointment and saving the data from that appointment, however when I go to click add to create the appointment, the application crashes and I left with this error;
E/CursorWindow: Failed to read row 0, column -1 from a CursorWindow which has 2 rows, 3 columns.
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: ie.app.barbershop, PID: 31270
java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
at android.database.CursorWindow.nativeGetString(Native Method)
at android.database.CursorWindow.getString(CursorWindow.java:438)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:51)
at ie.app.barbershop.TableControllerAppointments.read(TableControllerAppointments.java:46)
at ie.app.barbershop.Landing.readRecords(Landing.java:47)
at ie.app.barbershop.OnClickListenerCreateAppointment$1.onClick(OnClickListenerCreateAppointment.java:38)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:162)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
I/Process: Sending signal. PID: 31270 SIG: 9
Application terminated.
Here is my class for TableControllerAppointments.java
package ie.app.barbershop;
import android.content.Context;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
import java.util.List;
public class TableControllerAppointments extends DatabaseHandler {
public TableControllerAppointments(Context context) {
super(context);
}
public boolean create(ObjectAppointment objectAppointments) {
ContentValues values = new ContentValues();
values.put("fullname", objectAppointments.fullName);
values.put("contactno", objectAppointments.contactNumber);
SQLiteDatabase db = this.getWritableDatabase();
boolean createSuccessful = db.insert("appointments", null, values) > 0;
db.close();
return createSuccessful;
}
public List<ObjectAppointment> read() {
List<ObjectAppointment> recordsList = new ArrayList<>();
String sql = "SELECT * FROM Appointments ORDER BY id DESC";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(sql, null);
if (cursor.moveToFirst()) {
do {
String fullName = cursor.getString(cursor.getColumnIndex("firstname"));
int contactNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex("contactno")));
ObjectAppointment objectAppointment = new ObjectAppointment();
objectAppointment.fullName = fullName;
objectAppointment.contactNumber = contactNumber;
recordsList.add(objectAppointment);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return recordsList;
}
public int count() {
SQLiteDatabase db = this.getWritableDatabase();
String sql = "SELECT * FROM appointments";
int recordCount = db.rawQuery(sql, null).getCount();
db.close();
return recordCount;
}
}
And here is my class for OnClickListenerCreateAppointment.java
package ie.app.barbershop;
import android.view.View;
import android.content.Context;
import android.view.LayoutInflater;
import android.widget.EditText;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.widget.Toast;
public class OnClickListenerCreateAppointment implements View.OnClickListener {
public ObjectAppointment objectAppointment;
#Override
public void onClick(View view){
final Context context = view.getRootView().getContext();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View formElementsView = inflater.inflate(R.layout.appointment_input_form, null, false);
final EditText editTextFullName = formElementsView.findViewById(R.id.editTextFullName);
final EditText editTextContactNumber = formElementsView.findViewById(R.id.editTextContactNumber);
ObjectAppointment objectAppointment = new ObjectAppointment();
new AlertDialog.Builder(context)
.setView(formElementsView)
.setTitle("Create Appointment")
.setPositiveButton("Add",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String fullname = editTextFullName.getText().toString();
String contactno = editTextContactNumber.getText().toString();
((Landing) context).countRecords();
((Landing) context).readRecords();
dialog.cancel();
}
}).show();
boolean createSuccessful = new TableControllerAppointments(context).create(objectAppointment);
if(createSuccessful){
Toast.makeText(context, "Appointment Information was saved.", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context, "Unable to save appointment information", Toast.LENGTH_SHORT).show();
}
}
}
and this is my Landing.java class
package ie.app.barbershop;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import java.util.List;
public class Landing extends AppCompatActivity{
public Button buttonProducts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_landing);
countRecords();
buttonProducts = findViewById(R.id.buttonProducts);
Button buttonCreateAppointment = findViewById(R.id.buttonCreateAppointment);
buttonCreateAppointment.setOnClickListener(new OnClickListenerCreateAppointment());
buttonProducts.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Landing.this, Products.class));
}
});
}
public void readRecords() {
LinearLayout linearLayoutRecords = findViewById(R.id.linearLayoutRecords);
linearLayoutRecords.removeAllViews();
List<ObjectAppointment> appointments = new TableControllerAppointments(this).read();
if (appointments.size() > 0) {
for (ObjectAppointment obj : appointments) {
String fullName = obj.fullName;
int contactNumber = obj.contactNumber;
String textViewContents = fullName + " - " + contactNumber;
TextView textViewAppointmentItem= new TextView(this);
textViewAppointmentItem.setPadding(0, 10, 0, 10);
textViewAppointmentItem.setText(textViewContents);
textViewAppointmentItem.setTag(Integer.toString(contactNumber));
linearLayoutRecords.addView(textViewAppointmentItem);
}
}
else {
TextView locationItem = new TextView(this);
locationItem.setPadding(8, 8, 8, 8);
locationItem.setText("No records yet.");
linearLayoutRecords.addView(locationItem);
}
}
public void countRecords(){
int recordCount = new TableControllerAppointments(this).count();
TextView textViewRecordCount = findViewById(R.id.textViewRecordCount);
textViewRecordCount.setText(recordCount + " records found.");
}
}
Database Handler Class
package ie.app.barbershop;
import android.database.sqlite.SQLiteOpenHelper;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
protected static final String DATABASE_NAME = "AppointmentDatabase";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE appointments " +
"( id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"fullname TEXT, " +
"contactno NUMBER ) ";
db.execSQL(sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String sql = "DROP TABLE IF EXISTS students";
db.execSQL(sql);
onCreate(db);
}
}
The -1 is being returned from getColumnIndex meaning that the column firstname
doesn't exist in the cursor in the following line.
String fullName = cursor.getString(cursor.getColumnIndex("firstname"));
You create the table using :-
String sql = "CREATE TABLE appointments " +
"( id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"fullname TEXT, " +
"contactno NUMBER ) ";
Where the columns are id fullname and contactno.
--
Fix
To fix this change to use :-
String fullName = cursor.getString(cursor.getColumnIndex("fullname"));
Additional
Better still define column and tables names as constants and always refer to them.
e.g.
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
protected static final String DATABASE_NAME = "AppointmentDatabase";
public static final String TABLE_NAME = "appointments";
public static final String COL_ID = "id";
public static final String COl_FULLNAME = "fullname";
public static final String COL_CONTACTNO = "contactno";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE " + TABLE_NAME +
"( " + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL_FULLNAME + " TEXT, " +
COL_CONTACTNO + " NUMBER ) ";
db.execSQL(sql);
}
.... and so on
and later as one example :-
String fullName = cursor.getString(cursor.getColumnIndex(DatabaseHandler.COL_FULLNAME));

How to update record in listview as well as Database in android

I want all edit text content that I have saved in SQL to be displayed on the edit bills activity when I click on the list item, but I am only able to retrieve the name and display it again in the intent. Rather than saving another data it should update the record with the new data if I save the existing record another time in the editbills_activity. Here is my DBAdapter.java
package com.example.dhruv.bills;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBAdapter {
public static final String KEY_ROWID = "id";
public static final String KEY_NAME = "name";
public static final String KEY_AMOUNT = "amount";
public static final String KEY_DUEDATE = "duedate";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "billsdb";
private static final String DATABASE_TABLE = "bills";
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_CREATE =
"create table if not exists assignments (id integer primary key autoincrement, "
+ "name VARCHAR not null, amount VARCHAR, duedate date );";
// Replaces DATABASE_CREATE using the one source definition
private static final String TABLE_CREATE =
"CREATE TABLE IF NOT EXISTS " + DATABASE_TABLE + "(" +
KEY_ROWID + " INTEGER PRIMARY KEY, " + // AUTOINCREMENT NOT REQD
KEY_NAME + " DATE NOT NULL, " +
KEY_AMOUNT + " VARCHAR ," +
KEY_DUEDATE + " DATE " +
")";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(TABLE_CREATE); // NO need to encapsulate in try clause
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS contacts"); //????????
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
//---opens the database---
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
//---insert a record into the database---
public long insertRecord(String name, String amount, String duedate)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_AMOUNT, amount);
initialValues.put(KEY_DUEDATE, duedate);
//return db.insert(DATABASE_TABLE, null, initialValues);
// Will return NULL POINTER EXCEPTION as db isn't set
// Replaces commented out line
return DBHelper.getWritableDatabase().insert(DATABASE_TABLE,
null,
initialValues
);
}
//---deletes a particular record---
public boolean deleteContact(long rowId)
{
return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
//---retrieves all the records--- SEE FOLLOWING METHOD
public Cursor getAllRecords()
{SQLiteDatabase db = DBHelper.getWritableDatabase();
String query ="SELECT * FROM " + DATABASE_TABLE;
Cursor data = db.rawQuery(query,null);
return data;
}
//As per getAllRecords but using query convenience method
public Cursor getAllAsCursor() {
return DBHelper.getWritableDatabase().query(
DATABASE_TABLE,
null,null,null,null,null,null
);
}
public void deleteName(int id, String name){
SQLiteDatabase db = DBHelper.getWritableDatabase();
String query = "DELETE FROM " + DATABASE_TABLE + " WHERE "
+ KEY_ROWID + " = '" + id + "'" +
" AND " + KEY_NAME + " = '" + name + "'";
Log.d(TAG, "deleteName: query: " + query);
Log.d(TAG, "deleteName: Deleting " + name + " from database.");
db.execSQL(query);
}
public Cursor getItemID(String name) {
SQLiteDatabase db = DBHelper.getWritableDatabase();
String query = "SELECT " + KEY_ROWID + " FROM " + DATABASE_TABLE +
" WHERE " + KEY_NAME + " = '" + name + "'";
Cursor data = db.rawQuery(query, null);
return data;
}
//---retrieves a particular record--- THIS WILL NOT WORK - NO SUCH TABLE
/* public Cursor getRecord()
{String query1 ="SELECT * FROM" + KEY_TITLE;
Cursor mCursor = db.rawQuery(query1,null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}*/
// Retrieve a row (single) according to id
public Cursor getRecordById(long id) {
return DBHelper.getWritableDatabase().query(
DATABASE_TABLE,
null,
KEY_ROWID + "=?",
new String[]{String.valueOf(id)},
null,null,null
);
}
//---updates a record---
/* public boolean updateRecord(long rowId, String name, String amount, String duedate)
{
ContentValues args = new ContentValues();
args.put(KEY_NAME, name);
args.put(KEY_AMOUNT, amount);
args.put(KEY_DUEDATE, duedate);
String whereclause = KEY_ROWID + "=?";
String[] whereargs = new String[]{String.valueOf(rowId)};
// Will return NULL POINTER EXCEPTION as db isn't set
//return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
// Replaces commented out line
return DBHelper.getWritableDatabase().update(DATABASE_TABLE,
args,
whereclause,
whereargs
) > 0;
}*/
}
Here is my Bills.java (MainActivity)
Problem: Bills.java has the list view that shows the intent whenever the item in list view is clicked, but it does not put the amount and date or update the record. Instead it saves another record.
Solution: I want to retrieve it and display all (name ,amount,duedate) and instead of saving another record it should update it.
package com.example.dhruv.bill;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class bills extends AppCompatActivity {
DBAdapter dbAdapter;
ListView mrecycleview;
private static final String TAG ="assignments";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bills);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mrecycleview =(ListView) findViewById(R.id.mRecycleView);
dbAdapter = new DBAdapter(this);
// mlistview();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab1);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),Editbills.class);
startActivity(i);
}
});
mlistview();
}
#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_bills, 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);
}
private void mlistview(){
Log.d(TAG,"mlistview:Display data in listview");
Cursor mCursor = dbAdapter.getAllRecords();
ArrayList<String> listData = new ArrayList<>();
while (mCursor.moveToNext()){
listData.add(mCursor.getString(1));
}
ListAdapter adapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,listData);
mrecycleview.setAdapter(adapter);
mrecycleview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String name = adapterView.getItemAtPosition(i).toString();
Log.d(TAG, "onItemClick: You Clicked on " + name);
Cursor data = dbAdapter.getItemID(name); //get the id associated with that name
int itemID = -1;
while(data.moveToNext()){
itemID = data.getInt(0);
}
if(itemID > -1){
Log.d(TAG, "onItemClick: The ID is: " + itemID);
Intent editScreenIntent = new Intent(bills.this, Editbills.class);
editScreenIntent.putExtra("id",itemID);
editScreenIntent.putExtra("name",name);
startActivity(editScreenIntent);
}
else{
}
}
});
}
}
here is my editbills.java code
package com.example.dhruv.bill;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Editbills extends AppCompatActivity {
Button button;
private static final String Tag= "assignments";
DBAdapter db = new DBAdapter(this);
private String selectedName;
private int selectedID;
DBAdapter dbAdapter;
private EditText editText,editText2,editText3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_editbills);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
button=(Button)findViewById(R.id.button);
editText =(EditText)findViewById(R.id.editText);
editText2=(EditText)findViewById(R.id.editText2);
editText3 =(EditText)findViewById(R.id.editText3);
//get the intent extra from the ListDataActivity
Intent receivedIntent = getIntent();
//now get the itemID we passed as an extra
selectedID = receivedIntent.getIntExtra("id",-1); //NOTE: -1 is just the default value
//now get the name we passed as an extra
selectedName = receivedIntent.getStringExtra("name");
//set the text to show the current selected name
editText.setText(selectedName);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("test", "adding");
db.open();
long id = db.insertRecord(editText.getText().toString(), editText2.getText().toString(), editText3.getText().toString());
db.close();
Toast.makeText(Editbills.this," Added", Toast.LENGTH_LONG).show();
Intent q = new Intent(getApplicationContext(),bills.class);
startActivity(q);
}
});
}
#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_bills, 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_Delete) {
db.deleteName(selectedID,selectedName);
editText.setText("");
Toast.makeText(this, "Deleted", Toast.LENGTH_SHORT).show();
Intent p = new Intent(getApplicationContext(),bills.class);
startActivity(p);
return true;
}
return super.onOptionsItemSelected(item);
}
}
Instead of
DBHelper.getWritableDatabase().insert(DATABASE_TABLE, null, initialValues);
in insertRecord function of DBHelper, it should be
DBHelper.getWritableDatabase().update("markers", valores, where, whereArgs);

How to get database value into edit text in android

Here is my code
Databasehandler.java
package com.example.mybucky.myapplication;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.prefs.Preferences;
/**
* Created by Satyajeet Sen on 20/12/2016.
*/
public class DatabaseHandler extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "Register.db" ;
private static final int DATABASE_VERSION = 1 ;
private static final String TABLE_REGISTER = "REGISTER";
private static final String COL_ID = "id";
private static final String COL_NAME = "name";
private static final String COL_USERNAME = "username";
private static final String COL_PASSWORD = "password";
private static final String COL_AGE = "age";
SQLiteDatabase db;
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
//3rd argument to be passed is CursorFactory instance
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_REGISTER_TABLE = "CREATE TABLE " + TABLE_REGISTER + "("
+ COL_ID + " INTEGER PRIMARY KEY ," + COL_NAME + " TEXT ,"
+ COL_USERNAME + " TEXT ," + COL_PASSWORD + " TEXT ," + COL_AGE + " INTEGER "+")";
db.execSQL(CREATE_REGISTER_TABLE);
this.db=db;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_REGISTER);
// Create tables again
this.onCreate(db);
}
public void insertDetails(LoginRegisterBean l){
db=this.getWritableDatabase();
ContentValues values = new ContentValues();
String query ="SELECT * FROM "+TABLE_REGISTER;
Cursor cursor =db.rawQuery(query,null);
int count=cursor.getCount();
values.put(COL_ID,count);
// Contact Name
values.put(COL_NAME, l.getName());
values.put(COL_USERNAME, l.getUsername());
values.put(COL_PASSWORD, l.getPassword());
values.put(COL_AGE, l.getAge());
db.insert(TABLE_REGISTER,null,values);
db.close();
}
public String searchPass(String uname,String pass){
uname=COL_USERNAME;
pass=COL_PASSWORD;
db=this.getReadableDatabase();
String query=("SELECT " +uname+ "," +pass+ " from " + TABLE_REGISTER +"");
Cursor cursor = db.rawQuery(query,null);
String a,b ;
b="not found";
if(cursor.moveToFirst()){
do{
a=cursor.getString(0);
b=cursor.getString(1);
if(a.equals(COL_USERNAME)){
b=cursor.getString(1);
break;
}
}
while(cursor.moveToNext());
}
return b;
}
public String searchUser(String uname,String pass){
uname=COL_USERNAME;
pass=COL_PASSWORD;
db=this.getReadableDatabase();
String query=("SELECT " +uname+ "," +pass+ " from " + TABLE_REGISTER +"");
Cursor cursor = db.rawQuery(query,null);
String a,b ;
a="not found";
if(cursor.moveToFirst()){
do{
a=cursor.getString(0);
b=cursor.getString(1);
if(a.equals(COL_USERNAME)){
b=cursor.getString(1);
break;
}
}
while(cursor.moveToNext());
}
return a;
}
LoginRegisterBean getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_REGISTER, new String[] { COL_ID,
COL_USERNAME,COL_AGE }, COL_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
LoginRegisterBean retrievecontact = new LoginRegisterBean(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), Integer.parseInt(cursor.getString(2)));
// return contact
return retrievecontact;
}
}
UserAreaActivity.java 2edit texts one for age and other for username. Aim:-to display values of age nd username from database to edittext
package com.example.mybucky.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.EditText;
import android.widget.TextView;
import com.example.mybucky.myapplication.R;
import java.util.ArrayList;
import java.util.List;
public class UserAreaActivity extends AppCompatActivity {
DatabaseHandler helper = new DatabaseHandler(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_area);
final EditText etUsername = (EditText) findViewById(R.id.username);
final EditText etAge = (EditText) findViewById(R.id.age);
final TextView tvwelcome = (TextView) findViewById(R.id.tvwelcome);
public void retrievefromdb(LoginRegisterBean l){
List<LoginRegisterBean> lst =new ArrayList<LoginRegisterBean>();
for(int i=0;i<3;i++){
lst.add( helper.getContact(i));
}
}
}
}
I have a method returning a single contact in Databasehandler class but i dont need password to be displayed. Display fields only age and username in activity UserAreaActivity.
Welcome user!Your age is
age
---edit field------
username
---edit field-----

Building Database and outputting data in Android

I've built a database class in Android using SQLite, so far it just creates a database and inputs data, however the only log report I see is that the data has been input, but the log never shows for the database creation.
I have also seen people have a .db file in their assets folder, mine is not created.
so:
1) How come it's not showing the log error for building the database, and also is there meant to be a .db file created through SQLite? It's my first time using it.
2) If it is creating, how can I call the List from the getData() method and output it in MainActivity? I've tried using intents but once I realised I wasn't getting the log report from the database creation so I need that sorted before anything.
MainActivity.java
public class MainActivity extends Activity {
Intent appIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DB db = new DB(this);
db.insertStudent("T", "T", 5, "T", "T", "T");
List<tableStudents> outputList = db.getData();
}
DB.java
package com.example.project;
import java.util.ArrayList;
import java.util.List;
import com.example.project.tableStudents.tableColumns;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.view.View;
public class DB extends SQLiteOpenHelper {
public static final int db_version = 1;
public static final String Table = "Students";
public static final String Student_ID = "Student_ID";
public static final String Student_Name = "Student_Name";
public static final String Student_Password = "Student_Password";
public static final String Student_Gender = "gender";
public static final String Student_Age = "age";
public static final String Student_Course = "course";
public static final String Modules = "modules";
public DB(Context context) {
super(context, tableColumns.Database, null, db_version);
}
#Override
public void onCreate(SQLiteDatabase db) {
//Create Table
db.execSQL("CREATE TABLE " + Table + "(" +
Student_ID + " INTEGER PRIMARY KEY, " +
Student_Name + " TEXT, " +
Student_Password + " TEXT, " +
Student_Gender + " TEXT, " +
Student_Age + " INTEGER, " +
Student_Course + " TEXT, " +
Modules + "TEXT");
Log.d("DB", "DB Created");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + Table);
onCreate(db);
}
public List<tableStudents> getData() {
List<tableStudents> studentList = new ArrayList<tableStudents>();
// Select All Query
String selectQuery = "SELECT * FROM " + Table;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
tableStudents student = new tableStudents();
student.name = cursor.getString(0);
student.gender = cursor.getString(1);
student.age = Integer.parseInt(cursor.getString(2));
student.password = cursor.getString(3);
student.course = cursor.getString(4);
student.modules = cursor.getString(5);
studentList.add(student);
} while (cursor.moveToNext());
}
// return contact list
return studentList;
}
public boolean insertStudent(String name, String gender, int age, String password, String course, String modules) {
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(Student_Name, name);
contentValues.put(Student_Gender, gender);
contentValues.put(Student_Age, age);
contentValues.put(Student_Password, password);
contentValues.put(Student_Course, course);
contentValues.put(Modules, modules);
//Log for admin insert
Log.d("DB", "Inserted Successfully");
return true;
}
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_PH_NO + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
#Matt Murphy please go through this link for each detail for your project
http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/.

force close at cursor line!

Hy!
I'm trying to create an application that looks for gps data that was stored in SQlite database.
But I'm facing a problem:
I built an DbAdapter class that creates my database and now I'm trying from another class to get an cursor over my all data,using this function:
public Cursor fetchAllData() {
return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_LONGITUDE,KEY_LATITUDE,KEY_COUNTRY,KEY_TOWN,KEY_STREET}, null, null, null, null, null);
}
Now,I'm creating an instance of DbAdapter in my new class,but I get forceclose when I insert this line:Cursor c=db.fetchAllData();
The class that creates my database looks like this:
package test.android;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class CoordonateDbAdapter {
public static final String KEY_ROWID = "_id";
public static final String KEY_LONGITUDE= "longitude";
public static final String KEY_LATITUDE = "latitude";
public static final String KEY_COUNTRY= "country";
public static final String KEY_TOWN= "town";
public static final String KEY_STREET = "street";
private static final String TAG = "CoordonateDbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private static final String DATABASE_CREATE =
"create table car1 (_id integer primary key autoincrement, "
+ "longitude text not null, latitude text not null," +
"country text not null,town text not null,street text not null);";
private static final String DATABASE_NAME = "gps";
private static final String DATABASE_TABLE = "masini";
private static final int DATABASE_VERSION = 1;
private final Context mCtx;
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS notes");
onCreate(db);
}
}
public CoordonateDbAdapter(Context ctx) {
this.mCtx = ctx;
}
public CoordonateDbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
mDbHelper.close();
}
public long insertData(String longitude, String latitude, String country, String town, String street) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_LONGITUDE, longitude);
initialValues.put(KEY_LATITUDE, latitude);
initialValues.put(KEY_COUNTRY, country);
initialValues.put(KEY_TOWN, town);
initialValues.put(KEY_STREET, street);
return mDb.insert(DATABASE_TABLE, null, initialValues);
}
public boolean deleteData(long rowId) {
return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
public Cursor fetchAllData() {
return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_LONGITUDE,KEY_LATITUDE,KEY_COUNTRY,KEY_TOWN,KEY_STREET}, null, null, null, null, null);
}
public Cursor fetchData(long rowId) throws SQLException {
Cursor mCursor = mDb.query(true, DATABASE_TABLE, new String[]
{KEY_ROWID, KEY_LONGITUDE,KEY_LATITUDE,KEY_COUNTRY,KEY_TOWN,KEY_STREET},
KEY_ROWID + "=" + rowId, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public boolean updateNote(long rowId, String longitude, String latitude,String country, String town,String street) {
ContentValues args = new ContentValues();
args.put(KEY_LONGITUDE, longitude);
args.put(KEY_LATITUDE, latitude);
args.put(KEY_COUNTRY, country);
args.put(KEY_TOWN, town);
args.put(KEY_STREET, street);
return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
}
public List<String> selectAll() {
List<String> list = new ArrayList<String>();
Cursor cursor = this.mDb.query(DATABASE_TABLE, new String[] { "longitude"},
null, null, null, null, "name desc");
if (cursor.moveToFirst()) {
do {
list.add(cursor.getString(0));
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return list;
}
}
And the class that retrieves the gps data is like this:
package test.android;
import java.util.List;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.Toast;
public class screen_database extends Activity{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen_database);
CoordonateDbAdapter db = new CoordonateDbAdapter(this);
db.open();
long id;
// id= db.insertData("-36.2", "125","Romania","Cluj","Zorilor");
// db.insertData("44", "55","Romania","Iasi","Alexandru Ioan Cuza");
// List<String> names = db.selectAll();
Cursor c=db.fetchAllData();
/* if (c.moveToFirst())
{
do {
// DisplayTitle(c);
} while (c.moveToNext());
}*/
// c.close();
}
/* public void DisplayTitle(Cursor c)
{
Toast.makeText(this,
"longitude: " + c.getString(0) + "\n" +
"latitude: " + c.getString(1) + "\n" +
"country: " + c.getString(2) + "\n" +
"town: " + c.getString(3),
Toast.LENGTH_LONG).show();
}*/
}
//}
You can see lots of lines that are comments because I get force close when I'm asking for a Cursor,so I tried to keep it as simple.
Do I need any permissions to work with cursors,becuase I looked on the internet and all the line code looks like mine?!
Another problem is that my application is quite big,and I'm accesing this classes from other classes....a long row of classes until I get to query from the Sqlite.
I would really apreciate if you would help me,it might be something simple but I can't figure it out what it is.Thank you!!!
first try to access directly by copying
return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_LONGITUDE,KEY_LATITUDE,KEY_COUNTRY,KEY_TOWN,KEY_STREET}, null, null, null, null, null);
instead of calling it by method.
If that works, check if curser is available in the method.
If it is, try to reduce the SQLQuery like
return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_LONGITUDE}, null, null, null, null, null);
and add more columns step by step.

Categories

Resources