function only display first database entry. android, sqlite - android

I am trying to use some data from my database, but function only use data from first entry. What should I add to go through all the entries from database?
public void drawdayplan(){
DatabaseConnector dbConnector = new DatabaseConnector(Clock.this);
Intent a = getIntent();
String d_m_y = a.getStringExtra("d_m_y");
dbConnector.open();
Cursor result = dbConnector.gethour(d_m_y);
if(result.moveToFirst()){
int hourfromIndex = result.getColumnIndex("inthourfrom");
int hourtoIndex = result.getColumnIndex("inthourto");
int colourIndex = result.getColumnIndex("colour");
hourfrom = result.getInt(hourfromIndex);
hourto = result.getInt(hourtoIndex);
colour = result.getString(colourIndex);
// here are some steps with painting which are using this variables
}
}
result.close();
dbConnector.close();
}

But function only use data from first entry.
You never ask for more than the first row. Call moveToNext() in a loop like this:
while(result.moveToNext()){
// Read each row
}

Related

Handle Blob data type through ContentValues

I am trying to store and retrieve image data in Sqlite Db.
To do so I firstly stored in local device memory an example pic (path: storage/emulated/0/Download/).
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> {
private final String SAMPLE_IMAGE_PATH = "/storage/emulated/0/Download/image.jpg";
Then I set up an insert method to feed the db with these example data:
private void insertProduct() {
// Create a ContentValues object where column names are the keys,
// and sample attributes are the values.
ContentValues values = new ContentValues();
values.put(InventoryContract.ProductEntry.COLUMN_PRODUCT_NAME, sampleName);
values.put(InventoryContract.ProductEntry.COLUMN_PRODUCT_QTY, sampleQty);
values.put(InventoryContract.ProductEntry.COLUMN_PRODUCT_PRICE, SamplePrice);
values.put(InventoryContract.ProductEntry.COLUMN_EMAIL, sampleMail);
values.put(InventoryContract.ProductEntry.COLUMN_PHONE, samplePhone);
values.put(InventoryContract.ProductEntry.COLUMN_PRODUCT_PIC, SAMPLE_IMAGE_PATH);
//insert a new row
Uri newUri = getContentResolver().insert(InventoryContract.ProductEntry.CONTENT_URI,values);
}
and I define the onCreateLoader method as follows:
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// Define a projection that specifies the columns from the table we care about.
String[] projection = {
InventoryContract.ProductEntry._ID,
InventoryContract.ProductEntry.COLUMN_PRODUCT_PIC,
InventoryContract.ProductEntry.COLUMN_PRODUCT_PRICE,
InventoryContract.ProductEntry.COLUMN_PRODUCT_QTY,
InventoryContract.ProductEntry.COLUMN_PRODUCT_NAME};
// This loader will execute the ContentProvider's query method on a background thread
return new CursorLoader(this,
InventoryContract.ProductEntry.CONTENT_URI,
projection,
null,
null,
null);
}
In the CursorAdapter class I updated the listView adding the data from db in bindView() method:
public void bindView(View view, Context context, Cursor cursor) {
// Find individual views that we want to modify in the list item layout
TextView nameTextView = (TextView) view.findViewById(R.id.prod_name);
TextView priceTextView = (TextView) view.findViewById(R.id.prod_price);
TextView qtyTextView = (TextView) view.findViewById(R.id.prod_qty);
ImageView prodImageView = (ImageView) view.findViewById(R.id.prod_img);
// Find the columns of attributes that we're interested in
int nameColumnIndex = cursor.getColumnIndex(InventoryContract.ProductEntry.COLUMN_PRODUCT_NAME);
int priceColumnIndex = cursor.getColumnIndex(InventoryContract.ProductEntry.COLUMN_PRODUCT_PRICE);
int qtyColumnIndex = cursor.getColumnIndex(InventoryContract.ProductEntry.COLUMN_PRODUCT_QTY);
int picColumnIndex = cursor.getColumnIndex(InventoryContract.ProductEntry.COLUMN_PRODUCT_PIC);
// Read the attributes from the Cursor for the current product
String prodName = cursor.getString(nameColumnIndex);
Double prodPrice = cursor.getDouble(priceColumnIndex);
int prodQty = cursor.getInt(qtyColumnIndex);
byte [] prodImg = cursor.getBlob(picColumnIndex);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inTempStorage = new byte[1024 * 32];
Bitmap bmp = BitmapFactory.decodeByteArray(prodImg, 0, prodImg.length, options);
//Update Views
nameTextView.setText(String.valueOf(prodName));
priceTextView.setText(prodPrice.toString());
qtyTextView.setText(String.valueOf(prodQty));
prodImageView.setImageBitmap(bmp);
}
}
When I try execute this code everything goes ok, but I see a blank image instead of both the selected pic and placer pic.
So I think that there is some problem with inserting data into db.
I am trying to store and retrieve image data in Sqlite Db
I do not recommend this. Store the images in files. Store data in the rows that identifies the files.
Then I set up an insert method to feed the db with these example data
You are storing a string in COLUMN_PRODUCT_PIC. You are not storing a byte[]. This is good, relative to my recommendation. This is bad relative to your data-retrieval code, where you are attempting to retrieve a byte[].

