Saving Object in SQLite Database, no exception - Android - android

I'm getting crazy right now with a problem, while saving an object in a SQLite database. I've got an UI in which you can insert some data in TextEdits and Checkboxes.
This is the BaseListFragment, which handles the UI for different types:
package de.financeplanner.ui.fragment;
import android.app.ListFragment;
import android.os.Bundle;
import android.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import java.util.ArrayList;
import de.financeplanner.R;
import de.financeplanner.constant.TabConstants;
import de.financeplanner.model.Category;
import de.financeplanner.model.Finance;
import de.financeplanner.model.Model;
import de.financeplanner.util.adapter.list.CategoryListAdapter;
import de.financeplanner.util.adapter.list.FinanceListAdapter;
import de.financeplanner.util.db.DBHelperCategory;
import de.financeplanner.util.db.DBHelperFinance;
/**
* Created by Christian on 20.01.2017.
*/
public class BaseListFragment extends ListFragment implements AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener {
private ArrayList<? extends Model> listData;
private short type;
public static BaseListFragment newInstance(short type){
BaseListFragment fragment = new BaseListFragment();
Bundle arguments = new Bundle();
arguments.putShort("type", type);
fragment.setArguments(arguments);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_base_list, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
type = getArguments().getShort("type");
listData = loadListData(type);
initList();
initAddButton();
// getListView().setOnItemClickListener(this);
}
private ArrayList<? extends Model> loadListData(short type){
switch (type) {
case TabConstants.OVERVIEW:
return loadFinances();
case TabConstants.REVENUE:
return loadRevenues();
case TabConstants.EXPENSE:
return loadExpenses();
case TabConstants.CATEGORY:
return loadCategories();
}
return null;
}
private ArrayList<Finance> loadFinances() {
DBHelperFinance dbHelper = new DBHelperFinance(getContext());
return dbHelper.getAll();
}
private ArrayList<Finance> loadRevenues() {
DBHelperFinance dbHelper = new DBHelperFinance(getContext());
return dbHelper.getRevenues();
}
private ArrayList<Finance> loadExpenses() {
DBHelperFinance dbHelper = new DBHelperFinance(getContext());
return dbHelper.getExpanse();
}
private ArrayList<Category> loadCategories() {
DBHelperCategory dbHelper = new DBHelperCategory(getContext());
return dbHelper.getAll();
}
private void initList() {
ArrayAdapter adapter = null;
if (listData != null) {
if (type != TabConstants.CATEGORY) {
adapter = new FinanceListAdapter(getContext(), (ArrayList<Finance>)listData);
}else{
adapter = new CategoryListAdapter(getContext(), (ArrayList<Category>)listData);
}
setListAdapter(adapter);
}
}
private void initAddButton() {
ImageButton addButton = (ImageButton) getActivity().findViewById(R.id.add_button);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentTransaction trans = getFragmentManager().beginTransaction();
if(type != TabConstants.CATEGORY){
trans.replace(R.id.fragment_container, AddFinanceFragment.newInstance());
trans.addToBackStack(null).commit();
}else{
trans.replace(R.id.fragment_container, AddCategoryFragment.newInstance());
trans.addToBackStack(null).commit();
}
}
});
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
}
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
return false;
}
}
For explanation:
You cann choose 4 different tabs (overview, revenue, expense and category). The UI is every time the same, only the data inside changes.
Now, when I click on the addButton inside the category tab and insert data, the data is saved inside the database and the listview is correctly updated.
This is the called method to save the category.
private void onSaveRequest(){
Category category = new Category();
category.setTitle(title.getText().toString());
category.setDescription(description.getText().toString());
DBHelperCategory dbHelper = new DBHelperCategory(getContext());
dbHelper.saveOrUpdate(category);
getFragmentManager().popBackStack();
}
And this is the DBHelper method, which is called to save the category:
public void saveOrUpdate(Category category){
ContentValues values = new ContentValues();
values.put("title", category.getTitle());
values.put("description", category.getDescription());
if(category.getId() == 0){
save(values);
} else {
update(values);
}
}
private void save(ContentValues values){
SQLiteDatabase db = getWritableDatabase();
db.insert("category", null, values);
}
This is the method, to get categories from the database:
public ArrayList<Category> getAll(){
ArrayList<Category> categories = new ArrayList<Category>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor rows = db.rawQuery(GET_ALL_QUERY, null);
rows.moveToFirst();
while(!rows.isAfterLast()){
Category category = new Category();
category.setId(rows.getInt(0));
category.setTitle(rows.getString(1));
category.setDescription(rows.getString(2));
categories.add(category);
rows.moveToNext();
}
return categories;
}
The problem is, when I click the addButton inside the overview, revenue or expense tab, no data is insert into database and the listview is not updated.
And this the method, which is called, when the saveButton is pressed:
private void onSaveRequest(){
Finance finance = new Finance();
finance.setTitle(title.getText().toString());
finance.setCategoryID(0);
finance.setDescription(description.getText().toString());
finance.setPayment(Double.parseDouble(payment.getText().toString()));
finance.setExpense(expense.isChecked());
finance.setDate(date.getText().toString());
DBHelperFinance dbHelper = new DBHelperFinance(getContext());
dbHelper.saveOrUpdate(finance);
getFragmentManager().popBackStack();
}
And this is the method inside the DBHelper, which should insert the data in the database:
public void saveOrUpdate(Finance finance){
ContentValues values = new ContentValues();
values.put("title", finance.getTitle());
values.put("categoryID", finance.getCategoryID());
values.put("description", finance.getDescription());
values.put("payment", finance.getPayment());
values.put("expense", finance.isExpense() ? 1 : 0);
values.put("date", finance.getDate());
if(finance.getId() == 0){
save(values);
} else {
update(values);
}
}
private void save(ContentValues values){
SQLiteDatabase db = getWritableDatabase();
db.insert("finance", null, values);
}
This are the methods, to get the finances from the database:
private ArrayList<Finance> getAll(short condition){
ArrayList<Finance> finances = new ArrayList<Finance>();
SQLiteDatabase db = this.getReadableDatabase();
String whereClause = new String();
final String join = " INNER JOIN CATEGORY ON FINANCE.categoryID = CATEGORY.ID ";
if(condition != 0){
whereClause = condition == 1 ? " WHERE EXPENSE = 0 " : "WHERE EXPENSE = 1";
}
String query = GET_ALL_QUERY + join + whereClause;
Cursor rows = db.rawQuery(query, null);
rows.moveToFirst();
while(!rows.isAfterLast()){
Finance finance = new Finance();
finance.setId(rows.getInt(0));
finance.setTitle(rows.getString(1));
finance.setCategoryID(rows.getInt(2));
finance.setCategory(rows.getString(3));
finance.setDescription(rows.getString(4));
finance.setPayment(rows.getDouble(5));
finance.setExpense(rows.getInt(6) == 1);
finance.setDate(rows.getString(7));
finances.add(finance);
rows.moveToNext();
}
return finances;
}
To complete this, here is the super class for every DBHelper:
package de.financeplanner.util.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by Christian on 20.01.2017.
*/
public class DBHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "financeDB";
public DBHelper(Context context) {
super(context, DATABASE_NAME , null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE FINANCE " +
"(ID INTEGER PRIMARY KEY AUTOINCREMENT, TITLE VARCHAR(50), CATEGORYID INTEGER," +
"DESCRIPTION VARCHAR(240), PAYMENT DECIMAL(8,2), EXPENSE BOOLEAN," +
"DATE STRING); ");
db.execSQL("CREATE TABLE CATEGORY " +
"(ID INTEGER PRIMARY KEY AUTOINCREMENT, TITLE VARCHAR(50), DESCRIPTION VARCHAR(240));");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS FINANCE");
db.execSQL("DROP TABLE IF EXISTS CATEGORY");
onCreate(db);
}
}
I've debugged the app and can't find anything wrong. (Just, that every ArrayList is empty, so nothing is insert into database). Even there is no exception or other error shown, so I think the Syntax and the fields for the database is also right. Strange is also, that in the morning everything worked and I really don't know, what I've changed that everything goes wrong right now.

