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.
Related
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;
}
}
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.
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.
I'm using ORMLite (v4.48) with my Android app. I have the table "Contact" which can contain multiple "Email" (ForeignCollectionField) and one "Personal" (DatabaseField) object. When I get the Contact object from the database I would like to automatically get (or lazy load) the Personal object which has the same Contact ID.
It already automatically gets the Email objects which I can access. But for some reason the Personal object is always "null" even though there is an entry in the Personal table.
Here are my classes:
#DatabaseTable(tableName = "Contact", daoClass = ContactDao.class)
public class Contact {
#DatabaseField(generatedId = true, columnName = PersistentObject.ID)
int id;
#DatabaseField(index = true)
String contactName;
#ForeignCollectionField(eager = false)
ForeignCollection<Email> emails;
#DatabaseField(foreign = true)
public Personal personal;
public ForeignCollection<Email> getEmails() {
return emails;
}
public void setEmails(ForeignCollection<Email> emails) {
this.emails = emails;
}
public Personal getPersonal() {
return personal;
}
public void setPersonal(Personal personal) {
this.personal = personal;
}
...
}
And
#DatabaseTable(tableName = "Email", daoClass = EmailDao.class)
public class Email {
#DatabaseField(generatedId = true, columnName = PersistentObject.ID)
int id;
#DatabaseField(foreign = true, foreignAutoRefresh = true, columnName = PersistentObject.CONTACT_ID_FIELD_NAME) // contact_id
Contact contact;
#DatabaseField
String emailType;
#DatabaseField(canBeNull = false)
String email;
public Email() {
}
public Email(int id, Contact Contact, String emailType, String email) {
this.id = id;
this.contact = contact;
this.emailType = emailType;
this.email = email;
}
public int getId() {
return id;
}
public Contact getContact() {
return contact;
}
public void setContact(Contact contact) {
this.contact = contact;
}
public String getEmailType() {
return emailType;
}
public void setEmailType(String emailType) {
this.emailType = emailType;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
...
}
and
#DatabaseTable(tableName = "Personal", daoClass = PersonalDao.class)
public class Personal {
#DatabaseField(generatedId = true, columnName = PersistentObject.ID)
int id;
#DatabaseField(foreign = true, foreignAutoRefresh = true, columnName = PersistentObject.CONTACT_ID_FIELD_NAME)
Contact contact;
#DatabaseField
int age;
#DatabaseField
int weight; // in grams
#DatabaseField
int height; // in cm
public Personal() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Contact getContact() {
return contact;
}
public void setContact(Contact contact) {
this.contact = contact;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
}
I'm getting the data from the database like this:
QueryBuilder<Contact, Integer> queryBuilder = mContactDao.queryBuilder();
queryBuilder.orderBy("lastViewed", false);
queryBuilder.limit(limit);
PreparedQuery<Contact> preparedQuery = queryBuilder.prepare();
List<Contact> contactList = mContactDao.query(preparedQuery);
that all works well so far.
Then further down the code I can access the Email objects like this:
ForeignCollection<Email> emails = contact.getEmails();
Iterator<Email> iter = emails.iterator();
while (iter.hasNext()) {
Email iAddress = iter.next();
Log.d(TAG, "EMAIL: " + iAddress.getEmail());
Log.d(TAG, "EMAIL TYPE: " + iAddress.getEmailType());
}
Which also works perfectly. Only if I want to access the Personal object I always get NULL.
Personal personal = contact.getPersonal(); // is always NULL
I can't figure out why that is. Do I manually need to add a JOIN in the query builder? I thought it would also lazily load the data once I access it with getPersonal() like it does with getEmails()?
You did not show how entity instances are created, but i assume Personal is created after Contact has been inserted. If that is a case, then after inserting Personal you should do contact.setPersonal(personal), and contactDao.update(contact) - that way personal_id will be stored in contact row
I am trying to implement search on user input. The serach results will be shown after searching the relevant option from database.
I have made this method to display the results
public Cursor getBooksBySearch(String query) {
// TODO Auto-generated method stub
String[] args={query};
return(getReadableDatabase().rawQuery("SELECT _id,chapter FROM chapters WHERE chapter LIKE '%" + query + "%", args));
}
Here the query is coming from an activity SearchResultAcitvity.java
Intent intent = getIntent();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
ListView myListView = (ListView)findViewById(R.id.txt_query);
dbBookHelper = new BooklistHelper(this);
ourCursor = dbBookHelper.getBooksBySearch(query);
startManagingCursor(ourCursor);
adapter = new BookAdapter(ourCursor);
myListView.setAdapter(adapter);
myListView.setOnItemClickListener(onListClick);
}
I want to match this coming query string to get the results from my chapter table.
Can I just match the query string m getting in String query = intent.getStringExtra(SearchManager.QUERY) with the data in my database.
Using list view to display.
Please help me in this.
Let me know if you want more information
Thanks in Advance :)
This will return list of data search by keyword
public ArrayList<ObjectType> getSearchData(String keyword)
{
ArrayList<ObjectType> objectTypeList = new ArrayList<ObjectType>();
SQLiteDatabase db = getWritableDatabase();
String checkEntry="SELECT id,firstname,lastname FROM abc_table WHERE firstname like '%"+ keyword +"%'" +" or "+ "p.lastname like '%"+ keyword +"%'";
Cursor cursor = db.rawQuery(checkEntry, null);
try
{
//If entry exist then update
if (cursor.moveToFirst())
{
do
{
ObjectType objectType = new ObjectType();
int PID=cursor.getInt(0);
String fname = cursor.getString(1);
String LastName = cursor.getString(2);
objectType.setFirstName(fname);
objectType.setLastName(LastName);
objectTypeList.add(objectType);
}
while(cursor.moveToNext());
}
}
finally
{
if(cursor != null)
cursor.close();
}
return objectTypeList;
}
ObjectType is class
public class ObjectType {
int id;
String firstName;
String lastName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
Hope this ll help you.. :)