Cursor not working as expected - android

I'm trying to pass objects from a SQLite database to a fragment, but they're getting nulled somewhere along the way.
The Log.i line in DatabaseHelper outputs as expected, but the Log.i line in CollectionsFragment does not -- it returns the correct number of values, but all of them are null.
I feel like logging collectionsList in DatabaseHelper would be useful, but I'm not sure how to do that with an ArrayList.
Snippet from DatabaseHelper:
public List<Book> getAllCollections(int authorID) {
List<Book> collectionsList = new ArrayList<>();
// Select all query
String selectQuery = "SELECT DISTINCT collection FROM " + BOOKS + " WHERE author_id = '" + authorID + "'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Book book = new Book();
book.setCollection(cursor.getString(0));
Log.i("stories", cursor.getString(0)); // returns with correct values
collectionsList.add(book);
} while (cursor.moveToNext());
}
return collectionsList;
// not sure how to log collectionsList here
}
Snippet from CollectionsFragment:
// link ListView object with XML ListView
collectionsListView = (ListView) view.findViewById(R.id.collections_list_view);
// create new instance of DatabaseHelper
DatabaseHelper db = new DatabaseHelper(getActivity());
// return view;
// create list of collections through getAllCollections method
List<Book> collectionsList = db.getAllCollections(authorID);
Log.i("testing", collectionsList.toString()); // returns [null, null]
// create new ArrayAdapter
ArrayAdapter<Book> arrayAdapter =
new ArrayAdapter<Book>(getActivity(), android.R.layout.simple_list_item_1, collectionsList);
// link ListView and ArrayAdapter
collectionsListView.setAdapter(arrayAdapter);
Book Class:
public class Book {
int id;
String title;
int author_id;
String collection;
String body;
#Override
public String toString() {
return title;
}
public Book() {
}
public Book(int id, String title, int author_id, String collection, String body) {
this.id = id;
this.title = title;
this.author_id = author_id;
this.collection = collection;
this.body = body;
}
// getters
public int getStoryID() {
return this.id;
}
public String getTitle() {
return this.title;
}
public int getAuthorID() {
return this.author_id;
}
public String getCollection() {
return this.collection;
}
public String getBody() {
return this.body;
}
// setters
public void setStoryID(int id) {
this.id = id;
}
public void setTitle(String title) {
this.title = title;
}
public void setAuthorID(int author_id) {
this.author_id = author_id;
}
public void setCollection(String collection) {
this.collection = collection;
}
public void setBody(String body) {
this.body = body;
}
}

Related

What to use to store the rows after reading from table in android

What is the best way to save data read from SQLiteDatabase Android, and access them using row number or column name?
Hi Below is my code that I am using to fetch the data but I want to store the rows in some kind of dataset so that i can fetch the data using column number or name . I want to dynamically show these data in a grid in android.
MyDatabaseSQLHelper myDatabaseSQLHelper = new MyDatabaseSQLHelper(this);
SQLiteDatabase mySQLiteDatabase = myDatabaseSQLHelper.getReadableDatabase();
String[] projection = {
Items._ID,
Items.COL_ITEM_NAME,
Items.COL_ITEM_PRICE,
Items.COL_ITEM_QUANTITY,
Items.COL_ITEM_AMOUNT
};
Cursor cursor = mySQLiteDatabase.query(Items.TABLE_NAME,projection,null,null,null,null,null);
To store all rows fetch from database you can store it in Array list of type modal class. for you your modal class could be like this
ItemBeen.java
public class ItemBeen {
String id,itemName,itemPrice,itemQty,itemAmount;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getItemPrice() {
return itemPrice;
}
public void setItemPrice(String itemPrice) {
this.itemPrice = itemPrice;
}
public String getItemQty() {
return itemQty;
}
public void setItemQty(String itemQty) {
this.itemQty = itemQty;
}
public String getItemAmount() {
return itemAmount;
}
public void setItemAmount(String itemAmount) {
this.itemAmount = itemAmount;
}
}
then now in your class make method for get data from database and it store all record to array list and return that array list , like this.
public ArrayList<ItemBeen> getItemList() {
Cursor cur;
ArrayList<itemBeen> itemList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
cur = db.query(Items.TABLE_NAME.TBL_ITEM, projection, null, null, null, null, null);
if (cur != null) {
if (cur.moveToFirst()) {
do {
ItemBeen bean = new ItemBeen();
bean.setId(cur.getString(cur.getColumnIndex(DBConstant.TBL_ITEM.KEY_ID)));
bean.setItemName(cur.getString(cur.getColumnIndex(DBConstant.TBL_ITEM.KEY_ITEM_NAME)));
bean.setItemPrice(cur.getBlob(cur.getColumnIndex(DBConstant.TBL_ITEM.KEY_ITEM_PRICE)));
bean.setItemQty(cur.getString(cur.getColumnIndex(DBConstant.TBL_ITEM.KEY_ITEM_TQY)));
bean.setItemAmount(cur.getInt(cur.getColumnIndex(DBConstant.TBL_ITEM.KEY_ITEM_AMT)));
itemList.add(bean);
} while (cur.moveToNext());
}
}
return itemList;
}
Now in that class in which you want all item list in that class call this method.declare array list and fetch data.
ArrayList<ItemBeen> itemList = new ArrayList<ItemBeen>();
itemList = DBConstant.dbHelper.getItemList();
and this way in itemList contains all records.