Related

Setting up Model Class and Custom Adapter to get SQLite DB rowID from onListItemClick

I have an app that populates from a pre-existing SQLite database. I am now in need of obtaining the rowID (_id) when a list item is clicked. I think that I did not set my app up properly to be able to do that. I have had people provide me with input on what to do but I can't seem to understand it when trying to apply it to my app. Can someone please provide an example using my code? I would really appreciate it.
Here is my model class:
package com.mypackage.myapp.model;
import android.database.Cursor;
public class Verse {
private Cursor verseCursor;
private String verseNotificationString;
private String verseTitleString;
private int dBrowIdInt;
private String bookNameString;
private String chapterNumberString;
private String verseNumberString;
private String verseString;
public Verse(Cursor cursor, String bookNameString, String chapterNumberString, String verseNumberString, String verseString) {
verseCursor = cursor;
verseTitleString = bookNameString + " " + chapterNumberString + ":" + verseNumberString;
verseNotificationString = verseString;
}
public Verse(int dBrowId) {
dBrowIdInt = dBrowId;
}
public Cursor getVerseCursor() {
return verseCursor;
}
public void setVerseCursor(Cursor verseCursor) {
this.verseCursor = verseCursor;
}
public String getVerseTitleString() {
return verseTitleString;
}
public String getNotificationString() {
return verseNotificationString;
}
public Integer getDbRowId() {
return dBrowIdInt;
}
public void setNotificationString(String notificationString) {
this.verseNotificationString = notificationString;
}
public void setTitleString(String titleString) {
this.verseTitleString = titleString;
}
}
Here is my custom adapter:
package com.mypackage.myapp;
import android.content.Context;
import android.content.SharedPreferences;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
public class VerseAdapter extends ArrayAdapter<String> {
private Context mContext;
private int mResource1;
private int mResource2;
public List<String> mVerses;
private List<Long> mRowId;
private TextView mVerseTextView;
private TextView mVerseNumberTextView;
private TextView mRowIdTextView;
private boolean mNightModeSwitchState;
private boolean mNightModeTwoSwitchState;
public VerseAdapter(Context context, int resource1, List<String>
verses, List<Long> rowId) {
super(context, resource1, verses);
this.mContext = context;
this.mResource1 = resource1;
this.mVerses = verses;
this.mRowId = rowId;
}
#Override
public int getCount() {
return mVerses.size();
}
#Override
public long getItemId(int position) {
return (position);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView,
#NonNull ViewGroup parent) {
View listItem = convertView;
int pos = position + 1;
if (listItem == null) {
listItem =
LayoutInflater.from(mContext).inflate(mResource1, parent, false);
}
//mRowIdTextView = (TextView)
listItem.findViewById(R.id.rowId);
//mRowIdTextView.setText(String.valueOf(getItemId(position)));
//mRowIdTextView.setText(String.valueOf(mRowId.get(position)));
mVerseNumberTextView = (TextView)
listItem.findViewById(R.id.verseNumber);
mVerseNumberTextView.setText(String.valueOf(pos) + " ");
mVerseTextView = (TextView)
listItem.findViewById(R.id.verseWords);
mVerseTextView.setText(mVerses.get(position));
SharedPreferences nightModeSwitchState =
getContext().getSharedPreferences("SettingsActivity", 0);
mNightModeSwitchState =
nightModeSwitchState.getBoolean("NightModeSwitchState", false);
SharedPreferences rowPosition =
getContext().getSharedPreferences("RowPosition", 0);
rowPosition.edit().putInt("RowPositionSqlite",
position).apply();
return listItem;
}
}
Here is my onListItemClick mehtod in the class that I need to access the rowID from (You can see some stuff that I tried and didn't work commented out):
mListView.setOnItemClickListener(new
AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View
view, int position, long id) {
String selected = (String)
mListView.getItemAtPosition(position);
mVerseTextView = findViewById(R.id.verseWords);
mVerseNumberTextView = findViewById(R.id.verseNumber);
mAdapterView = adapterView;
mPositionForRow = position;
//mIdLong = id;
// VerseAdapter verseAdapter = (VerseAdapter)
adapterView.getAdapter();
// mSelectedVerse = (VerseForId)
mListView.getItemAtPosition(position);
// mDbRowId = mSelectedVerse.getDbRowId();
// mIdLong = verseAdapter.getItemId(position);
// mRowIdString = String.valueOf(id);
// VerseAdapter da = (VerseAdapter)
adapterView.getAdapter();
//mRowIdString =
String.valueOf(da.mVerses.get(position).getId());
// Toast.makeText(BibleBookVersesOldTestActivity.this,
mRowIdString + " id", Toast.LENGTH_LONG).show();
mBookCopied =
mVerseHeaderBookNameTextView.getText().toString();
mChapterNumberCopied =
Integer.toString(mChapterSelected + 1);
mVerseNumberCopied =
mVerseNumberTextView.getText().toString();
mPosition = position + 1;
mCopiedVerseListItem = mBookCopied + " " +
mChapterNumberCopied + ":" + mPosition + "\n\n" + selected;
showMenuVerseAction(view);
}
});
I know that I need to do something in my model class and custom adapter to set it up to be able to retrieve the database rowID onlistitemclick. Can someone possibly give me an example using my code? Thank you for your help.
*******Addition.... this is my Databaseaccess class.... well one section of it where I draw verses from a certain book from the SQLite Database. I have adjusted the other class that populates the list and therefor had to change the below operation to take in the model class Verse instead of String in the list... the problem I have is that the line below that reads list.add(cursor.getString(6)) where the (6) refers to the column index where to pull the verse from... gives an error that I can't apply that getString to Verse... how do I resolve this?
public List<Verse> getVersesChapterOne() {
List<Verse> list = new ArrayList<>();
Cursor cursor = database.rawQuery("SELECT * FROM bookcombinedfull
LIMIT 31", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
list.add(cursor.getString(6));
cursor.moveToNext();
}
cursor.close();
return list;
}
One idea is to replace the Custom Adapter's list from String to your model Verse. In this way, you can use the .getItem() to retrieve whatever information you want from your model class.
// public class VerseAdapter extends ArrayAdapter<String> {
public class VerseAdapter extends BaseAdapter {
public List<String> mVerses;
// public VerseAdapter(Context context, int resource1, List<String> verses, List<Long> rowId) {
public VerseAdapter(Context context, int resource1, List<Verse> verses) {
//...
mVerses = verses;
//...
#Override
public Object getItem(int i) {
return (Verse)mList.get(i);
}
// ...
// In your MainActivity.java, do this to get your item:
Verse verse = (Verse) mAdapter.getItem(position);
Log.d(TAG, verse.getVerseTitleString());

Multiple Table Android SQLite with Loader Callbacks

I'm trying to create a patient registration app in android but I'm currently stuck on how to achieved a multiple table to relate with and add to loader callback method.
The First table is for patient fullname.
And the Second table is for patient information foreign key to the id of the patient_fullname table.
Can someone here explain or help me on how to achieved this output?
Appreciate for any help.
PatienDBOpenHelper.java
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class PatientDBOpenHelper extends SQLiteOpenHelper{
//Constants for db name and version
private static final String LOGTAG = "DENTALAPP";
private static final String DATABASE_NAME = "dental.db";
private static final int DATABASE_VERSION = 1;
//Constants for identifying table and columns
public static final String TABLE_PATIENT = "patient";
public static final String PATIENT_ID = "_id";
public static final String PATIENT_NAME = "nameInfo";
public static final String PATIENT_GENDER = "genderInfo";
public static final String PATIENT_CREATED = "patientCreated";
/*I will put my desired table structure here
_id
patientId
address
occupation
etc....
*/
public static final String[] ALL_COLUMNS = {PATIENT_ID, PATIENT_NAME, PATIENT_GENDER,PATIENT_CREATED};
//SQL to create table
private static final String TABLE_CREATE_PATIENT =
"CREATE TABLE " + TABLE_PATIENT + " (" +
PATIENT_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
PATIENT_NAME + " TEXT, " +
PATIENT_GENDER + " TEXT, " +
PATIENT_CREATED + " TEXT default CURRENT_TIMESTAMP" +
")";
/*
Will also add query statement here for another table.
*/
public PatientDBOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
/*
Add the creation of other table.
*/
sqLiteDatabase.execSQL(TABLE_CREATE_PATIENT);
Log.i(LOGTAG,"Table Created!");
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
/*
Add the query of my additional drop table.
*/
sqLiteDatabase.execSQL("DROP TABLE IF EXIST " + TABLE_PATIENT);
onCreate(sqLiteDatabase);
}
}
PatientDataSource.java
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.bloxofcode.multipletabs.model.Patient;
public class PatientDataSource {
private static final String LOGTAG = "DENTALAPP";
SQLiteOpenHelper dbhelper;
SQLiteDatabase database;
public PatientDataSource(Context context){
dbhelper = new PatientDBOpenHelper(context);
}
public void open(){
Log.i(LOGTAG,"Database open");
database = dbhelper.getWritableDatabase();
}
public void close(){
Log.i(LOGTAG,"Database close");
dbhelper.close();
}
public Patient create(Patient patient){
ContentValues values = new ContentValues();
values.put(PatientDBOpenHelper.PATIENT_NAME,patient.getPatientFullName());
values.put(PatientDBOpenHelper.PATIENT_GENDER,patient.getPatientGender());
long id = database.insert(PatientDBOpenHelper.TABLE_PATIENT,null,values);
patient.setId(id);
return patient;
}
}
Tab1.java
public class Tab1 extends Fragment implements LoaderManager.LoaderCallbacks<Cursor>{
private ImageButton imgButton;
private CustomDialog customDialog;
private TextView tvNoRecord;
private ImageView imgNoRecord;
private CursorAdapter cursorAdapter;
PatientDataSource patientDataSource;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
patientDataSource = new PatientDataSource(getActivity());
patientDataSource.open();
final View v =inflater.inflate(R.layout.tab_1,container,false);
imgButton = (ImageButton) v.findViewById(R.id.imageButton);
imgNoRecord = (ImageView) v.findViewById(R.id.imgNoRecord);
tvNoRecord = (TextView) v.findViewById(R.id.tvNoRecord);
//Creating ImageButton
imgButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
customDialog = new CustomDialog(getActivity());
customDialog.setDialogResult(new OnMyDialogResult() {
#Override
public void finish(String resultName, String resultGender) {
if (!resultName.isEmpty()){
Log.d("TestingUnit","asdadasdsa");
Patient patient = new Patient();
patient.setPatientFullName(resultName);
patient.setPatientGender(resultGender);
patientDataSource.create(patient);
restartLoader();
}
listPatient(v);
}
});
customDialog.show();
}
});
listPatient(v);
return v;
}
private void listPatient(View v){
cursorAdapter = new PatientCursorAdapter(getActivity(),null,0 );
ListView list = (ListView) v.findViewById(android.R.id.list);
list.setAdapter(cursorAdapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String info = ((TextView) view.findViewById(R.id.tvName)).getText().toString();
Intent i = new Intent(getContext(), UserInfoActivity.class);
i.putExtra("PersonName", info);
startActivity(i);
}
});
getLoaderManager().initLoader(0,null,this);
}
private void restartLoader(){
getLoaderManager().restartLoader(0,null,this);
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new CursorLoader(getActivity(), PatientProvider.CONTENT_URI,null,null,null,null);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
if(data.getCount() > 0){
imgNoRecord.setVisibility(View.INVISIBLE);
tvNoRecord.setVisibility(View.INVISIBLE);
}else{
imgNoRecord.setVisibility(View.VISIBLE);
tvNoRecord.setVisibility(View.VISIBLE);
}
cursorAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
cursorAdapter.swapCursor(null);
}
#Override
public void onResume() {
super.onResume();
patientDataSource.open();
}
#Override
public void onPause() {
super.onPause();
patientDataSource.close();
}
}
This is where i will get the 1st table(patient full name):
This is where the 2nd table will show its data(patient info):