Collect data from sqlite and display it in TextView

I was able to be extracted the data that interest me in this way:
Cursor stipcursor = dataBase.rawQuery("SELECT (riepilogo) AS stip FROM "+DbHelper.RIEPILOGO+" WHERE MESI = 'Gennaio' and ANNI = "+anno+"", null);
int colIndexstip = stipcursor.getColumnIndex("stip");
if (colIndexstip == -1)
return;
else
stipcursor.moveToFirst();
double stip = stipcursor.getDouble(colIndexstip);
System.out.println("Riepilogo"+stip);
the problem is that if the database has data, everything works, but if the database is empty, the application crashes.
As given in this post, try this
if ( cursor.moveToFirst() ) {
// start activity a
} else {
// start activity b
}
cursor.moveToFirst() will return false if the cursor is empty. It works for me always.
You can try the first method given on that post also.

How to get saved value in sqlite database to list in Android?

I am trying to get saved values in a list. I am creating anotepad and I want when anybody open notepad every saved list display on homepage in a list.
I have successfully saved the value in a database but when I am trying to get a value in a list it is giving full string value like this "com.todo.task.activity#4106a690" in every single row.
I think problem is in my database getlist() method please check:
public List<TaskDetailsActivity> GetAddTaskLists() {
List<TaskDetailsActivity> TaskLists = new ArrayList<TaskDetailsActivity>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_TASKLISTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
TaskDetailsActivity tasks = new TaskDetailsActivity();
tasks.settaskLists_ID(cursor.getString(0));
tasks.settasklists_Title(cursor.getString(1));
// Adding Doc to list
TaskLists.add(tasks);
} while (cursor.moveToNext());
}
// return Doc list
return TaskLists;
}
Here I am calling database method like this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView list_tasklistname = (ListView)findViewById(R.id.list_tasklistname);
TaskManager_Database db = new TaskManager_Database(getApplicationContext());
list = db.GetAddTaskLists();
ArrayAdapter<TaskDetailsActivity> adapter = new ArrayAdapter<TaskDetailsActivity>(getApplicationContext(),
android.R.layout.simple_list_item_1, list);
list_tasklistname.setAdapter(adapter);
adapter.notifyDataSetChanged();
Please let me know what is the error. Thanks
You are getting object representation of objects been added to ListView...
In your case you should return data in cursor.getString(1) for adapter input param i.e. String array...... i.e list must be a string array or ArrayList... if you know what I mean..
check out this sample for ref
Your TaskDetailsActivity class should define a toString() method that returns whatever you want to display for that row.

How to store data from SQLite in a 2D Arraylist?

I need to get all of the information from my SQLite Database and store it in an Array List, or some other way if there is a better way. My database has 6 columns, here is how I am attempting to extract the data and store it in an Arraylist index;
db.open();
for(int i = 0; i<= amount; i++)
{
Cursor c = db.fetchAllNotes();
if (c.moveToFirst())
{
do {
mid = c.getString(0);
place =c.getString(1);
info =c.getString(2);
coordl1 =c.getString(3);
coordl2 =c.getString(4);
colour =c.getString(5);
//code here to store each string in an Array index
mapSetupList.add(mid,place,info,coordl1,coordl2,colour);
}while (c.moveToNext());
}
}
db.close();
I know how to create an Array list, but I do not know how to store 6 strings in one index, I experimented with 2D Arraylists, but this seemed to be too complicated and I didn't think it was the right way to do it. Is there a better way to do this, if not how can this be done with Arraylists?
What about to create one own defined Object that will wrap all columns as properties?
public class Foo {
private int id; // alternative to id column in db
private String type;
private String date;
...
public void setId(int id) { // setter
this.id = id;
}
public int getId() { // getter
return this.id;
}
}
Then create ArrayList<Foo> and now you can simply save data from SQLite into ArrayList:
public void store() {
Cursor c = null; // first declare and initialise appropriate objects
ArrayList<Foo> foos = new ArrayList<Foo>();
Foo member = null;
try {
c = db.rawQuery(query, whereArgs); // perform query
if (c.moveToFirst()) { // move cursor to first row because implicitly
do { // cursor is position before first row
member = new Foo(); // for each row create new Foo
member.setId(c.getInt(0)); // initialise properties
member.setType(c.getString(1));
member.setDate(c.getString(2));
...
foos.add(member); // add Foo into ArrayList
} while (c.moveToNext()); // it moves cursor to next row
}
}
finally { // in finally block release datasource(s), cursor(s)
if (c != null) {
c.close();
}
if (db != null && db.isOpen()) {
db.close();
}
}
}
Note: I recommend this approach. It's clear, safe and effective. Don't forget to release any datasources, cursors after work is done to avoid usually thrown exceptions like cursor is already open, database is already closed etc.
Update:
I am unsure about the class example, with the defined object and
getters and setters, can you please elaborate before I try this? Thank
you!!
So getters and setters are methods which are used "generaly "for manipulating with properies of Object to preserve Encapsulation - very important thing in OOP. Setters are used for initialising properties and getters for getting properties of Object.
Now i wrote for you example of method for store data from sqlite into ArrayList. There is this line:
member.setId(c.getInt(0));
where setId(c.getInt(0)) is setter of Foo Object with one Integer as parameter and with this method now you will fill up id value with data from Cursor.
Create a Class that contains all the informations that you like, and then create an instance of it then add that instance to the ArrayList.

