Iterating specific count of data from a Cursor in Android - android

I want to iterate through a cursor data from a database, i won't be returning all of the data from the cursor. I would only need 5 randomized row of data I have the logic to return all data below but I only want five rows to be returned.
private ArrayList<Insect> insectList(){
ArrayList<Insect> insects = new ArrayList<>();
Collections.shuffle(insects);
if (cursor.moveToFirst()) {
do {
Insect insect = new Insect();
insect.setName(cursor.getString(cursor.getColumnIndex(BugsContract.BugsEntry.COLUMN_FRIENDLYNAME)));
insect.setScientificName(cursor.getString(cursor.getColumnIndex(BugsContract.BugsEntry.COLUMN_SCIENTIFICNAME)));
insect.setClassification(cursor.getString(cursor.getColumnIndex(BugsContract.BugsEntry.COLUMN_SCIENTIFICNAME)));
insect.setImageAsset(cursor.getString(cursor.getColumnIndex(BugsContract.BugsEntry.COLUMN_IMAGEASSET)));
insect.setDangerLevel(Integer.parseInt(cursor.getString(cursor.getColumnIndex(BugsContract.BugsEntry.COLUMN_DANGERLEVEL))));
insects.add(insect);
} while (cursor.moveToNext());
}
return insects;
}
Which perfect loop can i use to achieve only five rows from this cursor while iterating

if (cursor.getCount() > 0) {
int count = 0;
while (cursor.moveToNext()){
if(count < 5){
count++;
Insect insect = new Insect();
insect.setName(cursor.getString(cursor.getColumnIndex(BugsContract.BugsEntry.COLUMN_FRIENDLYNAME)));
insect.setScientificName(cursor.getString(cursor.getColumnIndex(BugsContract.BugsEntry.COLUMN_SCIENTIFICNAME)));
insect.setClassification(cursor.getString(cursor.getColumnIndex(BugsContract.BugsEntry.COLUMN_SCIENTIFICNAME)));
insect.setImageAsset(cursor.getString(cursor.getColumnIndex(BugsContract.BugsEntry.COLUMN_IMAGEASSET)));
insect.setDangerLevel(Integer.parseInt(cursor.getString(cursor.getColumnIndex(BugsContract.BugsEntry.COLUMN_DANGERLEVEL))));
insects.add(insect);
}
}
cursor.close();
}

Related

Getting a selected row from an Arraylist in Android

I have an arraylist populated with data from a cursor, I would like to get a selected or single record from this list which I would need to pass as an intent, how possible can I achieve this.
private ArrayList<Insect> insectList(){
insects = new ArrayList<>();
if (cursor.getCount() > 0){
int count = 0;
while (cursor.moveToNext()){
if (count < quizActivity.ANSWER_COUNT){
count++;
insect = new Insect(cursor.getString(cursor.getColumnIndex(BugsContract.BugsEntry.COLUMN_FRIENDLYNAME)),
cursor.getString(cursor.getColumnIndex(BugsContract.BugsEntry.COLUMN_SCIENTIFICNAME)),
cursor.getString(cursor.getColumnIndex(BugsContract.BugsEntry.COLUMN_SCIENTIFICNAME)),
cursor.getString(cursor.getColumnIndex(BugsContract.BugsEntry.COLUMN_IMAGEASSET)),
Integer.parseInt(cursor.getString(cursor.getColumnIndex(BugsContract.BugsEntry.COLUMN_DANGERLEVEL)))
);
insects.add(insect);
Collections.shuffle(insects);
}
}
}
return insects;
}
I need to get a selected record from the Arraylist insects

how to ignore null values from the database in comparing values entered by the user in android

I'm trying to save user information in my application. I have Employee number editText and Company EditText. My employee number is not a required field so that means my table can have null values. My problem is when I am comparing if the employee number entered by the user already exist in my database, it also reads the null values when the user do not enter anything on the employee number editText. Can anyone help me do this please?
This is my code where I save all the employee number in an arraylist and remove all the null values
ArrayList<String> employeenumber = databaseAdapter.getEmployeeNumber();
employeenumber.removeAll(Collections.singleton(null));
employeenumber.removeAll(Collections.singleton(""));
What I wanna do is, if the user enter employee number, it will check if the arraylist contains it and if yes, it will all check the company corresponds to it. I need to trap duplicate entry. For example the employee number is 1234 and the company is ABCD, the program must not accept it. Thanks for anyone who could help me.
First check whether the user enter something on employee number editText. Then use int flag to compare it. Try the code below in your main activity:
int flag1 = 0;
if (!Emp.equals(""))
{
ArrayList<String> CompanyandEmp = new ArrayList<String>();
CompanyandEmp = databaseAdapter.getCompanyEmp(Emp);
CompanyandEmp.removeAll(Collections.singleton(""));
for(int i=0;i< CompanyandEmp.size();i++)
{
String cmpemp = CompanyandEmp.get(i).toString();
if(cmpemp.equalsIgnoreCase(companyName))
{
flag1 = 1;
}
}
}
if (flag1 == 0)
{
//as per your requirement
}else{
Toast.makeText(RegistrationActivity.this, "Account info already exist.", Toast.LENGTH_LONG).show();
}
Then in your databaseAdapter:
public ArrayList<String> getCompanyEmp(String emp) {
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<String> companyemp = new ArrayList<String>();
try {
Cursor c = db.query("select CompName FROM projsitemast where Emp='"+emp+"'", null);
if (c != null) {
c.moveToFirst();
for (int j = 0; j < c.getCount(); j++) {
companyemp.add(c.getString(0));
c.moveToNext();
}
c.close();
}
return companyemp;
} catch (Exception e) {
e.printStackTrace();
}
return companyemp;
}