Database delete function not working

Hello all I have got somthing wrong while deleting items from database.I have a list of schools in one activity.THis is my screen shot
[![Schools.java][1]][1]
At the top of schooldetails.class I have an star icon to bookmark the school.On clicking the bookmark icon the icon changes to filled one and the respective schools get saved to my bookmark class.Till this everything is working fine.Now I am trying to implement bookmark deletion on re-clicking the filled star icon.I wish to remove the bookmarked school from bookmark class.This is what I did inside Schooldetails class
package com.example.user.educationhunt;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import com.example.user.educationhunt.database.DatabaseHelper;
import com.example.user.educationhunt.fragment.About;
import com.example.user.educationhunt.fragment.Admission;
import com.example.user.educationhunt.fragment.FeeStructure;
import com.example.user.educationhunt.listner.DatabaseUpdatedListener;
import com.example.user.educationhunt.pojos.Bookmarkitem;
import com.example.user.educationhunt.pojos.OurSchool;
import java.util.ArrayList;
import java.util.List;
public class SchoolDetails extends AppCompatActivity implements DatabaseUpdatedListener {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
Boolean isStarFilled = false;
DatabaseHelper db;
OurSchool ourSchool;
private Menu menu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_school_details);
ourSchool = (OurSchool) getIntent().getSerializableExtra("school");
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(ourSchool.getSchoolName());
db = new DatabaseHelper(this);
db.databaseUpdatedListener = this;
Toast.makeText(this, ourSchool.getSchoolName(), Toast.LENGTH_SHORT).show();
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.fav_school, menu);
this.menu = menu;
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.star_School:
Bookmarkitem bookmarkitem = new Bookmarkitem();
bookmarkitem.setBookmarkID(ourSchool.getSchoolId());
bookmarkitem.setName(ourSchool.getSchoolName());
bookmarkitem.setLogo(ourSchool.getSchoolLogo());
bookmarkitem.setAddress(ourSchool.getSchoolAddress());
db.addSchoolBookmark(bookmarkitem, item);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
List<Bookmarkitem> bookmarkitems = db.getAllSchoolBookmark();
if (bookmarkitems.size() != 0) {
for (Bookmarkitem bookmarkitem : bookmarkitems) {
if (bookmarkitem.getBookmarkID() == ourSchool.getSchoolId()) {
isStarFilled = true;
break;
}
else isStarFilled=false;
}
if (isStarFilled) {
menu.getItem(0).setIcon(getResources().getDrawable(R.mipmap.starfilled));
}else if (isStarFilled.booleanValue()==true){
delete();
menu.getItem(0).setIcon(getResources().getDrawable(R.mipmap.star));
}
}
return true;
}
public void delete(){
List<Bookmarkitem> bookmarkitems = db.getAllSchoolBookmark();
db.removeBookmarkItem(ourSchool.getSchoolId()); }
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new About(), "ABOUT US");
adapter.addFragment(new Admission(), "ADMISSION");
adapter.addFragment(new FeeStructure(), "FEE");
viewPager.setAdapter(adapter);
}
#Override
public void setDatabaseSuccess(String schoolName, MenuItem item) {
Toast.makeText(this, schoolName + "successfully added as bookmark", Toast.LENGTH_SHORT).show();
item.setIcon(R.mipmap.starfilled);
}
#Override
public void setDatabaseError(String failureMessage) {
Toast.makeText(this, failureMessage, Toast.LENGTH_SHORT).show();
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
And this is my database class
package com.example.user.educationhunt.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.view.MenuItem;
import com.example.user.educationhunt.listner.DatabaseUpdatedListener;
import com.example.user.educationhunt.pojos.Bookmarkitem;
import java.util.ArrayList;
import java.util.List;
/**
* Created by user on 11/22/2016.
*/
public class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseUpdatedListener databaseUpdatedListener;
static final String DATABASE_NAME = "BookmarkDatabase";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME_BOOKMARK = "bookmark";
// Contact table columns name
private static final String ID = "Id";
private static final String NAME = "Name";
private static final String LOGO = "Logo";
private static final String LOCATION = "Location";
String createTableBookmark = "Create table if not exists `Bookmark` ("
+ "`name` TEXT," + "`location` TEXT," + "`logo` TEXT);";
String CREATE_SCHOOL_BOOKMARK_TABLE = "CREATE TABLE " + TABLE_NAME_BOOKMARK + "("
+ ID + " INTEGER PRIMARY KEY, "
+ NAME + " TEXT, "
+ LOGO + " TEXT, "
+ LOCATION + " TEXT " + ")";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void insertBookmarkData(Bookmarkitem bookmarkitem) {
SQLiteDatabase db = getWritableDatabase();
ContentValues content = new ContentValues();
content.put("name", bookmarkitem.name);
content.put("location", bookmarkitem.address);
content.put("logo", bookmarkitem.logo);
db.insert("Bookmark", null, content);
}
public ArrayList<Bookmarkitem> getBookmarkist() {
String sql = "select * from Bookmark ";
ArrayList<Bookmarkitem> bookmarklist = new ArrayList<Bookmarkitem>();
Cursor c = getWritableDatabase().rawQuery(sql, null);
while (c.moveToNext()) {
Bookmarkitem info = new Bookmarkitem();
info.name = c.getString(c.getColumnIndex("name"));
info.address = c.getString(c.getColumnIndex("location"));
info.logo = c.getString(c.getColumnIndex("logo"));
bookmarklist.add(info);
}
c.close();
return bookmarklist;
}
public Bookmarkitem getBookmarkData(String bookmarkName) {
String sql = "select * from Bookmark where id='" + bookmarkName + "'";
Cursor c = getWritableDatabase().rawQuery(sql, null);
while (c.moveToNext()) {
Bookmarkitem info = new Bookmarkitem();
info.name = c.getString(c.getColumnIndex("name"));
info.address = c.getString(c.getColumnIndex("location"));
info.logo = c.getString(c.getColumnIndex("logo"));
}
c.close();
Bookmarkitem info = null;
return info;
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
// TODO Auto-generated method stub
sqLiteDatabase.execSQL(CREATE_SCHOOL_BOOKMARK_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int arg1, int arg2) {
// TODO Auto-generated method stub
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_BOOKMARK);
onCreate(sqLiteDatabase);
}
public void addSchoolBookmark(Bookmarkitem bookmarkitem, MenuItem menuItem) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(ID, bookmarkitem.getBookmarkID());
values.put(NAME, bookmarkitem.getName());
values.put(LOGO, bookmarkitem.getLogo());
values.put(LOCATION, bookmarkitem.getAddress());
//inserting row
if (db.insert(TABLE_NAME_BOOKMARK, null, values) != -1) {
databaseUpdatedListener.setDatabaseSuccess(bookmarkitem.getName(), menuItem);
} else {
databaseUpdatedListener.setDatabaseError("Failed to insert");
}
db.close();
}
public List<Bookmarkitem> getAllSchoolBookmark() {
SQLiteDatabase db = this.getWritableDatabase();
String selectQuery = "SELECT * FROM " + TABLE_NAME_BOOKMARK;
List<Bookmarkitem> bookmarkitems = new ArrayList<>();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Bookmarkitem bookmarkitem = new Bookmarkitem();
bookmarkitem.setBookmarkID(Integer.parseInt(cursor.getString(0)));
bookmarkitem.setName(cursor.getString(1));
bookmarkitem.setLogo(cursor.getString(2));
bookmarkitem.setAddress(cursor.getString(3));
bookmarkitems.add(bookmarkitem);
} while (cursor.moveToNext());
}
return bookmarkitems;
}
public void removeBookmarkItem(int sID) {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_NAME_BOOKMARK + " WHERE " + ID + "= '" + sID + "'");
db.close();
}
}
In addition to this ,On clicking to the list inside bookmarked class items.I wish to load the details of respective class.This is my bookmark claass
package com.example.user.educationhunt;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import com.example.user.educationhunt.adapter.BookmarkAdapter;
import com.example.user.educationhunt.database.DatabaseHelper;
import com.example.user.educationhunt.pojos.Bookmarkitem;
import java.util.ArrayList;
import java.util.List;
public class Bookmark extends AppCompatActivity {
private List<Bookmarkitem> ourBookmarkListItems = new ArrayList<Bookmarkitem>();
private ListView listView;
private BookmarkAdapter adapter;
DatabaseHelper dbhelper;
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bookmark);
dbhelper = new DatabaseHelper(this);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setPadding(0, getStatusBarHeight(), 0, 0);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Bookmark");
List<Bookmarkitem> bookmarkedSchools = dbhelper.getAllSchoolBookmark();
listView = (ListView) findViewById(R.id.list_bookmarked);
if (bookmarkedSchools.size() != 0) {
adapter = new BookmarkAdapter(this, bookmarkedSchools);
listView.setAdapter(adapter);
} else {
Toast.makeText(this, "You have no bookmark yet.", Toast.LENGTH_SHORT).show();
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
startActivity(new Intent(Bookmark.this,SchoolDetails.class));
}
});
}
public int getStatusBarHeight() {
int result = 0;
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = getResources().getDimensionPixelSize(resourceId);
}
return result;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
I am neither getting any error nor proper result.Someone please help
Use this in your helper class :D
public boolean removeBookmarkItem(String id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME_BOOKMARK, ID + "=" + id, null) > 0;
}
You can check yours delete method through db. You can download DB browser for SQLite and open your db file with this browser and check, if you're really deleting bookmark state, if not maybe there is problem with query.