Android how to get clicked itemid from Listview and update another column value on this row

I am making small app. It has 2 listview on MainActivity.
DB is SQLLite and has tree cloumns id(int), person(text), status(text).
Firt listview will be show informations from DB with this query
select * from DB where status=B
And next ListView will show information where status=A.
lv1.status=b | lv2.status=a
Person 1 | Person 2
Person 3 | Person 4
When i click lv2 on item, value of clicked lv2 field 'status' must change to 'b'.
But I can not write right query for db.
public void changeUser(){
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_STATUS, "B");
db.update(TABLE_ORDER, values, null, null);
db.close();
}
Thanks
Here is my code
lvB = (ListView)findViewById(R.id.lvB);
listClientB();
lvA = (ListView)findViewById(R.id.lvA);
listClientA();
lvA.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
User user = (User)adapterView.getAdapter().getItem(i);
int id = user.get_id();
if (user.getStatus().contains("A")){
dbHelper.changeUser();
}
Toast.makeText(getApplicationContext(), id + "-NUMBER id", Toast.LENGTH_LONG).show();
Log.d(String.valueOf(user.get_id()), "-NUMBER id");
listClientA();
Log.d(user.getStatus(), "Pressed");
}
});
}
private void listClientA(){
list = dbHelper.allUsersA();
klientStatusAdapter = new KlientStatusAdapter(MainActivity.this, list);
lvA.setAdapter(klientStatusAdapter);
lvA.setTextFilterEnabled(true);
}
private void listClientB(){
list = dbHelper.allUsersB();
klientStatusAdapter = new KlientStatusAdapter(MainActivity.this, list);
lvB.setAdapter(klientStatusAdapter);
lvB.setTextFilterEnabled(true);
}
Here is from DB
public List<User> allUsersA(){
db = this.getReadableDatabase();
List<User> users = new ArrayList<User>();
String s = "select * from " + TABLE_ORDER + " where status = 'A'";
Cursor cursor = db.rawQuery(s, null);
if (cursor.moveToFirst()){
do {
User user = new User();
user.set_id(Integer.parseInt(cursor.getString(0)));
user.setClientName(cursor.getString(1));
user.setCleintOrderedFood(cursor.getString(2));
user.setStatus(cursor.getString(3));
users.add(user);
}while (cursor.moveToNext());
}
db.close();
return users;
}
public List<User> allUsersB(){
db = this.getReadableDatabase();
List<User> users = new ArrayList<User>();
String s = "select * from " + TABLE_ORDER + " where status = 'B'";
Cursor cursor = db.rawQuery(s, null);
if (cursor.moveToFirst()){
do {
User user = new User();
user.set_id(Integer.parseInt(cursor.getString(0)));
user.setClientName(cursor.getString(1));
user.setCleintOrderedFood(cursor.getString(2));
user.setStatus(cursor.getString(3));
users.add(user);
}while (cursor.moveToNext());
}
db.close();
return users;
}
public void changeUser(){
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_STATUS, "B");
db.update(TABLE_ORDER, values, null, null);
db.close();
}
Here is adapter
public class ClientStatusAdapter extends BaseAdapter{
LayoutInflater inflater;
Context context;
List<User> wordsList;
DbHelper dbHelper;
public ClientStatusAdapter(Context context1, List<User> wordsList) {
this.context = context1;
this.wordsList = wordsList;
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
dbHelper = new DbHelper(context);
}
#Override
public int getCount() {
return wordsList.size();
}
#Override
public Object getItem(int i) {
return wordsList.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (view == null){
view = inflater.inflate(R.layout.kliyent_status_adapter, null);
}
TextView txtIsmAdapter = (TextView)view.findViewById(R.id.txtIsmAdapter);
TextView txtOvqatAdapter = (TextView)view.findViewById(R.id.txtOvqatAdapter);
final User user = wordsList.get(i);
TextView txtCliyentNames = (TextView)view.findViewById(R.id.txtCliyentNames);
txtCliyentNames.setText(user.getClientName());
TextView txtCliyentOrderedFoood = (TextView)view.findViewById(R.id.txtCliyentOrderedFoood);
txtCliyentOrderedFoood.setText(user.getCleintOrderedFood());
TextView txtStatusAdapter = (TextView)view.findViewById(R.id.txtStatusAdapter);
txtStatusAdapter.setText(user.getStatus());
notifyDataSetChanged();
ImageView imgOn = (ImageView) view.findViewById(R.id.imgOn);
return view;
}
}
Here is entity User
public class User {
private int _id;
private String clientName;
private String cleintOrderedFood;
private String status = "A";
public User() {
}
public User(int _id, String clientName, String cleintOrderedFood) {
this._id = _id;
this.clientName = clientName;
this.cleintOrderedFood = cleintOrderedFood;
}
public User(int _id, String clientName, String cleintOrderedFood, String status) {
this._id = _id;
this.clientName = clientName;
this.cleintOrderedFood = cleintOrderedFood;
this.status = status;
}
public int get_id() {
return _id;
}
public void set_id(int _id) {
this._id = _id;
}
public String getClientName() {
return clientName;
}
public void setClientName(String clientName) {
this.clientName = clientName;
}
public String getCleintOrderedFood() {
return cleintOrderedFood;
}
public void setCleintOrderedFood(String cleintOrderedFood) {
this.cleintOrderedFood = cleintOrderedFood;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
If you look closely at the SQLiteDatabase.update() method, you will see it is declared as
int update (String table,
ContentValues values,
String whereClause,
String[] whereArgs)
Note the last two parameters. These are how you select which rows to update. For example, you can specify to only update rows with a given id:
public void changeUser(int userId){
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_STATUS, "B");
String whereClause = "_id = ?";
String where = new String[] {Integer.toString(userId)};
db.update(TABLE_ORDER, values, whereClause, where);
db.close();
}
Here I am assuming you use the conventional column name _id. Of course, you can change this to suit your needs if you have a different column name.
Note that you will now need to pass a parameter to changeUser(). However, you have not shown how nor where you currently call it, so I am unable to provide any advice how to change this.

Recyclerview not refreshing

I am working on a project where user adds data at runtime.The problem is whenever user inserts the fist element it is adding to the database and displaying in recyclerview.But when user adds more data the recyclerview keeps displaying firstelement over and over again.
If the user adds Apple it is adding to database and recyclerview is displaying Apple.Now if the user adds orange it is adding to database but the recyclerview is displaying Apple two times.
I am using Cursorloader to load data,Contentprovider to add data,and CustomCursoradapter(https://gist.github.com/skyfishjy/443b7448f59be978bc59) to set the data to recyclerview
addDetails() method execute when user adds data
public class AddLog extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor>{
TextView TotalAmount,Date;
EditText name,mobile,city,detailname,detailamount;
RecyclerView adddetailtolist;
DetailsAdapter adapter;
Intent returnback;
double totamount;
long logid;
String Debt = "Debt";
String Paid = "Paid";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_log);
Toolbar toolbar = (Toolbar)findViewById(R.id.addlogtoolbar);
setSupportActionBar(toolbar);
toolbar.setTitle("Add Log");
returnback = new Intent(this,MainActivity.class);
Intent intent = getIntent();
logid = intent.getExtras().getLong("ID");
TotalAmount = (TextView)findViewById(R.id.totalAmount);
Date = (TextView)findViewById(R.id.addlogDate);
name = (EditText)findViewById(R.id.AddName);
mobile = (EditText)findViewById(R.id.AddPhone);
city = (EditText)findViewById(R.id.Addcity);
detailname = (EditText)findViewById(R.id.Detailname);
detailamount = (EditText)findViewById(R.id.Detailamount);
adddetailtolist = (RecyclerView)findViewById(R.id.addloglist);
Date.setText(getDate());
getSupportLoaderManager().initLoader(1,null,this);
adapter = new DetailsAdapter(this,null);
adddetailtolist.setAdapter(adapter);
adddetailtolist.setLayoutManager(new LinearLayoutManager(this));
}
private String getDate()
{
Calendar calendar = Calendar.getInstance();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE,dd-MMM-yyyy");
String date = simpleDateFormat.format(calendar.getTime());
return date;
}
public void addDetails(View view)
{
String Name = detailname.getText().toString();
String Amount = detailamount.getText().toString();
String date = Date.getText().toString();
ContentValues contentValues = new ContentValues();
contentValues.put(DataProvider.Dname,Name);
contentValues.put(DataProvider.DCategory,Debt);
contentValues.put(DataProvider.Damount,Amount);
contentValues.put(DataProvider.Ddate,date);
contentValues.put(DataProvider.Per_In,logid);
Uri uri = getContentResolver().insert(DataProvider.ContentUri_Details,contentValues);
Toast.makeText(AddLog.this, uri.toString()+"Value Inserted", Toast.LENGTH_SHORT).show();
NumberFormat currency = changeamount();
TotalAmount.setText(currency.format(getAmount()));
}
private double getAmount()
{
ContentProviderClient client = getContentResolver().acquireContentProviderClient(DataProvider.ContentUri_Details);
SQLiteDatabase db = ((DataProvider)client.getLocalContentProvider()).sqLiteDatabase;
String query = "SELECT SUM(DAmount) FROM Details WHERE Per_In = "+logid;
Cursor cursor = db.rawQuery(query, null);
cursor.moveToFirst();
double amount = cursor.getDouble(0);
cursor.close();
client.release();
return amount;
}
public NumberFormat changeamount()
{
Locale locale = new Locale("en","IN");
NumberFormat currencyformat = NumberFormat.getCurrencyInstance(locale);
return currencyformat;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuinflate = getMenuInflater();
menuinflate.inflate(R.menu.addlogmenu,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.done:
saveData();
}
return super.onOptionsItemSelected(item);
}
private void saveData()
{
String name1 = name.getText().toString();
String phone = mobile.getText().toString();
String address = city.getText().toString();
if (TextUtils.isEmpty(name1)||TextUtils.isEmpty(phone)||TextUtils.isEmpty(address))
{
if (TextUtils.isEmpty(name1))
{
name.setError("Feild can not be Empty");
}
else if (TextUtils.isEmpty(phone))
{
mobile.setError("Feild can not be Empty");
}
else if (TextUtils.isEmpty(address))
{
city.setError("Feild can not be Empty");
}
}
else
{
ContentValues values = new ContentValues();
values.put(DataProvider.Pname,name1);
values.put(DataProvider.Pphone,phone);
values.put(DataProvider.Paddress,address);
values.put(DataProvider.PCategory,"Debt");
values.put(DataProvider.Pamount,totamount);
String where = DataProvider.PID+"=?";
String[] whereargs = {String.valueOf(logid)};
int a = getContentResolver().update(DataProvider.ContentUri_Person,values,where,whereargs);
Toast.makeText(AddLog.this, String.valueOf(1)+"Value updated", Toast.LENGTH_SHORT).show();
startActivity(returnback);
finish();
}
}
#Override
public Loader<Cursor> onCreateLoader(final int id, Bundle args)
{
String[] Projection = new String[]{DataProvider.DID,DataProvider.Dname,DataProvider.DCategory,DataProvider.Damount,DataProvider.Ddate};
String selection = DataProvider.Per_In+"=?";
String[] selectionargs = new String[]{String.valueOf(logid)};
return new CursorLoader(this,DataProvider.ContentUri_Details,Projection,selection,selectionargs,null);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data)
{
adapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader)
{
adapter.swapCursor(null);
}
}
Content Provider class:
public class DataProvider extends ContentProvider
{
static final String ProviderName = "com.example.mrudu.accounts.provider";
static final String URLPerson = "content://"+ProviderName+"/Person_Detail";
static final String URLDetails = "content://"+ProviderName+"/Details";
static final Uri ContentUri_Person = Uri.parse(URLPerson);
static final Uri ContentUri_Details = Uri.parse(URLDetails);
//Tables
private static String PTableName = "Person_Detail";
private static String DTableName = "Details";
public static long insertId = 0;
//Person_Detail Coloumns
public static String PID = "_id";
public static String Pname = "PName";
public static String Pphone = "PMobile";
public static String Paddress = "PCity";
public static String PCategory = "PCategory";
public static String Pamount = "PAmount";
//Details coloumn
public static String DID = "_id";
public static String Dname = "DName";
public static String Damount = "DAmount";
public static String Ddate = "DDate";
public static String DCategory = "DCategory";
public static String Per_In = "Per_In";
private static final int Person = 1;
private static final int Person_ID = 2;
private static final int Details = 3;
private static final int Details_Id = 4;
static UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
static
{
uriMatcher.addURI(ProviderName,PTableName,Person);
uriMatcher.addURI(ProviderName,PTableName+"/#",Person_ID);
uriMatcher.addURI(ProviderName,DTableName,Details);
uriMatcher.addURI(ProviderName,DTableName+"/#",Details_Id);
}
public static SQLiteDatabase sqLiteDatabase;
private static String Databasename = "Accounts";
private static int DatabaseVersion = 1;
private class DatabaseHelper extends SQLiteOpenHelper
{
public DatabaseHelper(Context context)
{
super(context, Databasename, null, DatabaseVersion);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase)
{
String Create_Person = " Create Table "+PTableName+"("+PID+" INTEGER PRIMARYKEY ,"+Pname+" TEXT ,"+Pphone+" TEXT ,"+Paddress+" TEXT ,"+PCategory+" TEXT ,"+Pamount+" REAL"+")";
String Create_Details = " Create Table "+DTableName+"("+DID+" INTEGER PRIMARYKEY ,"+Dname+" TEXT ,"+DCategory+" TEXT ,"+Damount+" REAl ,"+Ddate+" TEXT ,"+Per_In+" INTEGER )";
sqLiteDatabase.execSQL(Create_Person);
sqLiteDatabase.execSQL(Create_Details);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1)
{
sqLiteDatabase.execSQL("Drop TABLE if exists"+PTableName);
sqLiteDatabase.execSQL("Drop TABLE if exists"+DTableName);
onCreate(sqLiteDatabase);
}
}
#Override
public boolean onCreate()
{
Context context = getContext();
DatabaseHelper databaseHelper = new DatabaseHelper(context);
sqLiteDatabase = databaseHelper.getWritableDatabase();
return (sqLiteDatabase==null)?false:true;
}
#Override
public Uri insert(Uri uri, ContentValues values)
{
switch (uriMatcher.match(uri))
{
case Person:
long rowId = sqLiteDatabase.insert(PTableName,null,values);
insertId = rowId;
if (rowId>0)
{
Uri _uri = ContentUris.withAppendedId(ContentUri_Person,rowId);
getContext().getContentResolver().notifyChange(_uri,null);
return _uri;
}
break;
case Details:
long rowId1 = sqLiteDatabase.insert(DTableName,null,values);
if (rowId1>0)
{
Uri _uri = ContentUris.withAppendedId(ContentUri_Details,rowId1);
getContext().getContentResolver().notifyChange(_uri,null);
return _uri;
}
break;
}
return null;
}
#Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder)
{
SQLiteQueryBuilder sqLiteQueryBuilder = new SQLiteQueryBuilder();
switch (uriMatcher.match(uri))
{
case Person_ID:
sqLiteQueryBuilder.setTables(PTableName);
sqLiteQueryBuilder.appendWhere(PID+ "="+ uri.getPathSegments().get(1));
break;
case Person:
sqLiteQueryBuilder.setTables(PTableName);
break;
case Details_Id:
sqLiteQueryBuilder.setTables(DTableName);
sqLiteQueryBuilder.appendWhere(Per_In +"="+ uri.getPathSegments().get(1));
break;
case Details:
sqLiteQueryBuilder.setTables(DTableName);
break;
default:
throw new UnsupportedOperationException("Not yet implemented");
}
Cursor cursor = sqLiteQueryBuilder.query(sqLiteDatabase,projection,selection,selectionArgs,null,null,sortOrder);
cursor.setNotificationUri(getContext().getContentResolver(),uri);
return cursor;
}
#Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs)
{
int count = 0;
switch (uriMatcher.match(uri))
{
case Person:
count = sqLiteDatabase.update(PTableName,values,selection,selectionArgs);
break;
case Person_ID:
count = sqLiteDatabase.update(PTableName,values,PID+" = "+uri.getPathSegments().get(1)+(!TextUtils.isEmpty(selection)?" AND (" + selection + ')':""),selectionArgs);
break;
case Details:
count = sqLiteDatabase.update(DTableName,values,selection,selectionArgs);
break;
case Details_Id:
count = sqLiteDatabase.update(DTableName,values,Per_In+" = "+uri.getPathSegments().get(1)+(!TextUtils.isEmpty(selection)?" AND (" + selection + ')':""),selectionArgs);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri );
}
getContext().getContentResolver().notifyChange(uri,null);
return count;
}
#Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
// Implement this to handle requests to delete one or more rows.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public String getType(Uri uri) {
// TODO: Implement this to handle requests for the MIME type of the data
// at the given URI.
throw new UnsupportedOperationException("Not yet implemented");
}
}
Detils class:
public class Details
{
String name,date;
double amount;
public Details(String name, double amount, String date) {
this.name = name;
this.amount = amount;
this.date = date;
}
public Details() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public static Details from(Cursor cursor)
{
cursor.moveToFirst();
do {
Details details = new Details(cursor.getString(1),cursor.getDouble(3),cursor.getString(4));
return details;
}while (cursor.moveToNext());
}
}
Adapter class :
public class DetailsAdapter extends CursorRecyclerViewAdapter<DetailsAdapter.View_Holder>
{
public DetailsAdapter(Context context, Cursor cursor) {
super(context, cursor);
}
public static class View_Holder extends RecyclerView.ViewHolder
{
TextView mName,mAmount,mDate;
public View_Holder(View itemView)
{
super(itemView);
mName = (TextView)itemView.findViewById(R.id.DetailName);
mAmount = (TextView)itemView.findViewById(R.id.DetailAmount);
mDate = (TextView)itemView.findViewById(R.id.DetailDate);
}
}
#Override
public DetailsAdapter.View_Holder onCreateViewHolder(ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.addloglistlayout,parent,false);
View_Holder viewHolder = new View_Holder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(DetailsAdapter.View_Holder viewHolder, Cursor cursor)
{
Details details = Details.from(cursor);
viewHolder.mName.setText(details.getName());
viewHolder.mAmount.setText(String.valueOf(details.getAmount()));
viewHolder.mDate.setText(details.getDate());
}
}
Cursor Recyclerview Adapter class:
public abstract class CursorRecyclerViewAdapter<VH extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<VH> {
private Context mContext;
private Cursor mCursor;
private boolean mDataValid;
private int mRowIdColumn;
private DataSetObserver mDataSetObserver;
public CursorRecyclerViewAdapter(Context context, Cursor cursor) {
mContext = context;
mCursor = cursor;
mDataValid = cursor != null;
mRowIdColumn = mDataValid ? mCursor.getColumnIndex("_id") : -1;
mDataSetObserver = new NotifyingDataSetObserver();
if (mCursor != null) {
mCursor.registerDataSetObserver(mDataSetObserver);
}
}
public Cursor getCursor() {
return mCursor;
}
#Override
public int getItemCount() {
if (mDataValid && mCursor != null) {
return mCursor.getCount();
}
return 0;
}
#Override
public long getItemId(int position) {
if (mDataValid && mCursor != null && mCursor.moveToPosition(position)) {
return mCursor.getLong(mRowIdColumn);
}
return 0;
}
#Override
public void setHasStableIds(boolean hasStableIds) {
super.setHasStableIds(true);
}
public abstract void onBindViewHolder(VH viewHolder, Cursor cursor);
#Override
public void onBindViewHolder(VH viewHolder, int position) {
if (!mDataValid) {
throw new IllegalStateException("this should only be called when the cursor is valid");
}
if (!mCursor.moveToPosition(position)) {
throw new IllegalStateException("couldn't move cursor to position " + position);
}
onBindViewHolder(viewHolder, mCursor);
}
/**
* Change the underlying cursor to a new cursor. If there is an existing cursor it will be
* closed.
*/
public void changeCursor(Cursor cursor) {
Cursor old = swapCursor(cursor);
if (old != null) {
old.close();
}
}
/**
* Swap in a new Cursor, returning the old Cursor. Unlike
* {#link #changeCursor(Cursor)}, the returned old Cursor is <em>not</em>
* closed.
*/
public Cursor swapCursor(Cursor newCursor) {
if (newCursor == mCursor) {
return null;
}
final Cursor oldCursor = mCursor;
if (oldCursor != null && mDataSetObserver != null) {
oldCursor.unregisterDataSetObserver(mDataSetObserver);
}
mCursor = newCursor;
if (mCursor != null) {
if (mDataSetObserver != null) {
mCursor.registerDataSetObserver(mDataSetObserver);
}
mRowIdColumn = newCursor.getColumnIndexOrThrow("_id");
mDataValid = true;
notifyDataSetChanged();
} else {
mRowIdColumn = -1;
mDataValid = false;
notifyDataSetChanged();
//There is no notifyDataSetInvalidated() method in RecyclerView.Adapter
}
return oldCursor;
}
private class NotifyingDataSetObserver extends DataSetObserver {
#Override
public void onChanged() {
super.onChanged();
mDataValid = true;
notifyDataSetChanged();
}
#Override
public void onInvalidated() {
super.onInvalidated();
mDataValid = false;
notifyDataSetChanged();
//There is no notifyDataSetInvalidated() method in RecyclerView.Adapter
}
}
}
Thank you
Probably from method in Details causing issue due to cursor.moveToFirst(); and do-while loop. change it as:
public static Details from(Cursor cursor)
{
Details details = new Details(cursor.getString(1),
cursor.getDouble(3),
cursor.getString(4));
return details;
}
I have checked your adapter and all, so you are already moving your cursor to particular position from Adapter, so you don't need to set it moveToFist, so just remove the line cursor.moveToFirst() from Details Class and check result.

