Database delete function not working - android

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.

Related

getContext().getContentResolver().notifyChange(uri, null) didn't notify cursor

i'm trying to undestand Content Provider,but i stuck in one thing,
notification of cursor didn't work,if i update cursor in query method everything works fine.Where i get wrong.Thank you! This is full source code
https://github.com/denmariupol/StartAndroid/tree/master/lesson101_contentprovider_creation_h/src/main
MainActivity
package com.example.lesson101_contentprovider_creation_h;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.database.Cursor;
import android.databinding.DataBindingUtil;
import android.net.Uri;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.example.lesson101_contentprovider_creation_h.databinding.ActivityMainBinding;
import com.example.lesson101_contentprovider_creation_h.interfaces.IUpdateCursor;
import com.example.lesson101_contentprovider_creation_h.fragments.Insert;
import com.facebook.stetho.Stetho;
import java.util.ArrayList;
public class MainActivity extends FragmentActivity implements IUpdateCursor {
public final static Uri PROVIDER_URI = Uri.parse("com.example.lesson101_contentprovider_creation_h");
private Cursor cursor;
private MyAdapter scAdapter;
private ActivityMainBinding mainActivity;
private OnClickListener clickListener;
private int colId;
private int colText;
private ArrayList<Integer> chekedItems = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
stethoInit();
mainActivity = DataBindingUtil.setContentView(this, R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
cursor = getContentResolver().query(MyProvider.CONTENT_URI, null, null, null, null, null);
}
colId = cursor.getColumnIndex(MyProvider.ID);
colText = cursor.getColumnIndex(MyProvider.TEXT);
String[] from = new String[]{MyProvider.ID, MyProvider.TEXT};
int[] to = new int[]{R.id.itemId, R.id.itemText};
scAdapter = new MyAdapter(this, R.layout.item, cursor, from, to, 0);
mainActivity.listItem.setAdapter(scAdapter);
scAdapter.notifyDataSetChanged();
mainActivity.listItem.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final View v = view;
final LinearLayout itemUpdateLayout = (LinearLayout)view.findViewById(R.id.itemUpdateLayout);
final LinearLayout itemViewLayout = (LinearLayout)view.findViewById(R.id.itemViewLayout);
TextView idView = (TextView)view.findViewById(R.id.itemId);
TextView textView = (TextView)view.findViewById(R.id.itemText);
final EditText editText = (EditText)view.findViewById(R.id.updateTextField);
Button updateButton = (Button)view.findViewById(R.id.updateRecButton);
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Log.d("!!!","onTextChanged -> "+s.toString());
// ed
}
#Override
public void afterTextChanged(Editable s) {
}
});
final String updId = idView.getText().toString();
updateButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ContentValues cv = new ContentValues();
String text = editText.getText().toString();
Log.d("!!!","clicked text -> "+editText.getText().toString());
if(text.length() > 0) {
cv.put(MyProvider.TEXT, text);
Uri newUri = ContentUris.withAppendedId(MyProvider.CONTENT_URI,Long.valueOf(updId));
getContentResolver().update(newUri, cv,null,null);
// Cursor cursor = null;
// if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
// cursor = getContentResolver().query(MyProvider.CONTENT_URI,null,null,null,null,null);
// }
// updateCursor(cursor);
}
itemUpdateLayout.setVisibility(View.GONE);
itemViewLayout.setVisibility(View.VISIBLE);
}
});
editText.setText(textView.getText());
itemUpdateLayout.setVisibility(View.VISIBLE);
itemViewLayout.setVisibility(View.INVISIBLE);
}
});
mainActivity.insert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment insertFragment = new Insert();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.container, insertFragment);
ft.addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
});
mainActivity.delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(chekedItems.size() > 0){
for (int i = 0; i < chekedItems.size(); i++) {
Uri newUri = ContentUris.withAppendedId(MyProvider.CONTENT_URI,chekedItems.get(i));
getContentResolver().delete(newUri,null,null);
// Cursor cursor = null;
// if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
// cursor = getContentResolver().query(MyProvider.CONTENT_URI,null,null,null,null,null);
// }
// updateCursor(cursor);
}
chekedItems.clear();
}else{
Toast.makeText(MainActivity.this,"Nothing selected",Toast.LENGTH_SHORT).show();
}
}
});
}
private void stethoInit() {
// Create an InitializerBuilder
Stetho.InitializerBuilder initializerBuilder =
Stetho.newInitializerBuilder(this);
// Enable Chrome DevTools
initializerBuilder.enableWebKitInspector(
Stetho.defaultInspectorModulesProvider(this)
);
// Enable command line interface
initializerBuilder.enableDumpapp(
Stetho.defaultDumperPluginsProvider(this)
);
// Use the InitializerBuilder to generate an Initializer
Stetho.Initializer initializer = initializerBuilder.build();
// Initialize Stetho with the Initializer
Stetho.initialize(initializer);
}
#Override
public void updateCursor(Cursor newCusor) {
scAdapter.changeCursor(newCusor);
scAdapter.notifyDataSetChanged();
//hide keyboard
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
private class MyAdapter extends SimpleCursorAdapter{
private int layout;
public MyAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags) {
super(context, layout, c, from, to, flags);
this.layout = layout;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
final String id = cursor.getString(colId);
String title = cursor.getString(colText);
TextView idView = (TextView)view.findViewById(R.id.itemId);
idView.setText(id);
TextView textView = (TextView)view.findViewById(R.id.itemText);
textView.setText(title);
CheckBox checkBox = (CheckBox)view.findViewById(R.id.itemCheckBox);
checkBox.setChecked(false);
checkBox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(!chekedItems.contains(Integer.valueOf(id))){
chekedItems.add(Integer.valueOf(id));
}else{
chekedItems.remove(chekedItems.indexOf(Integer.valueOf(id)));
}
}
});
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = getLayoutInflater().inflate(layout,parent,false);
return view;
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getViewTypeCount() {
return getCount();
}
}
}
Insert Fragment
package com.example.lesson101_contentprovider_creation_h.fragments;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.lesson101_contentprovider_creation_h.MainActivity;
import com.example.lesson101_contentprovider_creation_h.MyProvider;
import com.example.lesson101_contentprovider_creation_h.R;
import com.example.lesson101_contentprovider_creation_h.databinding.FragmentInsertBinding;
import com.example.lesson101_contentprovider_creation_h.interfaces.IUpdateCursor;
/**
* A simple {#link Fragment} subclass.
*/
public class Insert extends Fragment{
Activity activity;
public Insert() {
// Required empty public constructor
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.activity = (Activity)context;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final FragmentInsertBinding insertBinding = DataBindingUtil.inflate(inflater,R.layout.fragment_insert,container,false);
View v = insertBinding.getRoot();
insertBinding.insertRecButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ContentValues cv = new ContentValues();
String text = insertBinding.insertTextField.getText().toString();
if(text.length() > 0) {
cv.put(MyProvider.TEXT, text);
getContext().getContentResolver().insert(MyProvider.CONTENT_URI, cv);
getActivity().getSupportFragmentManager().beginTransaction().remove(Insert.this).commit();
insertBinding.insertTextField.clearFocus();
// Cursor cursor = null;
// if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
// cursor = getContext().getContentResolver().query(MyProvider.CONTENT_URI,null,null,null,null,null);
// }
// ((IUpdateCursor)activity).updateCursor(cursor);
}
}
});
// Inflate the layout for this fragment
return v;
}
// public interface IUpdateCursor{
// void updateCursor(Cursor newCursor);
// }
}
MyProvider
package com.example.lesson101_contentprovider_creation_h;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
/**
* Created by den on 2017-03-31.
*/
public class MyProvider extends ContentProvider{
private final String DB_NAME = "my";
private int DB_VERSION = 1;
private static final String AUTHORITY = "com.example.lesson101_contentprovider_creation_h";
private static final String PATH = "table";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + PATH);
public static final String DB_TABLE = "MYTABLE";
public static final String ID = "_id";
public static final String TEXT = "text";
private final String CREATE_DB = "CREATE TABLE " + DB_TABLE + " ("
+ ID + " integer primary key autoincrement, "
+ TEXT + " text);";
private DBHelper dbHelper;
private SQLiteDatabase database;
private static final int TABLE = 1;
private static final int TABLE_ID = 2;
static final String CONTACT_CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd."
+ AUTHORITY + "." + PATH;
private static UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
static {
uriMatcher.addURI(AUTHORITY, PATH, TABLE);
uriMatcher.addURI(AUTHORITY, PATH + "/#", TABLE_ID);
}
#Override
public boolean onCreate() {
dbHelper = new DBHelper(getContext());
return true;
}
#Nullable
#Override
public Cursor query(#NonNull Uri uri, #Nullable String[] projection,
#Nullable String selection, #Nullable String[] selectionArgs, #Nullable String sortOrder) {
database = dbHelper.getWritableDatabase();
switch (uriMatcher.match(uri)){
case TABLE:
sortOrder = ID;
break;
case TABLE_ID:
String id = uri.getLastPathSegment();
sortOrder = TEXT;
break;
}
Cursor cursor = database.query(DB_TABLE,projection,selection,selectionArgs,null,null,sortOrder);
Log.d("!!!","query -> "+uri.toString());
cursor.setNotificationUri(getContext().getContentResolver(),CONTENT_URI);
return cursor;
}
#Nullable
#Override
public String getType(#NonNull Uri uri) {
switch (uriMatcher.match(uri)){
case TABLE:
break;
case TABLE_ID:
return CONTACT_CONTENT_ITEM_TYPE;
}
return null;
}
#Nullable
#Override
public Uri insert(#NonNull Uri uri, #Nullable ContentValues values) {
database = dbHelper.getWritableDatabase();
Log.d("!!!","insert -> "+uri.toString());
if(uriMatcher.match(uri) != TABLE)
throw new IllegalArgumentException("Wrong URI: "+uri);
long id = database.insert(DB_TABLE,null,values);
Uri resultUri = ContentUris.withAppendedId(CONTENT_URI,id);
Log.d("!!!","insert after -> "+resultUri.toString());
getContext().getContentResolver().notifyChange(resultUri,null);
return resultUri;
}
#Override
public int delete(#NonNull Uri uri, #Nullable String selection, #Nullable String[] selectionArgs) {
database = dbHelper.getWritableDatabase();
switch (uriMatcher.match(uri)){
case TABLE:
break;
case TABLE_ID:
String id = uri.getLastPathSegment();
selection = ID + " = " + id;
break;
}
int c = database.delete(DB_TABLE,selection,selectionArgs);
getContext().getContentResolver().notifyChange(uri, null);
return c;
}
#Override
public int update(#NonNull Uri uri, #Nullable ContentValues values, #Nullable String selection, #Nullable String[] selectionArgs) {
database = dbHelper.getWritableDatabase();
switch (uriMatcher.match(uri)){
case TABLE:
break;
case TABLE_ID:
String id = uri.getLastPathSegment();
selection = ID + " = " +id;
Log.d("!!!",id);
break;
}
int c = database.update(DB_TABLE,values,selection,null);
getContext().getContentResolver().notifyChange(uri, null);
return c;
}
private class DBHelper extends SQLiteOpenHelper{
public DBHelper(Context context) {
super(context,DB_NAME,null,DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
updateDB(db,0,DB_VERSION);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
private void updateDB(SQLiteDatabase db, int oldVersion, int newVersion){
if(oldVersion < 1)
db.execSQL(CREATE_DB);
}
}
}
Did you check if the uri used in setNotificationUri is matching the ones used in the getContext().getContentResolver().notifyChange()?
Cursor.setNotificationUri()
will register for the underline uri for the
getContext().getContentResolver().notifyChange(uri, null);
which is called when such as at ContentProvider's insert(), update() and delete() calls, so the Cursor (has setNotificationUri()) will be notified.
If you are using CursorAdapter, by default, CursorAdapter objects will get this notification issued by getContext().getContentResolver().notifyChange.
Another thing to make sure not to do cursor.close(), the close() will cause unregister the content observer which was registered by CursorLoader. And the cursor closing is managed by CursorLoader.

Saving Object in SQLite Database, no exception - 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.

Not getting the number after decimal point in android

I'm a new in android.I tried to take the floating value in edittext and store it on the database. Then i got the total number of those stored value. But i'm not getting the value after the decimal point.
Here is my code...
package com.example.usaukglu.tablayoyt;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Income extends AppCompatActivity implements View.OnClickListener {
TextView amount, payer, note, show;
EditText edi_amount, payer_name, edit_note;
Button save, cancel;
DatabaseHandler db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_income);
save = (Button) findViewById(R.id.save);
cancel = (Button) findViewById(R.id.cancel);
amount = (TextView) findViewById(R.id.amount);
payer = (TextView) findViewById(R.id.payer);
note = (TextView) findViewById(R.id.note);
show = (TextView) findViewById(R.id.show);
edi_amount = (EditText) findViewById(R.id.edit_amount);
payer_name = (EditText) findViewById(R.id.edit_payer);
edit_note = (EditText) findViewById(R.id.edit_note);
//date= (EditText) findViewById(R.id.date);
db = new DatabaseHandler(this);
save.setOnClickListener(this);
cancel.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (view.getId() == R.id.save) {
String amounts,payers,notes;
amounts=edi_amount.getText().toString();
payers= payer_name.getText().toString();
notes= edit_note.getText().toString();
if(amounts.isEmpty())
{
edi_amount.setError("Amounts should not be blank");
}
else if (payers.isEmpty()){
payer_name.setError("Payer name should not be blank");
}
else {
Double a =new Double(amounts);
DataProvider provider = new DataProvider(""+a, payers, notes);
db.addInformation(provider);
Intent i = new Intent(this, MainActivity.class);
startActivity(i);
}
}
if (view.getId() == R.id.cancel) {
Intent i =new Intent(this,MainActivity.class);
startActivity(i);
}
}
public void show(String data) {
show.setText(data);
}
}
Here is the dataProvider class:
package com.example.usaukglu.tablayoyt;
public class DataProvider {
private String money;
private String name;
private String desc;
public DataProvider(String money, String name, String desc) {
this.money = money;
this.name = name;
this.desc = desc;
}
public String getMoney() {
return money;
}
public void setMoney(String money) {
this.money = money;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
DatabaseHandler Class:
package com.example.usaukglu.tablayoyt;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import static com.example.usaukglu.tablayoyt.R.id.amount;
import static com.example.usaukglu.tablayoyt.R.id.note;
import static com.example.usaukglu.tablayoyt.R.id.payer;
public class DatabaseHandler extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "income.db";
public static final String TABLE_NAME = "income_table";
public static final String ID="id";
public static final String AMOUNT = "amount";
public static final String PAYER_NAME = "payer";
public static final String NOTE = "note";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String query = "CREATE TABLE " + TABLE_NAME +
"(" +ID+ " integer primary key autoincrement, " + AMOUNT + " real, " + PAYER_NAME + " text, " + NOTE + " text " + ")";
sqLiteDatabase.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(sqLiteDatabase);
}
public void addInformation(DataProvider provider){
SQLiteDatabase db = getWritableDatabase();
ContentValues values=new ContentValues();
values.put(AMOUNT,provider.getMoney());
values.put(PAYER_NAME,provider.getName());
values.put(NOTE,provider.getDesc());
db.insert(TABLE_NAME, null, values);
db.close();
}
public Cursor display()
{
SQLiteDatabase sqLiteDatabase=getReadableDatabase();
Cursor res= sqLiteDatabase.rawQuery("SELECT * FROM "+TABLE_NAME,null);
return res;
}
public double getTotalOfAmount() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("SELECT SUM(AMOUNT) FROM " + TABLE_NAME, null);
c.moveToFirst();
double i = c.getInt(0);
c.close();
return i;
}
}
FragmentIncome class whre i want o show the data:
package com.example.usaukglu.tablayoyt;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class FragmentIncome extends Fragment {
ListView list;
private DatabaseHandler handler;
private SQLiteDatabase database;
private List<DataProvider> amountList;
private ListDataAdaptar listDataAdaptar;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view =inflater.inflate(R.layout.fragment_income,container,false);
list=(ListView) view.findViewById(R.id.listView);
amountList=new ArrayList<>();
handler=new DatabaseHandler(getContext());
database=handler.getReadableDatabase();
Cursor cursor=handler.display();
if(cursor.moveToFirst()){
do {
String amount,payer,note;
amount= cursor.getString(cursor.getColumnIndex(handler.AMOUNT));
payer=cursor.getString(cursor.getColumnIndex(handler.PAYER_NAME));
note=cursor.getString(cursor.getColumnIndex(handler.NOTE));
DataProvider provider=new DataProvider(amount,payer,note);
amountList.add(provider);
listDataAdaptar=new ListDataAdaptar(getContext(),R.layout.display_income_row,amountList);
list.setAdapter(listDataAdaptar);
}while (cursor.moveToNext());
}
return view;
}
}
You are using String variables in your database.Use float datatype in your tables to run a SUM query.
Your DataProvider class should be like this-
public class DataProvider {
private Float money;
private String name;
private String desc;
public DataProvider(Float money, String name, String desc) {
this.money = money;
this.name = name;
this.desc = desc;
}
public Float getMoney() {
return money;
}
public void setMoney(Float money) {
this.money = money;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}

(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);

LoadMoreListView Fragment implementation using sqlite database

I need to load a large dataset from a sqlite database. This will take too much of time to load the data. Therefore I used LoadMorelistView library to load with pagination.
I followed below link and successfully load the data from hard coded list.
pull to refresh and loadmore listview like facebook
But when I tried to load from sqlite database I got the following error.
// The constructor ArrayAdapter(Activity, int, ArrayList) is Undefined
I searched the google as well as stackoverflow. But unable to find a solution.
Please find the code snippet which I used to load the data,
Code for the list loading fragment. (FragmentThree.java)
package com.load.more.list.view;
import java.util.ArrayList;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import com.costum.android.widget.LoadMoreListView;
import com.costum.android.widget.LoadMoreListView.OnLoadMoreListener;
import com.load.more.list.model.Customer;
import com.load.more.list.data.CustomerDS;
import com.load.more.list.data.DatabaseHelper;
import android.app.Fragment;
import com.load.more.list.control.CustomerAdapter;
public class FragmentThree extends Fragment {
View view;
LoadMoreListView lyt;
ArrayAdapter<String> files;
ArrayList<Customer> mListItems;
CustomerDS customerDS;
private DatabaseHelper dbHelper;
private int visibleThreshold = 20;
private int currentPage = 0;
private int previousTotal = 0;
private int firstVisibleItem = 0;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_three, container, false);
lyt = (LoadMoreListView) view.findViewById(R.id.lvRouteCustomers);
mListItems = customerDS.getAllCustomersFromTo(visibleThreshold,
firstVisibleItem);
// Following Error Thrown from here
// The constructor ArrayAdapter<String>(Activity, int,
// ArrayList<Customer>) is Undefined
files = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, mListItems);
lyt.setAdapter(files);
lyt.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
// TODO Auto-generated method stub
new LoadMoreDataTask().execute();
}
});
return view;
}
private class LoadMoreDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
if (isCancelled()) {
return null;
}
// Simulates a background task
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
// Following Error Thrown from here
// The constructor ArrayAdapter<String>(Activity, int,
// ArrayList<Customer>) is Undefined
files = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, mListItems);
lyt.setAdapter(files);
return null;
}
#Override
protected void onPostExecute(Void result) {
files.notifyDataSetChanged();
// Call onLoadMoreComplete when the LoadMore task, has finished
lyt.onLoadMoreComplete();
super.onPostExecute(result);
}
#Override
protected void onCancelled() {
// Notify the loading more operation has finished
lyt.onLoadMoreComplete();
}
}
}
Code for the database helper class. (DatabaseHelper)
package com.load.more.list.data;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
//database information
private static final String DATABASE_NAME = "fmcgDB.db";
private static final int DATABASE_VERSION = 1;
//TABLES
//Customer table
public static final String TABLE_CUSTOMER = "customer";
public static final String CUSTOMER_ID = "customer_id";
public static final String CUSTOMER_NO = "customer_no";
public static final String CUSTOMER_NAME = "customer_name";
public static final String CUSTOMER_CONTACT_PERSON = "customer_contact_person";
public static final String CUSTOMER_TELEPHONE_NO = "customer_telephone_no";
public static final String CUSTOMER_ADDRESS = "customer_address";
public static final String CUSTOMER_LONGITUDE = "customer_longitude";
public static final String CUSTOMER_LATITUDE = "customer_latitude";
public static final String CUSTOMER_TLP = "customer_tlp";
public static final String CUSTOMER_REP_ID = "customer_rep_id";
public static final String CUSTOMER_CATEGORY_ID = "cc_id";
public static final String CUSTOMER_OUTLET_TYPE_ID = "ot_id";
public static final String CUSTOMER_PERIPHERY_TYPE_ID = "pt_id";
public static final String CUSTOMER_VOLUME_ID = "volume_id";
public static final String CUSTOMER_MARKET_ID = "market_id";
private static final String CREATE_CUSTOMER_TABLE = "CREATE TABLE " + TABLE_CUSTOMER + " ("
+ CUSTOMER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ CUSTOMER_NO + " TEXT, "
+ CUSTOMER_NAME + " TEXT, "
+ CUSTOMER_CONTACT_PERSON + " TEXT, "
+ CUSTOMER_TELEPHONE_NO + " TEXT, "
+ CUSTOMER_ADDRESS + " TEXT, "
+ CUSTOMER_LONGITUDE + " REAL, "
+ CUSTOMER_LATITUDE + " REAL, "
+ CUSTOMER_TLP + " INTEGER, "
+ CUSTOMER_REP_ID + " INTEGER, "
+ CUSTOMER_CATEGORY_ID + " INTEGER, "
+ CUSTOMER_OUTLET_TYPE_ID + " INTEGER, "
+ CUSTOMER_PERIPHERY_TYPE_ID + " INTEGER, "
+ CUSTOMER_VOLUME_ID + " INTEGER, "
+ CUSTOMER_MARKET_ID + " INTEGER "
+");";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase arg0) { // this order must be followed when creating tables
arg0.execSQL(CREATE_CUSTOMER_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
arg0.execSQL("DROP TABLE IF EXISTS " + CREATE_CUSTOMER_TABLE);
onCreate(arg0);
}
}
Code for the sqlite data loading. (CustomerDS.java)
package com.load.more.list.data;
import java.util.ArrayList;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import com.load.more.list.model.Customer;
public class CustomerDS {
private SQLiteDatabase fmcgDB;
private DatabaseHelper dbHelper;
Context context;
public CustomerDS(Context context) {
this.context = context;
dbHelper = new DatabaseHelper(context);
}
public void open() throws SQLException {
fmcgDB = dbHelper.getWritableDatabase();
}
public ArrayList<Customer> getAllCustomersFromTo(int limit, int offset) {
if (fmcgDB == null) {
open();
} else if (!fmcgDB.isOpen()) {
open();
}
ArrayList<Customer> customersList = new ArrayList<Customer>();
// Newly Added
String selectQuery = "SELECT * FROM " + dbHelper.TABLE_CUSTOMER
+ " LIMIT " + limit + " OFFSET " + offset +"";
Cursor cursor = null;
try{
cursor = fmcgDB.rawQuery(selectQuery, null);
/*cursor = fmcgDB.query(dbHelper.TABLE_CUSTOMER, null, null, null,
null, null, null);
*/
while (cursor.moveToNext()) {
Customer customer = new Customer();
customer.setCustomer_id(cursor.getInt(cursor.getColumnIndex(dbHelper.CUSTOMER_ID)));
customer.setCustomer_no(cursor.getString((cursor.getColumnIndex(dbHelper.CUSTOMER_NO))));
customer.setCustomer_name(cursor.getString((cursor.getColumnIndex(dbHelper.CUSTOMER_NAME))));
customer.setCustomer_contact_person(cursor.getString((cursor.getColumnIndex(dbHelper.CUSTOMER_CONTACT_PERSON))));
customer.setCustomer_telephone_no(cursor.getString((cursor.getColumnIndex(dbHelper.CUSTOMER_TELEPHONE_NO))));
customer.setCustomer_address(cursor.getString((cursor.getColumnIndex(dbHelper.CUSTOMER_ADDRESS))));
customer.setCustomer_longitude(cursor.getDouble((cursor.getColumnIndex(dbHelper.CUSTOMER_LONGITUDE))));
customer.setCustomer_latitude(cursor.getDouble((cursor.getColumnIndex(dbHelper.CUSTOMER_LATITUDE))));
int TLP = cursor.getInt((cursor.getColumnIndex(dbHelper.CUSTOMER_TLP)));
if(TLP == 0){
customer.setCustomer_TLP_member(true);
}else{
customer.setCustomer_TLP_member(false);
}
customersList.add(customer);
}
}
finally {
if (cursor!=null) {
cursor.close();
}
fmcgDB.close();
return customersList;
}
}
}
Code for the Adapter Class. (CustomerAdapter.java)
package com.load.more.list.control;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.load.more.list.model.Customer;
import com.load.more.list.view.R;
public class CustomerAdapter extends ArrayAdapter<Customer> {
Context context;
ArrayList<Customer> customerList;
public CustomerAdapter(Context context, ArrayList<Customer> customerList){
super(context, R.layout.item_customer, customerList);
this.context = context;
this.customerList = customerList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.item_customer, parent, false);
TextView tvName = (TextView) row.findViewById(R.id.tvRouteCustomerListName);
TextView tvMarket = (TextView) row.findViewById(R.id.tvRouteCustomerListMarket);
TextView tvVolume = (TextView) row.findViewById(R.id.tvRouteCustomerListVolume);
tvName.setText(customerList.get(position).getCustomer_name());
return row;
}
}
Code for the Customer Object. (Customer.java)
package com.load.more.list.model;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.util.Log;
public class Customer {
private static final String TAG_CUSTOMER = "customers";
private static final String TAG_CUSTOMER_ID = "customer_id";
private static final String TAG_CUSTOMER_NO = "CustomerCode";
private static final String TAG_CUSTOMER_NAME = "CustomerName";
private static final String TAG_CUSTOMER_ADDRESS = "Address1";
private static final String TAG_CUSTOMER_CONTACT_PERSON = "ContactPersonName";
private static final String TAG_CUSTOMER_TELEPHONE_NO = "PhoneNo";
private static final String TAG_CUSTOMER_LATITUDE = "CustomerLatitude";
private static final String TAG_CUSTOMER_LONGITUDE = "CustomerLongitude";
private static final String TAG_CUSTOMER_IS_TLP = "Istlp";
private static final String TAG_CUSTOMER_REP_ID = "";
private static final String TAG_CUSTOMER_PT_ID = "PheriheryId";
private static final String TAG_CUSTOMER_CATEGORY_ID = "CatrgoryId";
private static final String TAG_CUSTOMER_OUTLETTYPE_ID = "OutletTypeId";
private static final String TAG_CUSTOMER_VOLUME_ID = "VolumeId";
private static final String TAG_CUSTOMER_MARKET_ID = "MarketId";
private int customer_id;
private String customer_no;
private String customer_name;
private String customer_contact_person;
private String customer_telephone_no;
private String customer_address;
private double customer_longitude;
private double customer_latitude;
private boolean customer_TLP_member;
public int getCustomer_id() {
return customer_id;
}
public void setCustomer_id(int customer_id) {
this.customer_id = customer_id;
}
public String getCustomer_name() {
return customer_name;
}
public void setCustomer_name(String customer_name) {
this.customer_name = customer_name;
}
public String getCustomer_contact_person() {
return customer_contact_person;
}
public void setCustomer_contact_person(String customer_contact_person) {
this.customer_contact_person = customer_contact_person;
}
public String getCustomer_telephone_no() {
return customer_telephone_no;
}
public void setCustomer_telephone_no(String customer_telephone_no) {
this.customer_telephone_no = customer_telephone_no;
}
public String getCustomer_address() {
return customer_address;
}
public void setCustomer_address(String customer_address) {
this.customer_address = customer_address;
}
public double getCustomer_longitude() {
return customer_longitude;
}
public void setCustomer_longitude(double customer_longitude) {
this.customer_longitude = customer_longitude;
}
public double getCustomer_latitude() {
return customer_latitude;
}
public void setCustomer_latitude(double customer_latitude) {
this.customer_latitude = customer_latitude;
}
public boolean isCustomer_TLP_member() {
return customer_TLP_member;
}
public void setCustomer_TLP_member(boolean customer_TLP_member) {
this.customer_TLP_member = customer_TLP_member;
}
public String getCustomer_no() {
return customer_no;
}
public void setCustomer_no(String customer_no) {
this.customer_no = customer_no;
}
}
Can anyone know how to solve this problem? If yes, please help me to solve this problem.
Thanks in advance.
Finally I solved the issue,.
I have changed the type of mListItems to
ArrayList<String> mListItems;
and the return type of getAllCustomersFromTo() to String array.
It solved my issue.
Final source code of the updated classes are shown below.
Code for the list loading fragment. (FragmentThree.java)
package com.load.more.list.view;
import java.util.ArrayList;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import com.costum.android.widget.LoadMoreListView;
import com.costum.android.widget.LoadMoreListView.OnLoadMoreListener;
import com.load.more.list.model.Customer;
import com.load.more.list.data.CustomerDS;
import com.load.more.list.data.DatabaseHelper;
import android.app.Fragment;
import com.load.more.list.control.CustomerAdapter;
public class FragmentThree extends Fragment {
View view;
LoadMoreListView lyt;
ArrayAdapter<String> files;
ArrayList<String> mListItems;
CustomerDS customerDS;
private DatabaseHelper dbHelper;
private int visibleThreshold = 20;
private int currentPage = 0;
private int previousTotal = 0;
private int firstVisibleItem = 0;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_three, container, false);
lyt = (LoadMoreListView) view.findViewById(R.id.lvRouteCustomers);
mListItems = customerDS.getAllCustomersFromTo(visibleThreshold,
firstVisibleItem);
files = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, mListItems);
lyt.setAdapter(files);
lyt.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
// TODO Auto-generated method stub
new LoadMoreDataTask().execute();
}
});
return view;
}
private class LoadMoreDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
if (isCancelled()) {
return null;
}
// Simulates a background task
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
files = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, mListItems);
lyt.setAdapter(files);
return null;
}
#Override
protected void onPostExecute(Void result) {
files.notifyDataSetChanged();
// Call onLoadMoreComplete when the LoadMore task, has finished
lyt.onLoadMoreComplete();
super.onPostExecute(result);
}
#Override
protected void onCancelled() {
// Notify the loading more operation has finished
lyt.onLoadMoreComplete();
}
}
}
Code for the sqlite data loading. (CustomerDS.java)
package com.load.more.list.data;
import java.util.ArrayList;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import com.load.more.list.model.Customer;
public class CustomerDS {
private SQLiteDatabase fmcgDB;
private DatabaseHelper dbHelper;
Context context;
public CustomerDS(Context context) {
this.context = context;
dbHelper = new DatabaseHelper(context);
}
public void open() throws SQLException {
fmcgDB = dbHelper.getWritableDatabase();
}
public ArrayList<String> getAllCustomersFromTo(int limit, int offset) {
if (fmcgDB == null) {
open();
} else if (!fmcgDB.isOpen()) {
open();
}
ArrayList<String> customersList = new ArrayList<String>();
String selectQuery = "SELECT * FROM " + dbHelper.TABLE_CUSTOMER
+ " LIMIT " + limit + " OFFSET " + offset +"";
Cursor cursor = null;
try{
cursor = fmcgDB.rawQuery(selectQuery, null);
while (cursor.moveToNext()) {
customersList.add(cursor.getString((cursor.getColumnIndex(dbHelper.CUSTOMER_NAME))));
}
}
finally {
if (cursor!=null) {
cursor.close();
}
fmcgDB.close();
return customersList;
}
}
}

Categories

Resources