I am generating an events dynamically. These events data I am storing in sqlite database. Now I want to retrieve data of the clicked event. I tried to retrieve data but always getting 0th id data.
Generating events function :
private void createEvent(LayoutInflater inflater, ViewGroup dayplanView, int fromMinutes, int toMinutes, String title) {
final View eventView = inflater.inflate(R.layout.event_view, dayplanView, false);
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) eventView.getLayoutParams();
RelativeLayout container = (RelativeLayout) eventView.findViewById(R.id.container);
TextView tvTitle = (TextView) eventView.findViewById(R.id.textViewTitle);
if (tvTitle.getParent() != null)
((ViewGroup) tvTitle.getParent()).removeView(tvTitle);
tvTitle.setText(title);
int distance = (toMinutes - fromMinutes);
layoutParams.topMargin = dpToPixels(fromMinutes + 9);
layoutParams.height = dpToPixels(distance);
eventView.setLayoutParams(layoutParams);
dayplanView.addView(eventView);
container.addView(tvTitle);
eventView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
i = new Intent(getActivity(),AddEventActivity.class);
startActivity(i);
}
});
}
This is my attempt to get data:
db = new EventTableHelper(getApplication());
eventData = new EventData();
if(editMode)//true
{
eventData = events.get(id);
Toast.makeText(getApplicationContext(),String.valueOf(id),Toast.LENGTH_LONG).show();
title.setText(eventData.getTitle());
eventTitle = title.getText().toString();
db.updateEvent(eventData);
Toast.makeText(getApplicationContext(),"Edit mode",Toast.LENGTH_LONG).show();
Log.i("Log","save mode");
}
I have EventTableHelper in that i have created functions to get event,update and delete events.
public class EventTableHelper extends SQLiteOpenHelper {
private static final String TABLE = "event";
private static final String KEY_ID = "id";
private static final String KEY_TITLE = "title";
private static final String KEY_FROM_DATE = "datefrom";
private static final String KEY_TO_DATE = "dateto";
private static final String KEY_LOCATION = "location";
private static final String KEY_DAY_OF_WEEK = "dayofweek";
public EventTableHelper(Context context) {
super(context, Constants.DATABASE_NAME, null, Constants.DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
}
public void createTable(SQLiteDatabase db){
String CREATE_EVENTS_TABLE = "CREATE TABLE " + TABLE+ "("
+ KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_TITLE + " TEXT,"
+ KEY_FROM_DATE + " DATE,"
+ KEY_TO_DATE + " DATE,"
+ KEY_DAY_OF_WEEK + " TEXT "
+ KEY_LOCATION + " TEXT" + ")";
db.execSQL(CREATE_EVENTS_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE);
// createTable(db);
// onCreate(db);
}
public void addEvent(EventData event) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TITLE,event.getTitle());
values.put(KEY_FROM_DATE, event.getFromDate());
values.put(KEY_TO_DATE,event.getToDate());
values.put(KEY_DAY_OF_WEEK,event.getDayOfWeek());
values.put(KEY_LOCATION,event.getLocation());
db.insert(TABLE, null, values);
db.close();
}
EventData getEvent(int id) {
SQLiteDatabase db = this.getReadableDatabase();
EventData eventData = new EventData();
Cursor cursor = db.query(TABLE, new String[]{KEY_ID,
KEY_TITLE, KEY_FROM_DATE, KEY_TO_DATE,KEY_DAY_OF_WEEK, KEY_LOCATION}, KEY_ID + "=?",
new String[]{String.valueOf(id)}, null, null, null, null);
if( cursor != null && cursor.moveToFirst() ) {
eventData = new EventData(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2),
cursor.getString(3), cursor.getString(4), cursor.getString(5));
}
return eventData;
}
public List<EventData> getAllEvents() {
List<EventData> conList = new ArrayList<EventData>();
String selectQuery = "SELECT * FROM " + TABLE;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
EventData event = new EventData();
event.setId(Integer.parseInt(cursor.getString(0)));
event.setTitle(cursor.getString(1));
event.setFromDate(cursor.getString(2));
event.setToDate(cursor.getString(3));
event.setLocation(cursor.getString(4));
conList.add(event);
} while (cursor.moveToNext());
}
return conList;
}
}
I want to show data and update data if changes made.
Whats going wrong?
Related
I'm using fragment to create tabs, and I'm trying to insert information from the fragment to my database.
So I've 3 RadioGroup and I'm adding to the database the 'Checked' radio button that the user has marked, and I'm not able to add into the database the data because the following error:
Attempt to invoke virtual method
'android.database.sqlite.SQLiteDatabase
android.content.Context.openOrCreateDatabase(java.lang.String, int,
android.database.sqlite.SQLiteDatabase$CursorFactory,
android.database.DatabaseErrorHandler)' on a null object reference
There are DatabaseHandler functions (which works) that I use such as
db.checkSetting() - Check if the database table is empty, if empty return false, if not return true.
db.updateSetting() - Update the data inside the table.
db.addSetting() - Create new table with new data.
public class DatabaseHandler extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "database.db";
//table name
private static final String TABLE_DETAILS = "details";
private static final String TABLE_FOOD = "food";
private static final String TABLE_OLDDETAILS = "oldDetails";
private static final String TABLE_SETTING = "setting";
//Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_HEIGHT = "height";
private static final String KEY_WEIGHT = "weight";
private static final String KEY_CALORIES = "calories";
private static final String KEY_DATE = "date";
private static final String KEY_LEVEL = "level";
private static final String KEY_DURATION = "duration";
private static final String KEY_DAYS = "days";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_DETAILS_TABLE = "CREATE TABLE " + TABLE_DETAILS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_HEIGHT + " REAL," + KEY_WEIGHT + " REAL " + ")";
String CREATE_FOOD_TABLE = "CREATE TABLE " + TABLE_FOOD + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT," + KEY_CALORIES + " INTEGER " + ")";
String CREATE_OLDDETAILS_TABLE = "CREATE TABLE " + TABLE_OLDDETAILS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_DATE + " TEXT," + KEY_HEIGHT + " REAL," + KEY_WEIGHT + " REAL " + ")";
String CREATE_SETTING_TABLE = "CREATE TABLE " + TABLE_SETTING + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_LEVEL + " INTEGER," + KEY_DURATION + " INTEGER," + KEY_DAYS + " INTEGER " + ")";
db.execSQL(CREATE_OLDDETAILS_TABLE);
db.execSQL(CREATE_DETAILS_TABLE);
db.execSQL(CREATE_FOOD_TABLE);
db.execSQL(CREATE_SETTING_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_DETAILS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_OLDDETAILS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_FOOD);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_SETTING);
// Create tables again
onCreate(db);
}
public boolean addSetting(int level, int duration, int days) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ID, 1);
values.put(KEY_LEVEL, level);
values.put(KEY_DURATION, duration);
values.put(KEY_DAYS, days);
// Inserting Row
long result = db.insert(TABLE_SETTING, null, values);
if(result == -1){
return false;
}
else{
return true;
}
}
public boolean checkSetting(){
SQLiteDatabase db = this.getWritableDatabase();
String selectQuery = "SELECT * FROM " + TABLE_SETTING;
Cursor cursor = db.rawQuery(selectQuery, null);
Boolean rowExists;
if (cursor.moveToFirst())
{
// DO SOMETHING WITH CURSOR
rowExists = true;
} else
{
// I AM EMPTY
rowExists = false;
}
return rowExists;
}
public setting getSetting() {
String selectQuery = "SELECT * FROM " + TABLE_SETTING;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor != null)
cursor.moveToFirst();
setting set = new setting(cursor.getInt(1), cursor.getInt(2), cursor.getInt(3));
return set;
}
public int updateSetting(setting set) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_LEVEL, set.getLevel());
values.put(KEY_DURATION, set.getDuration());
values.put(KEY_DAYS, set.getDays());
Log.d("UPDATE: ", "updated all");
// updating row
return db.update(TABLE_SETTING, values, KEY_ID + " = ?", new String[] { String.valueOf(1) });
}
Fragment:
public class PageFragment extends Fragment {
DatabaseHandler db = new DatabaseHandler(getActivity()); //DATABASE
private int group1;
private int group2;
private int group3;
public static final String ARG_PAGE = "ARG_PAGE";
private int mPage;
public static PageFragment newInstance(int page) {
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
PageFragment fragment = new PageFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPage = getArguments().getInt(ARG_PAGE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_training, container, false);
ViewStub stub = (ViewStub) view.findViewById(R.id.stub);
if(mPage == 1) { // mPage represents the ID of the tab/page/fragment that in use.
stub.setLayoutResource(R.layout.fragment_trainingone); // Sets resource for each fragment
View inflated = stub.inflate();
return inflated;
}
else{
stub.setLayoutResource(R.layout.fragment_trainingtwo);
View inflated = stub.inflate();
RadioGroup rg1 = (RadioGroup) inflated.findViewById(R.id.group1);
RadioGroup rg2 = (RadioGroup) inflated.findViewById(R.id.group2);
RadioGroup rg3 = (RadioGroup) inflated.findViewById(R.id.group3);
Button update = (Button) inflated.findViewById(R.id.update);
rg1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch(checkedId){
case R.id.radio1:
group1 = 1;
break;
case R.id.radio2:
group1 = 2;
break;
case R.id.radio3:
group1 = 3;
break;
}
}
});
rg2.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch(checkedId){
case R.id.radio11:
group2 = 1;
break;
case R.id.radio22:
group2 = 2;
break;
case R.id.radio33:
group2 = 3;
break;
}
}
});
rg3.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch(checkedId){
case R.id.radio111:
group3 = 1;
break;
case R.id.radio222:
group3 = 2;
break;
case R.id.radio333:
group3 = 3;
break;
}
}
});
update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(android.view.View v) {
setting set = new setting(group1, group2, group3);
if (db.checkSetting()) {
db.updateSetting(set);
} else {
db.addSetting(group1, group2, group3);
}
}
});
return inflated;
}
}
}
How can I insert data into database within fragment and avoiding NullPointerException?
You're calling
DatabaseHandler db = new DatabaseHandler(getActivity());
before the Activity is even attached to the Fragment. Initialise it in the onCreate(), or onAttach() method, so getActivity() doesn't return null.
Attempt to invoke virtual method
'android.database.sqlite.SQLiteDatabase
android.content.Context.openOrCreateDatabase(java.lang.String, int,
android.database.sqlite.SQLiteDatabase$CursorFactory,
android.database.DatabaseErrorHandler)' on a null object reference
According to Exception You Have to open database before querying from it follow the below linked post
public void openDataBase() throws SQLException
{
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}
SQLite database status on app uninstall
I saw this tutorial: https://www.youtube.com/watch?v=gaOsl2TtMHs
but it seem that when i see the activity there isn't any item listview :\
What can be the problem? I put my code under below
The Main Activity.java
public class Prova2 extends Activity {
int[] imageIDs = {
R.drawable.spaghettiscoglio,
R.drawable.abbacchioascottadito,
R.drawable.agnellocacioeova,
R.drawable.agnolotti,
R.drawable.alettedipollo,
R.drawable.amaretti,
R.drawable.anatraarancia,
R.drawable.alberinatale
};
int nextImageIndex = 0;
DBAdapter myDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.prova2);
openDB();
populateListViewFromDB();
registerListClickCallback();
}
#Override
protected void onDestroy() {
super.onDestroy();
closeDB();
}
private void openDB() {
myDb = new DBAdapter(this);
myDb.open();
}
private void closeDB() {
myDb.close();
}
/*
* UI Button Callbacks
*/
public void onClick_AddRecord(View v) {
int imageId = imageIDs[nextImageIndex];
nextImageIndex = (nextImageIndex + 1) % imageIDs.length;
// Add it to the DB and re-draw the ListView
myDb.insertRow("Jenny" + nextImageIndex, imageId, "Green");
populateListViewFromDB();
}
public void onClick_ClearAll(View v) {
myDb.deleteAll();
populateListViewFromDB();
}
private void populateListViewFromDB() {
Cursor cursor = myDb.getAllRows();
// Allow activity to manage lifetime of the cursor.
// DEPRECATED! Runs on the UI thread, OK for small/short queries.
startManagingCursor(cursor);
// Setup mapping from cursor to view fields:
String[] fromFieldNames = new String[]
{DBAdapter.KEY_NAME, DBAdapter.KEY_STUDENTNUM, DBAdapter.KEY_FAVCOLOUR, DBAdapter.KEY_STUDENTNUM};
int[] toViewIDs = new int[]
{R.id.tvFruitPrice, R.id.ivFruit, R.id.tvFruitPrice, R.id.smalltext};
// Create adapter to may columns of the DB onto elemesnt in the UI.
SimpleCursorAdapter myCursorAdapter =
new SimpleCursorAdapter(
this, // Context
R.layout.sis, // Row layout template
cursor, // cursor (set of DB records to map)
fromFieldNames, // DB Column names
toViewIDs // View IDs to put information in
);
// Set the adapter for the list view
ListView myList = (ListView) findViewById(R.id.listViewFromDB);
myList.setAdapter(myCursorAdapter);
}
private void registerListClickCallback() {
ListView myList = (ListView) findViewById(R.id.listViewFromDB);
myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked,
int position, long idInDB) {
updateItemForId(idInDB);
displayToastForId(idInDB);
}
});
}
private void updateItemForId(long idInDB) {
Cursor cursor = myDb.getRow(idInDB);
if (cursor.moveToFirst()) {
long idDB = cursor.getLong(DBAdapter.COL_ROWID);
String name = cursor.getString(DBAdapter.COL_NAME);
int studentNum = cursor.getInt(DBAdapter.COL_STUDENTNUM);
String favColour = cursor.getString(DBAdapter.COL_FAVCOLOUR);
favColour += "!";
myDb.updateRow(idInDB, name, studentNum, favColour);
}
cursor.close();
populateListViewFromDB();
}
private void displayToastForId(long idInDB) {
Cursor cursor = myDb.getRow(idInDB);
if (cursor.moveToFirst()) {
long idDB = cursor.getLong(DBAdapter.COL_ROWID);
String name = cursor.getString(DBAdapter.COL_NAME);
int studentNum = cursor.getInt(DBAdapter.COL_STUDENTNUM);
String favColour = cursor.getString(DBAdapter.COL_FAVCOLOUR);
String message = "ID: " + idDB + "\n"
+ "Name: " + name + "\n"
+ "Std#: " + studentNum + "\n"
+ "FavColour: " + favColour;
Toast.makeText(Prova2.this, message, Toast.LENGTH_LONG).show();
}
cursor.close();
}
The DBAdaptor.java
public class DBAdapter {
/////////////////////////////////////////////////////////////////////
// Constants & Data
/////////////////////////////////////////////////////////////////////
// For logging:
private static final String TAG = "DBAdapter";
// DB Fields
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
/*
* CHANGE 1:
*/
// TODO: Setup your fields here:
public static final String KEY_NAME = "name";
public static final String KEY_STUDENTNUM = "studentnum";
public static final String KEY_FAVCOLOUR = "favcolour";
// TODO: Setup your field numbers here (0 = KEY_ROWID, 1=...)
public static final int COL_NAME = 1;
public static final int COL_STUDENTNUM = 2;
public static final int COL_FAVCOLOUR = 3;
public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_NAME, KEY_STUDENTNUM, KEY_FAVCOLOUR};
// DB info: it's name, and the table we are using (just one).
public static final String DATABASE_NAME = "MyDb";
public static final String DATABASE_TABLE = "mainTable";
// Track DB version if a new version of your app changes the format.
public static final int DATABASE_VERSION = 2;
private static final String DATABASE_CREATE_SQL =
"create table " + DATABASE_TABLE
+ " (" + KEY_ROWID + " integer primary key autoincrement, "
/*
* CHANGE 2:
*/
// TODO: Place your fields here!
// + KEY_{...} + " {type} not null"
// - Key is the column name you created above.
// - {type} is one of: text, integer, real, blob
// (http://www.sqlite.org/datatype3.html)
// - "not null" means it is a required field (must be given a value).
// NOTE: All must be comma separated (end of line!) Last one must have NO comma!!
+ KEY_NAME + " text not null, "
+ KEY_STUDENTNUM + " integer not null, "
+ KEY_FAVCOLOUR + " string not null"
// Rest of creation:
+ ");";
// Context of application who uses us.
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
/////////////////////////////////////////////////////////////////////
// Public methods:
/////////////////////////////////////////////////////////////////////
public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
// Open the database connection.
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}
// Close the database connection.
public void close() {
myDBHelper.close();
}
// Add a new set of values to the database.
public long insertRow(String name, int studentNum, String favColour) {
/*
* CHANGE 3:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_STUDENTNUM, studentNum);
initialValues.put(KEY_FAVCOLOUR, favColour);
// Insert it into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}
// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
return db.delete(DATABASE_TABLE, where, null) != 0;
}
public void deleteAll() {
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
if (c.moveToFirst()) {
do {
deleteRow(c.getLong((int) rowId));
} while (c.moveToNext());
}
c.close();
}
// Return all data in the database.
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Get a specific row (by rowId)
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Change an existing row to be equal to new data.
public boolean updateRow(long rowId, String name, int studentNum, String favColour) {
String where = KEY_ROWID + "=" + rowId;
/*
* CHANGE 4:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues newValues = new ContentValues();
newValues.put(KEY_NAME, name);
newValues.put(KEY_STUDENTNUM, studentNum);
newValues.put(KEY_FAVCOLOUR, favColour);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
/////////////////////////////////////////////////////////////////////
// Private Helper Classes:
/////////////////////////////////////////////////////////////////////
/**
* Private class which handles database creation and upgrading.
* Used to handle low-level database access.
*/
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_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading application's database from version " + oldVersion
+ " to " + newVersion + ", which will destroy all old data!");
// Destroy old database:
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
// Recreate new database:
onCreate(_db);
}
}
i can't get my data to show on my ListView. i created database handler with a query that says: "SELECT * FROM TABLE_NAME WHERE COLUMN_USERNAME = '"+Username+"'". i want to show Data that have the username i want only. But i cant seem to get it work. here is the code.
ViewEvent class with the List View
public class ViewEvent extends Activity {
private static String z = "";
private static final int _EDIT = 0, _DELETE = 1; // constants to be used later
static int longClickedItemIndex;
static List<Event> events = new ArrayList<Event>();
ArrayAdapter<Event> eventsAdapter;
ListView listViewEvents;
static DatabaseHandlerEvent helper;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_event);
Typeface myTypeFace = Typeface.createFromAsset(getAssets(), "Type Keys Filled.ttf");
TextView myTextview = (TextView) findViewById(R.id.textViewHead4);
myTextview.setTypeface(myTypeFace);
helper = new DatabaseHandlerEvent(getApplicationContext());
listViewEvents = (ListView) findViewById(R.id.listView);
registerForContextMenu(listViewEvents);
listViewEvents.setOnItemLongClickListener(
new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
longClickedItemIndex = position;
return false;
}
}
);
populateList();
SharedPreferences prfs = getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_PRIVATE);
String Username = prfs.getString("Username", "");
if (helper.getEventCount() != 0 && events.size() == 0) {
events.addAll(helper.getAllEvent(Username));
}
}
public void registerForContextMenu(View view) {
view.setOnCreateContextMenuListener(this);
}
public void onButtonClick(View v){
if(v.getId() == R.id.bSignoutb){
Toast so = Toast.makeText(ViewEvent.this, "Signing out.. Redirecting to Login Page..." , Toast.LENGTH_SHORT);
so.show();
Intent i = new Intent(ViewEvent.this, MainActivity.class);
startActivity(i);
}
if(v.getId() == R.id.Bback){
Intent i = new Intent(ViewEvent.this, CreateEvent.class);
startActivity(i);
}
}
private void populateList() {
eventsAdapter = new eventListAdapter();
listViewEvents.setAdapter(eventsAdapter);
}
public class eventListAdapter extends ArrayAdapter<Event> {
public eventListAdapter() {
super(ViewEvent.this, R.layout.listview_event, events);
}
#Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null) {
view = getLayoutInflater().inflate(R.layout.listview_event, parent, false);
}
Event currentEvent = events.get(position);
TextView name = (TextView) view.findViewById(R.id.textViewEventName);
name.setText(currentEvent.getName());
TextView location = (TextView) view.findViewById(R.id.textViewLocation);
location.setText(currentEvent.getLocation());
TextView date = (TextView) view.findViewById(R.id.textViewDate);
date.setText(currentEvent.getDate());
TextView description = (TextView) view.findViewById(R.id.textViewDescription);
description.setText(currentEvent.getDescription());
TextView time = (TextView) view.findViewById(R.id.textViewTime);
time.setText(currentEvent.getTime());
TextView testnia = (TextView) view.findViewById(R.id.testnia);
testnia.setText(currentEvent.getUsername());
return view;
}
}
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, view, menuInfo);
menu.setHeaderIcon(R.drawable.huhu);// find a suitable icon
menu.setHeaderTitle("Event options:");
menu.add(Menu.NONE, _EDIT, Menu.NONE, "Edit Event");
menu.add(Menu.NONE, _DELETE, Menu.NONE, "Delete Event");
}
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case _EDIT:
// editing a contact
Intent editContactIntent = new Intent(getApplicationContext(), EditEvent.class);
startActivityForResult(editContactIntent, 2); // reqcode=2
break;
case _DELETE:
helper.deleteEvent(events.get(longClickedItemIndex));
events.remove(longClickedItemIndex);
eventsAdapter.notifyDataSetChanged();
break;
}
return super.onContextItemSelected(item);
}
}
And this is my DataBaseHelperEvent class
public class DatabaseHandlerEvent extends SQLiteOpenHelper {
static DatabaseHelperUser helper;
Event event;
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "Events";
private static final String TABLE_NAME = "Events";
private static final String COLUMN_ID = "id",
COLUMN_NAME = "name", COLUMN_LOCATION = "location", COLUMN_DATE = "date",
COLUMN_TIME ="time", COLUMN_DESCRIPTION = "description", COLUMN_USERNAME = "username";
SQLiteDatabase db;
public DatabaseHandlerEvent(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_NAME + " TEXT, " + COLUMN_LOCATION + " TEXT, " +
COLUMN_DATE + " TEXT, " + COLUMN_TIME + " TEXT, " +
COLUMN_DESCRIPTION + " TEXT, " + COLUMN_USERNAME + " TEXT)"
);
}
public long createEvent (Event event) {
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, event.getName());
values.put(COLUMN_LOCATION, event.getLocation());
values.put(COLUMN_DATE, event.getDate());
values.put(COLUMN_TIME, event.getTime());
values.put(COLUMN_DESCRIPTION, event.getDescription());
values.put(COLUMN_USERNAME, event.getUsername());
long result = db.insert(TABLE_NAME, null, values);
db.close();
return result;
}
public int updateEvent(Event event) {
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, event.getName());
values.put(COLUMN_LOCATION, event.getLocation());
values.put(COLUMN_DATE, event.getDate());
values.put(COLUMN_TIME, event.getTime());
values.put(COLUMN_DESCRIPTION, event.getDescription());
int rowsAffected = db.update(TABLE_NAME, values, COLUMN_ID + "=?",
new String[]{String.valueOf(event.getId())});
db.close();
return rowsAffected;
}
public List<Event> getAllEvent(String Username) {
List<Event> events = new ArrayList<Event>();
db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_NAME +" WHERE "+COLUMN_USERNAME+" = "+ "'"+Username+"'", null);
if (cursor.moveToFirst()) {
do {
events.add(new Event(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2),
cursor.getString(3), cursor.getString(4),
cursor.getString(5), cursor.getString(6)));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return events;
}
public int getEventCount() {
db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
int count = cursor.getCount();
cursor.close();
db.close();
return count;
}
public int deleteEvent(Event event) {
db = this.getWritableDatabase();
int rowsAffected = db.delete(TABLE_NAME, COLUMN_ID + "=?",
new String[]{String.valueOf(event.getId())});
db.close();
return rowsAffected;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String query = "DROP TABLE IF EXISTS "+TABLE_NAME;
db.execSQL(query);
this.onCreate(db);
}
}
So whenever i show my ListView, it will show nothing. How can i show the data that only have a specific username i want? thanks! Sorry for my bad english
I get following error in logcat when trying to retrieve all SQLite rows from SQLiteOpenHelper.
Caused by: java.lang.NullPointerException at notes.dev.tauhid.com.mynotes.fragment.MyNotes.onCreateView(MyNotes.java:89)
My SQLiteOpenHelper class is
public class DatabaseHandlerNotes extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "my_notes";
private static final String TABLE_NOTES = "my_notes_table";
private static final String KEY_ID = "id";
private static final String KEY_TITLE = "title";
private static final String KEY_DESCRIPTION = "phone_number";
private static final String KEY_DATE = "date";
private static final String KEY_REMINDER_DATE = "reminder_date";
private static final String KEY_CATEGORY = "category";
private static final String KEY_LOCK = "lock";
public DatabaseHandlerNotes(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_NOTES_TABLE = "CREATE TABLE " + TABLE_NOTES + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_TITLE + " TEXT,"
+ KEY_DESCRIPTION + " TEXT," + KEY_DATE + " INTEGER," + KEY_REMINDER_DATE + " INTEGER," + KEY_CATEGORY + " INTEGER," + KEY_LOCK + " TEXT" + ")";
db.execSQL(CREATE_NOTES_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NOTES);
onCreate(db);
}
public void addNote(Note note) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TITLE, note.getTitle());
values.put(KEY_DESCRIPTION, note.getDescription());
values.put(KEY_DATE, note.getDate());
values.put(KEY_REMINDER_DATE, note.getReminderDate());
values.put(KEY_CATEGORY, note.getCategory());
values.put(KEY_LOCK, note.getLock());
db.insert(TABLE_NOTES, null, values);
db.close();
}
public Note getNote(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NOTES, new String[] { KEY_ID,
KEY_TITLE, KEY_DESCRIPTION, KEY_DATE, KEY_REMINDER_DATE, KEY_CATEGORY }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Note note = new Note(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2), Integer.parseInt(cursor.getString(3)), Integer.parseInt(cursor.getString(4)), Integer.parseInt(cursor.getString(5)), cursor.getString(6));
return note;
}
public List<Note> getAllNotes() {
List<Note> noteList = new ArrayList<Note>();
String selectQuery = "SELECT * FROM " + TABLE_NOTES;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Note note = new Note();
note.setID(Integer.parseInt(cursor.getString(0)));
note.setTitle(cursor.getString(1));
note.setDescription(cursor.getString(2));
note.setDate(Integer.parseInt(cursor.getString(3)));
note.setReminderDate(Integer.parseInt(cursor.getString(4)));
note.setCategory(Integer.parseInt(cursor.getString(5)));
note.setLock(cursor.getString(6));
noteList.add(note);
} while (cursor.moveToNext());
}
return noteList;
}
public int updateNote(Note note) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TITLE, note.getTitle());
values.put(KEY_DESCRIPTION, note.getDescription());
values.put(KEY_DATE, note.getDate());
values.put(KEY_REMINDER_DATE, note.getReminderDate());
values.put(KEY_CATEGORY, note.getCategory());
values.put(KEY_LOCK, note.getLock());
// updating row
return db.update(TABLE_NOTES, values, KEY_ID + " = ?",
new String[] { String.valueOf(note.getID()) });
}
public void deleteNote(Note note) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NOTES, KEY_ID + " = ?",
new String[] { String.valueOf(note.getID()) });
db.close();
}
public int getNotesCount() {
String countQuery = "SELECT * FROM " + TABLE_NOTES;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
return cursor.getCount();
}
And in my Fragment class where i want to retrieve all rows
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
databaseHandlerNote = new DatabaseHandlerNotes(getActivity());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.my_notes_fragment_notes, container, false);
ListView allNotes = (ListView) rootView.findViewById(R.id.my_notes_all);
List<Note> noteList = databaseHandlerNote.getAllNotes();
for (Note note : noteList) {
Note noteEach = new Note();
noteEach.setID(note.getID());
noteEach.setTitle(note.getTitle());
noteEach.setDescription(note.getDescription());
noteEach.setCategory(note.getCategory());
noteEach.setLock(note.getLock());
noteEach.setDate(note.getDate());
noteEach.setReminderDate(note.getReminderDate());
this.customNotesList.add(noteEach);
}
customNoteAdapter = new CustomNoteAdapter(getActivity(), customNotesList);
allNotes.setAdapter(customNoteAdapter);
return rootView;
}
Here 89th line in onCreateView is
List<Note> noteList = databaseHandlerNote.getAllNotes();
Thanks in advance.
The problem is that onActivityCreated() is called after onCreateView(). Thus your databaseHandlerNote hasn't been created yet, and trying to use it will result in a NullPointerException.
Check out the Fragment lifecycle diagram from the Fragment documentation.
From Fragment lifecircle, onCreateView() is called before onActivityCreated(), so when you call:
List<Note> noteList = databaseHandlerNote.getAllNotes();
in onCreateView(), databaseHandlerNote is not yet created, then you got exception. So solution is that:
move your:
databaseHandlerNote = new DatabaseHandlerNotes(getActivity());
from onActivityCreated() to onCreate()
I have a problem with the following issue:
I have build an Android app which saves data into a SQL database (SQLite). I managed so the current date, time and the category is saved down and shown in a different menu. Somehow I am not able to get the value saved down and shown in the other layout. The data should come from an EditText: android:id="#+id/edit_betrag
The SQL column is defined like: public static final String BUDGET_BETRAG = "betrag";
and then should be shown in textView_betrag in the class BudgetRechnerAdapter respectively the other layout.
Can you please help me with this issue? Thanks a lot!!!
public class BudgetRechnerOpenHandler extends SQLiteOpenHelper {
private static final String TAG = BudgetRechnerOpenHandler.class
.getSimpleName();
// Name und Version der Datenbank
private static final String DATABASE_NAME = "budgetrechner.db";
private static final int DATABASE_VERSION = 1;
// Name und Attribute der Tabelle "Budget"
public static final String _ID = "_id";
public static final String TABELLE_NAME_BUDGET = "budget";
public static final String BUDGET_ZEIT = "zeitStempel";
public static final String BUDGET_AUSGABENART = "ausgabenArt";
public static final String BUDGET_BETRAG = "betrag";
// Konstanten für die Stimmungen
public static final int BUDGET_ESSEN = 1;
public static final int BUDGET_GETRAENK = 2;
public static final int BUDGET_SONSTIGES = 3;
// Tabelle Budget anlegen
private static final String TABELLE_BUDGET_ERSTELLEN = "CREATE TABLE "
+ TABELLE_NAME_BUDGET + " (" + _ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + BUDGET_ZEIT + " INTEGER, "
+ BUDGET_BETRAG + " INTEGER," + BUDGET_AUSGABENART + " INTEGER);";
// Tabelle Budget löschen
private static final String TABELLE_BUDGET_DROP = "DROP TABLE IF EXISTS "
+ TABELLE_NAME_BUDGET;
BudgetRechnerOpenHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABELLE_BUDGET_ERSTELLEN);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrade der Datenbank von Version " + oldVersion + " zu "
+ newVersion + "; alle Daten werden gelöscht");
db.execSQL(TABELLE_BUDGET_DROP);
onCreate(db);
}
public void insert(int art, String beschreibung, long zeit) {
long rowId = -1;
try {
// Datenbank öffnen
SQLiteDatabase db = getWritableDatabase();
// die zu speichernden Werte
ContentValues wert = new ContentValues();
wert.put(BUDGET_AUSGABENART, art);
wert.put(BUDGET_BETRAG, beschreibung);
wert.put(BUDGET_ZEIT, zeit);
// in die Tabelle Budget einfügen
rowId = db.insert(TABELLE_NAME_BUDGET, null, wert);
} catch (SQLiteException e) {
Log.e(TAG, "insert()", e);
} finally {
Log.d(TAG, "insert(): rowId=" + rowId);
}
}
public Cursor query() {
// ggf. Datenbank öffnen
SQLiteDatabase db = getWritableDatabase();
return db.query(TABELLE_NAME_BUDGET, null, null, null, null, null,
BUDGET_ZEIT + " DESC"
);
}
public void update(long id, int ausgabe_art_zahl) {
// ggf. Datenbank öffnen
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(BUDGET_AUSGABENART, ausgabe_art_zahl);
int numUpdated = db.update(TABELLE_NAME_BUDGET, values, _ID + " = ?",
new String[] { Long.toString(id) });
Log.d(TAG, "update(): id=" + id + " -> " + numUpdated);
}
public void delete(long id) {
// ggf. Datenbank öffnen
SQLiteDatabase db = getWritableDatabase();
int numDeleted = db.delete(TABELLE_NAME_BUDGET, _ID + " = ?",
new String[] { Long.toString(id) });
Log.d(TAG, "delete(): id=" + id + " -> " + numDeleted);
}
}
public class BudgetRechnerAdapter extends CursorAdapter {
private final Date datum;
private static final DateFormat DF_DATE = SimpleDateFormat
.getDateInstance(DateFormat.MEDIUM);
private static final DateFormat DF_TIME = SimpleDateFormat
.getTimeInstance(DateFormat.MEDIUM);
private Integer betrag;
private static final Integer DF_BETRAG = R.id.edit_betrag;
private LayoutInflater inflator;
private int ciAusgabenArt, ciZeit, ciBetrag;
public BudgetRechnerAdapter(Context context, Cursor c) {
super(context, c);
datum = new Date();
betrag = null;
inflator = LayoutInflater.from(context);
ciAusgabenArt = c.getColumnIndex(BudgetRechnerOpenHandler.BUDGET_AUSGABENART);
ciZeit = c.getColumnIndex(BudgetRechnerOpenHandler.BUDGET_ZEIT);
ciBetrag = c.getColumnIndex(BudgetRechnerOpenHandler.BUDGET_BETRAG);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
ImageView image = (ImageView) view.findViewById(R.id.icon);
int art = cursor.getInt(ciAusgabenArt);
TextView textView_art = (TextView) view.findViewById(R.id.text3);
if (art == BudgetRechnerOpenHandler.BUDGET_ESSEN) {
image.setImageResource(R.drawable.bild_essen);
textView_art.setText("Essen");
} else if (art == BudgetRechnerOpenHandler.BUDGET_GETRAENK) {
image.setImageResource(R.drawable.bild_getraenk);
textView_art.setText("Getränk");
} else {
image.setImageResource(R.drawable.bild_sonstiges);
textView_art.setText("Sonstiges");
}
TextView textView_Datum = (TextView) view.findViewById(R.id.text1);
TextView textView_Zeit = (TextView) view.findViewById(R.id.text2);
TextView textView_betrag = (TextView) view.findViewById(R.id.text4);
long zeitStempel = cursor.getLong(ciZeit);
datum.setTime(zeitStempel);
textView_Datum.setText(DF_DATE.format(datum));
textView_Zeit.setText(DF_TIME.format(datum));
textView_betrag.setText(DF_BETRAG.toString());
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return inflator.inflate(R.layout.verlauf, null);
}
}