How implement my sqlite data in a GraphView?

I have my method to retrieve data from sqlite data using rawQuery. But now I don't know how to put it in the graph view,( for ex: all date and all weight column) put in the graphview
Here is the code to retrieve data
DBHelperNote connect = new DBHelperNote(AnalysisGraph.this);
SQLiteDatabase db = connect.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM weight;", null);
if (cursor.moveToNext()) {
d = cursor.getString(cursor.getColumnIndex("date"));
e = cursor.getString(cursor.getColumnIndex("weight"));
tv.setText(d);
tc.setText(d);
}
db.close();
and this is my graphview , and how can i use the retrieve data method that I have and add or combine the data to implement in my graphview ?
GraphView line_graph = (GraphView) contentView.findViewById(R.id.graph);
LineGraphSeries<DataPoint> line_series =
new LineGraphSeries<DataPoint>(new DataPoint[] {
new DataPoint(0, 1),
new DataPoint(1, 5),
new DataPoint(2, 3),
new DataPoint(3, 2),
new DataPoint(4, 6)
});
line_graph.addSeries(line_series);
line_series.setDrawDataPoints(true);
line_series.setDataPointsRadius(10);
line_series.setOnDataPointTapListener(new OnDataPointTapListener() {
#Override
public void onTap(Series series, DataPointInterface dataPoint) {
Toast.makeText(getActivity(), "Series: On Data Point clicked: " + dataPoint, Toast.LENGTH_SHORT).show();
}
You just make a one data model of your column list what you need and then store a data into that datamodel. So you can easily find a gap in that.
package yourpakage name;
public class datamodel {
private String id, weight, time, date;
public datamodel(String id, String weight, String time, String date) {
this.id = id;
this.weight = weight;
this.time = time;
this.date = date;
}
public String getId() {
return this.id;
}
public String getweight() {
return this.weight;
}
public String getTime() {
return this.time;
}
public String getDate() {
return this.date;
}
public void setid(String id) {
this.id = id;
}
public void setweight(String weight) {
this.weight = weight;
}
public void setTime(String time) {
this.time = time;
}
public void setDate(String date) {
this.date = date;
}
This a datamodel for your example.and than store your data into that like that. You make one array list file in main Arraylist<datamodel> your filename (file).
DBHelperNote connect = new DBHelperNote(AnalysisGraph.this);
file = new Arraylist<>;
SQLiteDatabase db = connect.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM weight;", null);
if (cursor.moveToNext()) {
file.add(new datamodel(data.getString(data.getColumnIndex("id")), data.getString(data.getColumnIndex("weight")),
, data.getString(data.getColumnIndex("time")),
data.getString(data.getColumnIndex("date"))));
}
db.close();
Now your data was store into datamodel then you just retrieve data from it.and display into graph easily you don't need to make an arraylist.

arraylist returning only one record

I tried to retrieve all data from database and put it into arraylist but i get only one record of table. here is my code :
where Birthdates is arraylist.
public ArrayList<String> read()
{
Birthdates.clear();
String selectQuery = "SELECT * FROM Birthday_Reminder";
Cursor crs=database.rawQuery(selectQuery,null);
System.out.println("In read");
if(crs.moveToFirst())
{
do {
Toast.makeText(con,"adding to arraylist", Toast.LENGTH_LONG).show();
Birthdates.add(crs.getString(crs.getColumnIndex("B_Date")));
}
while (crs.moveToNext());
}
return Birthdates;
}
i am doing this way by using getters and setters
package com.sunil.smilee;
public class DataOfUser {
int _id;
String _data;
String _date;
// Empty constructor
public DataOfUser(){
}
// constructor
// getting ID
public int getID(){
return this._id;
}
// setting id
public void setID(int id){
this._id = id;
}
// getting name
public String getD(){
return this._data;
}
// setting name
public void setD(String s){
this._data = s;
}
//
public void setDate(String string) {
// TODO Auto-generated method stub
this._date = string;
}
public String getDate(){
return this._date ;
}
}
// Add it in database class or change accordingly
// Getting All Contacts
public List<DataOfUser> getAllContacts() {
List<DataOfUser> dist = new ArrayList<DataOfUser>();
// Select All Query
String selectQuery = "SELECT * FROM " + ITEM.TABLE_DATA;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
DataOfUser contact = new DataOfUser();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setD(cursor.getString(1));
contact.setDate(cursor.getString(2));
dist.add(contact);//add data in list
} while (cursor.moveToNext());
//
}
// return contact list
return dist;
}

Categories

Resources