RecyclerView does not update after deleting an item from sqlite? [duplicate]

This question already has answers here:
How to update RecyclerView Adapter Data
(16 answers)
Closed 2 years ago.
I have populated recyclerview from sqlite .when clicking each row ,row will delete from sqlite but recyclerview not showing updated list after delete. Recycler view show updated list only after launching activity once again. My question is how to update the recycler view soon after deleting an item from the recylcerview without refresh.
following are my code
SecondActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import java.util.ArrayList;
import java.util.List;
public class SecondActivity extends AppCompatActivity {
DatabaseHelpher helpher;
List<DatabaseModel> dbList;
RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
helpher = new DatabaseHelpher(this);
dbList= new ArrayList<DatabaseModel>();
dbList = helpher.getDataFromDB();
mRecyclerView = (RecyclerView)findViewById(R.id.recycleview);
mRecyclerView.setHasFixedSize(true);
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
// specify an adapter (see also next example)
mAdapter = new RecyclerAdapter(this,dbList);
mRecyclerView.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged ();
}
#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_second, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
DatabaseHelpher.java
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class DatabaseHelpher extends SQLiteOpenHelper {
private static final String DATABASE_NAME="student";
private static final int DATABASE_VERSION = 1;
private static final String STUDENT_TABLE = "stureg";
private static final String STU_TABLE = "create table "+STUDENT_TABLE +"(name TEXT,email TEXT primary key,roll TEXT,address TEXT,branch TEXT)";
Context context;
public DatabaseHelpher(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(STU_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + STUDENT_TABLE);
// Create tables again
onCreate(db);
}
/* Insert into database*/
public void insertIntoDB(String name,String email,String roll,String address,String branch){
Log.d("insert", "before insert");
// 1. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// 2. create ContentValues to add key "column"/value
ContentValues values = new ContentValues();
values.put("name", name);
values.put("email", email);
values.put("roll", roll);
values.put("address", address);
values.put("branch", branch);
// 3. insert
db.insert(STUDENT_TABLE, null, values);
// 4. close
db.close();
Toast.makeText(context, "insert value", Toast.LENGTH_LONG);
Log.i("insert into DB", "After insert");
}
/* Retrive data from database */
public List<DatabaseModel> getDataFromDB(){
List<DatabaseModel> modelList = new ArrayList<DatabaseModel>();
String query = "select * from "+STUDENT_TABLE;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query,null);
if (cursor.moveToFirst()){
do {
DatabaseModel model = new DatabaseModel();
model.setName(cursor.getString(0));
model.setEmail(cursor.getString(1));
model.setRoll(cursor.getString(2));
model.setAddress(cursor.getString(3));
model.setBranch(cursor.getString(4));
modelList.add(model);
}while (cursor.moveToNext());
}
Log.d("student data", modelList.toString());
return modelList;
}
/*delete a row from database*/
public void deleteARow(String email){
SQLiteDatabase db= this.getWritableDatabase();
db.delete(STUDENT_TABLE, "email" + " = ?", new String[] { email });
db.close();
}
}
DatabaseModel.java
public class DatabaseModel {
private String name;
private String roll;
private String address;
private String branch;
private String email;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRoll() {
return roll;
}
public void setRoll(String roll) {
this.roll = roll;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getBranch() {
return branch;
}
public void setBranch(String branch) {
this.branch = branch;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
RecyclerAdapter.java
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
static List<DatabaseModel> dbList;
static Context context;
static DatabaseHelper dh;
RecyclerAdapter(Context context, List<DatabaseModel> dbList ){
this.dbList = new ArrayList<DatabaseModel>();
this.context = context;
this.dbList = dbList;
dh=new DatabaseHelper(context);
}
#Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(
R.layout.item_row, null);
// create ViewHolder
ViewHolder viewHolder = new ViewHolder(itemLayoutView);
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerAdapter.ViewHolder holder, int position) {
holder.name.setText(dbList.get(position).getName());
holder.email.setText(dbList.get(position).getEmail());
}
#Override
public int getItemCount() {
return dbList.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView name,email;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
name = (TextView) itemLayoutView
.findViewById(R.id.rvname);
email = (TextView)itemLayoutView.findViewById(R.id.rvemail);
itemLayoutView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
dh.delete(dbList.get(getAdapterPosition()).getEmail);
Toast.makeText(RecyclerAdapter.context, "you have clicked Row " + getAdapterPosition(), Toast.LENGTH_LONG).show();
}
}
}
i have tried to update recyclerview using mAdapter.notifyDataSetChanged (); but it doesn't working for me.please sugget me.Thank you
Remove data from both from your arraylist and from database and than notify your list will update.
or
Delete data from database and after delete get data from database and reload your arraylist with new data will do your work
dbList.remove(getAdapterPosition());
notifyDataSetChanged();
//or use this for better perfomance.
notifyItemRemoved(getAdapterPosition());
Pass position in remove method
You just need to notify adapter that one item is removed, inside onClick method
#Override
public void onClick(View v) {
notifyItemRemoved(this.getLayoutPosition());
}
You are deleting data from DB but not from list in which you have fetch all data so untill you delete data from list, it will show you even if it is deleted. So you need to change your delete method and also need to remove data from list also.
Check below updated method of deletion.
#Override
public void onClick(View v) {
dh.delete(dbList.get(getAdapterPosition()).getEmail);
// These two lines added for remove data from adapter also.
dbList.remove(getAdapterPosition());
notifyDataSetChanged();
Toast.makeText(RecyclerAdapter.context, "you have clicked Row " + getAdapterPosition(), Toast.LENGTH_LONG).show();
}
Try reloading the info.
Change this
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
To this:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
dbList = helpher.getDataFromDB();
mAdapter = new RecyclerAdapter(this,dbList);
mRecyclerView.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged ();
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
That will reload the information at your Recycler Vuew with every click.
//Define an interface in the Adapter class
private static ItemClickListener itemClickListener;
public interface ItemClickListener {
void onItemClick(int position, View v);
}
and a method
public void setOnItemClickListener(ItemClickListener myClickListener) {
RecyclerAdapter.itemClickListener = myClickListener;
}
in onClick method of viewHolder
#Override
public void onClick(View v) {
dh.delete(dbList.remove(getAdapterPosition()).getEmail);
itemClickListener.onItemClick(getLayoutPosition(), v);
Toast.makeText(RecyclerAdapter.context, "you have clicked Row " + getAdapterPosition(), Toast.LENGTH_LONG).show();
}
In your Activity's onCreate() or onResume() method
mAdapter.setOnItemClickListener(new RecyclerAdapter.ItemClickListener() {
#Override
public void onItemClick(int position, View v) {
mAdapter.notifyDataSetChanged();
}
});
You can call recreate() after performing the delete operation in your activity so you can refresh the activity. it works for me. Hope this will work you as well.
Remove the list data from arrayList using
arrayList.remove(position);
And update your Adapter using,
mAdapter.notifyDataSetChanged ();
use notifyItemRemoved() instead of notifyDataSetChanged()
Do It like this
builder.setNeutralButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
PersonDBHelper dbHelper = new PersonDBHelper(mContext);
dbHelper.deletePersonRecord(person.getId(), mContext);
mPeopleList.remove(position);
mRecyclerV.removeViewAt(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, mPeopleList.size());
notifyDataSetChanged();
}
});
and Use the On restart method in the recycle list