Convert Android Cursor to ArrayList of arrays

I try to convert my Cursor data to a arraylist. But at the end all the data in the arraylist is overwrited with the last row. What do i do wrong?
Cursor c = myDbHelper.getLvl1Cata();
String[] data = new String[3];
c.moveToFirst();
while(!c.isAfterLast()) {
data[0] = Integer.toString(c.getInt(0));
data[1] = c.getString(1);
data[2] = Integer.toString(c.getInt(2));
Log.e("cc", data[1]);
catalogueData.add(data);
c.moveToNext();
}
Try this
Cursor c = myDbHelper.getLvl1Cata();
String[] data;
if (c != null) {
while(c.moveToNext()) {
data = new String[3]; // Note this addition
data[0] = Integer.toString(c.getInt(0));
data[1] = c.getString(1);
data[2] = Integer.toString(c.getInt(2));
Log.e("cc", data[1]);
catalogueData.add(data);
}
c.close();
}
data is an array of strings. In the original code, you added the same array to your catalogueData structure several times. You changed the value of the array's contents each time, but it was still the same array object. So you ended up with catalogueData holding several references to a single array, and that array can only have one value for data[0]: the last thing you set it to.
This answer fixes that by using a new and different array for each row in the cursor.
Try this:
if(mycursor!=null){
do{
TextView name = (TextView)view.findViewById(R.id.contact_name);
name.setText(cursor.getString(cursor.getColumnIndex
(Displayname)));
mycursor.moveToNext();
}while (mycursor.isLast());
}
Put String[] data = new String[3]; into the while loop. You're overwriting the array object with each iteration.

How do i get data from an SQLITE database to an array in android?

Pretty sure this is an easy one, but i'm getting confused by all the examples that adapt the data returned from a cursor into different views. I just want to run a rawquery and put each item of data returned into a float array (so that i can add them up later). What do i need to use for this? Thanks
You'll still have a cursor when you query your database, but once you got the cursor you could iterate over it, pulling out the values you need into an array, like this:
DbAdapter db = new DbAdapter(mContext);
int columnIndex = 3; // Whichever column your float is in.
db.open();
Cursor cursor = db.getAllMyFloats();
float[] myFloats = new float[cursor.getCount()-1];
if (cursor.moveToFirst())
{
for (int i = 0; i < cursor.getCount(); i++)
{
myFloats[i] = cursor.getFloat(columnIndex);
cursor.moveToNext();
}
}
cursor.close();
db.close();
// Do what you want with myFloats[].
Don't minus by 1 in float[] myFloats = new float[cursor.getCount()-1]; because (int i =0) or i start from 0. If you use it, will appear Java.lang.IndexOutOfBoundsException. You need array index until [cursor.getCount()], not until [cursor.getCount()-1]. So the correct thing is float[] myFloats = new float[cursor.getCount()];

How to set spinner selection by id not position

I have created a simple Spinner binding it to a SimpleCursorAdapter. I'm populating the SimpleCursorAdapter with a list of towns from a content provider.
When I go to save the users selection I'm planning on saving the row id that is being populated into my SimpleCursorAdapter.
I'm using the following code to get the ID.
townSpinner.getSelectedItemId();
What I can not figure out is how best to set the selection when I pull back up the saved item.
The following code works but it only sets selection by position number.
townSpinner.setSelection(2);
Should I just create a loop to determine the correct position value based on Id?
long cityId = Long.parseLong(cursor.getString(CityQuery.CITY_ID));
for (int i = 0; i < citySpinner.getCount(); i++) {
long itemIdAtPosition2 = citySpinner.getItemIdAtPosition(i);
if (itemIdAtPosition2 == cityId) {
citySpinner.setSelection(i);
break;
}
}
I think you've answered your own question there!
Just write your own setSelectionByItemId method using the code you posted
Example:
DB:
public Cursor getData() {
SQLiteDatabase db = getReadableDatabase();
String sql = "select ID _id, Name from MyTable order by Name ";
Cursor c = db.rawQuery(sql, null);
c.moveToFirst();
return c;
}
Activity:
Cursor myCursor = db.getData();
SimpleCursorAdapter adapter1 = new SimpleCursorAdapter(
this,
android.R.layout.simple_spinner_item,
myCursor,
new String[] { "Name" }, new int[] { android.R.id.text1 }, 0);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mySpinner.setAdapter(adapter1);
for(int i = 0; i < adapter1.getCount(); i++)
{
if (adapter1.getItemId(i) == myID )
{
mySpinner.setSelection(i, false); //(false is optional)
break;
}
}
Android Spinner set Selected Item by Value
The spinner provides a way to set the selected valued based on the position using the setSelection(int position) method. Now to get the position based on a value you have to loop thru the spinner and get the position. Here is an example
mySpinner.setSelection(getIndex(mySpinner, myValue));
private int getIndex(Spinner spinner, String myString){
int index = 0;
for (int i=0;i<spinner.getCount();i++){
if (spinner.getItemAtPosition(i).equals(myString)){
index = i;
}
}
return index;
}
If you are using an ArrayList for your Spinner Adapter then you can use that to loop thru and get the index. Another way is is to loop thru the adapter entries
Spinner s = (Spinner) findViewById(R.id.spinner_id);
for(i=0; i < adapter.getCount(); i++) {
if(myString.trim().equals(adapter.getItem(i).toString())){
s.setSelection(i);
break;
}
}

Categories

Resources