Sorting the contents of ArrayAdapter or ArrayList

I am working on android project and am making using of a ListView that retrieves data from the SQLite database.
I am making a dataset using an ArrayList and then adding this ArrayList into an ArrayAdapter.
When the data is being retrieved from the database, I am telling SQLite to do the sorting so everything is in alphabetical order when it is added into the ListView. At certain times, the information will be added dynamically to to the ListView without it requiring to re-fetch everythin from the database again. However, I want to keep everything in alphabetical order.
How would I do this, do I sort the DataSet and then call the notifyDataSet Changes or do I do the sort directly on the ArrayAdapter. I've looked into performing the sort on the ArrayAdapter but this wants an argument that uses a Comparator but not sure what this is and can't find any working examples that may be of any help for what I want to achieve.
Below is the code that populates the array and sets the list adapter
ArrayList<Spanned> passwords = managePasswordList.getPasswordList();
if (passwords != null && passwords.size() > 0)
{
passwordArrayAdapter = new ArrayAdapter<Spanned>(getActivity().getApplicationContext(),
android.R.layout.simple_list_item_activated_1, passwords);
setListAdapter(passwordArrayAdapter);
myListView.setTextFilterEnabled(true);
txtNoRecords.setVisibility(View.GONE);
}
else
{
txtNoRecords.setVisibility(View.VISIBLE);
}
I am then adding data to the dataset and refreshing the list view using the following
String company = Encryption.decrypt(passwords.get(i).company);
String username = Encryption.decrypt(passwords.get(i).username);
details = Html.fromHtml(company + "<br />" + "<small><font color=\"#767676\">" + username + "</b></small>");
passwords.add(details);
passwordArrayAdapter.notifyDataSetChanged();
Thanks for any help you can provide.
UPDATE 1
I've tried doing what Nick Bradbury suggested but I am having a problem with the comparator. I have the following code but I don't know where to go from here.
SQLiteDatabase myDb = null;
Cursor cursor = null;
ArrayList<Spanned> passwords = new ArrayList<Spanned>();
try
{
myDb = context.openOrCreateDatabase("PasswordManager", Context.MODE_PRIVATE, null);
cursor = myDb.rawQuery("SELECT * FROM password ASC", null);
while (cursor.moveToNext())
{
final String company = Encryption.decrypt(cursor.getString(2));
final String username = Encryption.decrypt(cursor.getString(4));
Spanned details = Html.fromHtml(company + "<br />" + "<small><font color=\"#767676\">" + username + "</b></small>");
passwords.add(details);
Collections.sort(passwords, new Comparator<Spanned>() {
public int compare(Spanned lhs, Spanned rhs) {
return 0;
}
});
}
}
catch (SQLiteException ex)
{
common.showBasicAlertDialog("Unfortunately something has gone wrong.\n\nWe will fix this as soon as we can", false);
Log.e("Database Error", ex.toString());
return null;
}
In the return statement I have no idea what to do, I've tried return lhs.compareTo but the lhs and rhs variables don't have the compareTo function so I have not got a clue what to do.
Here's a simple example of sorting an ArrayList using Comparator. In this example, the ArrayList is defined as:
public class StatusList extends ArrayList<Status>
A sort routine for this ArrayList could look like this:
public void sort() {
Collections.sort(this, new Comparator<Status>() {
#Override
public int compare(Status item1, Status item2) {
return item2.getDate().compareTo(item1.getDate());
}
});
}
Replace <Status> with whatever object your ArrayList contains, then change the comparison to compare the values of the object you wish to sort by.

Categories

Resources