(Android) What have I done wrong in my code while trying to populate a spinner with database info

I am make data show that up in a spinner that consists of food objects (name, calories) that gets created in my main, and then make these objects (just the name for now) show up in a spinner that is on the activity. This activity will actually become a part of a larger program, and eventually I want to be able to allow the user the ability to "count" the total amount of calories that they have eaten by added up all the foods selected. For now, I just want to be able to make the foods appear so I can move further along. However, whenever I go to run it, my app just crashes with no error message stated the problem. If anyone knows what I need to do, please help. My code below:
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.List;
public class MainActivity extends ActionBarActivity implements
OnItemSelectedListener {
MyDBHandler dbHandler = new MyDBHandler(this, null, null, 1);
Spinner spinner = (Spinner) findViewById(R.id.spinner);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Foods food1 = new Foods("Apple", "80");
Foods food2 = new Foods("Bagel", "200");
Foods food3 = new Foods("Biscuit", "65" );
Foods food4 = new Foods("Banana", "105");
Foods food5 = new Foods("Beef Roast", "205");
Foods food6 = new Foods("Corn", "60");
Foods food7 = new Foods("Cereal", "120");
Foods food8 = new Foods("Chicken", "240");
Foods food9 = new Foods("Eggs", "105");
Foods food10 = new Foods("Cabbage", "30");
Foods food11 = new Foods("Oatmeal", "160");
Foods food12 = new Foods("Pancake", "60");
Foods food13 = new Foods("Pears", "100");
Foods food14 = new Foods("Pizza", "290");
Foods food15 = new Foods("Ice Cream", "270");
Foods food16 = new Foods("Pork Chop", "335");
Foods food17 = new Foods("Ham", "250");
Foods food18 = new Foods("Ribs", "270");
Foods food19 = new Foods("Popcorn", "55");
Foods food20 = new Foods("Baked Potato", "220");
Foods food21 = new Foods("Rice", "225");
Foods food22 = new Foods("Salad", "85");
Foods food23 = new Foods("Spaghetti", "360");
Foods food24 = new Foods("Bread", "65");
Foods food25 = new Foods("Fish", "175");
dbHandler.addFood(food1);
dbHandler.addFood(food2);
dbHandler.addFood(food3);
dbHandler.addFood(food4);
dbHandler.addFood(food5);
dbHandler.addFood(food6);
dbHandler.addFood(food7);
dbHandler.addFood(food8);
dbHandler.addFood(food9);
dbHandler.addFood(food10);
dbHandler.addFood(food11);
dbHandler.addFood(food12);
dbHandler.addFood(food13);
dbHandler.addFood(food14);
dbHandler.addFood(food15);
dbHandler.addFood(food16);
dbHandler.addFood(food17);
dbHandler.addFood(food18);
dbHandler.addFood(food19);
dbHandler.addFood(food20);
dbHandler.addFood(food21);
dbHandler.addFood(food22);
dbHandler.addFood(food23);
dbHandler.addFood(food24);
dbHandler.addFood(food25);
spinner.setOnItemSelectedListener(this);
loadSpinnerData();
}
private void loadSpinnerData()
{
List<String> foodnames = dbHandler.getFoodNames();
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, foodnames);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String food = parent.getItemAtPosition(position).toString();
// Showing selected spinner item
Toast.makeText(parent.getContext(), "You selected: " + food,
Toast.LENGTH_LONG).show();
}
}
public class Foods {
private int _id;
public int get_id() {
return _id;
}
public void set_id(int _id) {
this._id = _id;
}
private String name;
private String calories;
public Foods(){
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCalories() {
return calories;
}
public void setCalories(String calories) {
this.calories = calories;
}
public Foods(String foodname, String foodcalories){
this.name = foodname;
this.calories = foodcalories;
}
}
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.Cursor;
import android.content.Context;
import android.content.ContentValues;
import java.util.ArrayList;
import java.util.List;
public class MyDBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "BroncoWellness.db";
public static final String TABLE_FOODS = "food";
public static final String COLUMN_FOOD_ID = "_id";
public static final String COLUMN_FOOD_NAME = "foodname";
public static final String COLUMN_FOOD_CALORIES = "foodcalories";
#Override
public void onCreate(SQLiteDatabase db) {
String Foodquery = "CREATE TABLE " + TABLE_FOODS + "(" +
COLUMN_FOOD_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_FOOD_NAME + " TEXT " +
COLUMN_FOOD_CALORIES + " TEXT " +
");";
db.execSQL(Foodquery);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_FOODS);
onCreate(db);
}
public MyDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context,DATABASE_NAME ,factory, DATABASE_VERSION);}
public void addFood(Foods food){
ContentValues values = new ContentValues();
values.put(COLUMN_FOOD_NAME, food.getName());
values.put(COLUMN_FOOD_CALORIES, food.getCalories());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_FOODS,null,values);
db.close();
}
public List<String> getFoodNames(){
List<String> foodnames = new ArrayList<String>();
String selectQuery = "SELECT * FROM " + TABLE_FOODS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
foodnames.add(cursor.getString(1));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return foodnames;
}
}
In your code, you are initializing the spinner outside the onCreate() method. It should be like this-
Spinner spinner;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (Spinner) findViewById(R.id.spinner);
//your code
}
This will solve your issue.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// **Spinner element here**
spinner = (Spinner) findViewById(R.id.spinner);

Categories

Resources