I am trying to implement a user search through my database with the use of spinners.
I have fleets and vehicles(fleets contain vehicles). I have a list of fleets as one spinner and a list of vehicles as the other.
By default I want the fleets to be set to "All" and the vehicle one to show all the vehicles(This is currently the case), however when the fleet input is changed to a particular one, say fleet1, the vehicle spinner should update accordingly[this will be implemented via SQLite database search but I don't think the issue is here].
How do I make a listener for when fleet spinner data is changed?
vehicleSpinner = (Spinner) findViewById(R.id.vehicleSpinner);
String selected = (String)fleetSpinner.getSelectedItem();
ArrayAdapter<String> adapter5 = null;
if(selected == "All"){
//show all vehicles
adapter5 = new ArrayAdapter<String>(this, R.layout.sherlock_spinner_item, vehicleArrayListString);
}else{
String vehiclesInFleetQuery = "SELECT * FROM " + Database.TABLE_VEHICLE + " WHERE " + Database.COLUMN_FLEET + "='" + selected +"'";
Log.i(TAG,"QUERY: "+ vehiclesInFleetQuery);
Cursor cursor = Database.listOfVehiclesDesired(query);
if(cursor.moveToFirst()){
do {
String addToList = cursor.getString(cursor.getColumnIndex(Database.COLUMN_VEHICLE_ID));
vehicleArrayFleet.add(addToList);
} while (cursor.moveToNext());
}else{//error on fleet search, no vehicles in fleet
vehicleArrayFleet = vehicleArrayListString;
builderContinue.setMessage("Selected Fleet(" + selected + ") had zero associated vehicles").setTitle("Error").show();
}
if (cursor != null && !cursor.isClosed()) {
System.out.println("Closed");
cursor.close();
}
adapter5 = new ArrayAdapter<String>(this, R.layout.sherlock_spinner_item, vehicleArrayFleet);
}
adapter5.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);
vehicleSpinner.setAdapter(adapter5);
You need to set an OnItemSelectedListener for the fleet spinner. You can find an example at http://start-jandroid.blogspot.com/2011/01/android-spinner-example.html. From the listener in the fleet spinner, you can set the selected item of the vehicle spinner.
Related
I created a small activity that displays all contacts with phone numbers in my phone. However, there are duplicates for contacts that have whatsapp installed. For example, if John is in my contact list and he has a whatsapp account as well, the list would look like this:
...
Jake
John
John
JP
...
This is my code for assigning the cursor to the the adapter which links to a listview.
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String sortOrder = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC";
final Cursor cursor = getContentResolver().query(uri, null, null, null, sortOrder);
String[] from = {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone._ID};
int[] to = {android.R.id.text1};
adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_multiple_choice, cursor, from, to, 0);
EDIT
With this code, I confirmed that the duplicates have 0 value for the ContactsContract.CommonDataKinds.Phone.TYPE which means it is a custom contact (Whatsapp). The rest are 2 which means it is a normal contact.
I need to figure out a query where it doesn't use any contacts where ContactsContract.CommonDataKinds.Phone.TYPE == 0
I know it might be a bit late. However I was having the same issue.
ContactsContract.CommonDataKinds.Phone.TYPE as per the android documentation refers not to whether it is a custom contact but to what type of contact it is i.e. Mobile(2), Home(1) or Work(3). Whatsapp contacts will be a 2 - mobile.
I used the following function to remove the duplicates (not sure if there is a better way):
private boolean checkDuplicate(String position) {
LinkedHashMap<String, Integer> map;
Integer testNull;
map=new LinkedHashMap<>();
testNull=map.get(position);
if(testNull==null) {
testNull=1;
map.put(position, testNull);
return false;
}
else {
testNull=testNull+1;
if(testNull==2) {
return true;
}
else {
map.put(position, testNull);
return false;
}
}
}
I have a problem with my SQLiteOpenHelper class.
I have a database with printer manufacturers and details of any kind of printer.
I try to get all manufacturer from my database with this code and returning them in a arraylist.
// Read database for All printer manufacturers and return a list
public ArrayList<String> getPrManufacturer(){
ArrayList<String> manufacturerList = new ArrayList<String>();
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query(CoDeskContract.Printer.TABLE_NAME,
printerManuProjection, null, null, null, null, null,null);
// If cursor is not null and manufacturer List
// does not contains Manufacturer in the list then add it!
if ((cursor != null) && (cursor.getCount()>0)){
cursor.moveToFirst();
do {
String cursorManufacturer = cursor.getString(0);
//Checking for manufacturer in the list
for(String manufacturerInList:manufacturerList){
if (!manufacturerInList.equals(cursorManufacturer))
manufacturerList.add(cursorManufacturer);
}
}while(cursor.moveToNext());
}
// Return list of manufacturers from database
return manufacturerList;
}
I want every manufacturer to be once in a list.
Somehow i cant to get it to work.
Im still a newbie.
Thanks for any Help.
You can also use the distinct keyword in SQLite (http://www.sqlite.org/lang_select.html). Use SQLiteDatabase.rawQuery(String query, String[] args) for that.
db.rawQuery("SELECT DISTINCT name FROM " + CoDeskContract.Printer.TABLE_NAME,null);
There are two issues:
In the beginning, when your list manufacturerInList is empty then it will not go inside for(String manufacturerInList:manufacturerList){ loop and hence it will never add any entry in the list.
Once you fix your problem 1, still it will not work as if (!manufacturerInList.equals(cursorManufacturer)) checks against each entry in the list and adds the non matching entry in the list possibly multiple times.
To fix the issue, you have two options.
Option1: Use contains as:
if (!manufacturerList.contains(cursorManufacturer)) {
manufacturerList.add(cursorManufacturer);
}
Option2: Use a matchFound boolean flag as:
String cursorManufacturer = cursor.getString(0);
boolean matchFound = false;
//Checking for manufacturer in the list
for(String manufacturerInList:manufacturerList){
if (manufacturerInList.equals(cursorManufacturer)){
matchFound = true;
break;
}
}
if(!matchFound){ // <- doesn't exit in the list
manufacturerList.add(cursorManufacturer);
}
Use ArrayList.contains(Object elem) to check if item is exist in ArrayList or not Change your code as:
// does not contains Manufacturer in the list then add it!
if ((cursor != null) && (cursor.getCount()>0)){
cursor.moveToFirst();
do {
String cursorManufacturer = cursor.getString(0);
//Checking for manufacturer in the list
if (!manufacturerList.contains(cursorManufacturer)) {
manufacturerList.add(cursorManufacturer);
} else {
System.out.println("cursorManufacturernot found");
}
}while(cursor.moveToNext());
}
I have an application that has 2 screens. The first screen has a ListView of movies with a row consisting of 3 Elements: Title, Date and Gross declared in strings.xml. The user has the option of adding a movie by clicking the menu button, which sends him to another screen. The second screen has 3 Edit texts that correspond to Title Date and Gross, which is alphabetically sorted straight away when it returns to screen 1.
Similarly, the user can also Edit/Delete entries by long clicking a row thatbrings up a context menu. The Edit function works like this:
a.) User long clicks Titanic and chooses Edit
b.) Row gets deleted, and user is brought to screen 2
c.) Edit texts are populated with the initial data from the deleted Row
d.) When user edits data, new movie is added at the bottom of the ListView.
The problem arises when the user deletes this new movie at the bottom of the ListView. Logcat gives a
java.lang.IndexOutOfBoundsException: Invalid index 50, size is 50
Here is my code (Take note I am using Perst to persist data, but I don;t think that won't really matter with my problem):
case R.id.contextedit:
Lab9_082588FetchDetails row = (Lab9_082588FetchDetails) getListView()
.getItemAtPosition(info.position);
Intent editData = new Intent(MovieList.this, Lab9_082588Edit.class);
String startTitle = row.getTitle();
String startGross = row.getGross();
String startDate = row.getDate();
editData.putExtra(Lab9_082588Edit.TITLE_STRING, startTitle);
editData.putExtra(Lab9_082588Edit.GROSS_STRING, startGross);
editData.putExtra(Lab9_082588Edit.DATE_STRING, startDate);
startActivityForResult(editData, MovieList.EDIT_MOVIE);
int posEdit = info.position;
String editTitle = results.get(info.position).getTitle();
results.remove(posEdit);
adapter.notifyDataSetChanged();
//Perst
Index<Lab9_082588FetchDetails> rootEdit = (Index<Lab9_082588FetchDetails>) db
.getRoot();
rootEdit.remove(editTitle, results.get((int) info.id));
db.setRoot(rootEdit);
return true;
Edit Class:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection using item.getItemId()
switch (item.getItemId()) {
case R.id.edit:
next();
break;
}
return true;
}
private void next() {
// TODO Auto-generated method stub
EditText movieTitle = (EditText) findViewById(R.id.etTitle);
EditText movieGross = (EditText) findViewById(R.id.etGross);
EditText movieDate = (EditText) findViewById(R.id.etDate);
String title = movieTitle.getText().toString();
String gross = movieGross.getText().toString();
String date = movieDate.getText().toString();
if ((title.length() > 0) && (gross.length() > 0)
&& (date.length() == 4)) {
Intent hobby = getIntent();
hobby.putExtra(Lab9_082588Edit.TITLE_STRING, title);
hobby.putExtra(Lab9_082588Edit.GROSS_STRING, gross);
hobby.putExtra(Lab9_082588Edit.DATE_STRING, date);
setResult(RESULT_OK, hobby);
finish();
}
}
Delete function:
int posDelete = info.position;
String deleteTitle = results.get(
info.position).getTitle();
results.remove(posDelete);
adapter.notifyDataSetChanged();
Index<Lab9_082588FetchDetails> rootDelete = (Index<Lab9_082588FetchDetails>) db
.getRoot();
rootDelete.remove(deleteTitle,
results.get(info.position));
db.setRoot(rootDelete); //Perst
return;
OnActivityResult (Edit):
case EDIT_MOVIE:
Lab9_082588FetchDetails edittedMovie = new Lab9_082588FetchDetails();
NumberFormat formatterEdit = new DecimalFormat("###,###,###");
edittedMovie.setTitle(data
.getStringExtra(Lab9_082588Add.TITLE_STRING));
edittedMovie.setGross("$"
+ formatterEdit.format(Double.parseDouble(data
.getStringExtra(Lab9_082588Add.GROSS_STRING))));
edittedMovie.setDate(data
.getStringExtra(Lab9_082588Add.DATE_STRING));
results.add(edittedMovie);
adapter.notifyDataSetChanged();
Populating the Listview:
for (int i = 0; i < items.size(); i++) {
Lab9_082588FetchDetails sr = new Lab9_082588FetchDetails();
sr.setTitle(items.get(i).getTitle());
sr.setGross(items.get(i).getGross());
sr.setDate(items.get(i).getDate());
results.add(sr);
Collections.sort(results, ignoreCaseStart);
}
How do I remedy this?
This problem occurs because in your delete function, you first remove the element from the results collection("results.remove(posDelete);"), and then, a few lines later, you call "results.get(info.position)" to fetch a parameter for the rootDelete.remove call, but which is already removed.
If the element is the last element of your collection, let's say the 50th element, the value for "info.position" is 50. You remove one element, so the number of elements is now 49. In the rootDelete.remove line you call results.get(50), which produces the error.
I followed this guide http://www.vogella.de/articles/AndroidSQLite/article.html and altered the table and code to handle additional fields. But when the list is displayed it only displays the Item field and not the price. I can't find where in the code it does this.
Here is the code for the loading of items into the adapter, the getAllItems returns and array of items. Item has id, item and price.
List<Item> values = datasource.getAllItems();
// Use the SimpleCursorAdapter to show the
// elements in a ListView
ArrayAdapter<Item> adapter = new ArrayAdapter<Item>(this,
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
Here is the code behind that :
public List<Item> getAllItems() {
List<Item> items = new ArrayList<Item>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_ITEMS,
null, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Item item = cursorToItem(cursor);
items.add(item);
cursor.moveToNext();
}
// Make sure to close the cursor
cursor.close();
return items;
}
private Item cursorToItem(Cursor cursor) {
Item item = new Item();
item.setId(cursor.getLong(0));
item.setItem(cursor.getString(1));
item.setPrice(cursor.getString(2));
return item;
}
It appears 'values' is only Item.items and not price and ID but I don't see why?
Without the whole private Item cursorToItem stuff, how about adding
while (!cursor.isAfterLast()) {
items.add(cursor.getLong(0) + " " + cursor.getString(1) + " " + cursor.getString(1));
cursor.moveToNext();
}
If you want to have more objects in a row, your task is much bigger. I suggest you check this link and implement Pankaj's code. I have been using it for a while and it works like a charm. However, it took me a while to understand.
my code here is horribly wrong, and i'm not sure how you would properly do this. i have a Spinner which is populated from a SQLite database query through a CursorAdapter. i need to get the text (value) of the currently selected item. i tried this garbage:
((Cursor)prdSpn.getItemAtPosition(prdSpn.getSelectedItemPosition())).getString(prdSpn.getSelectedItemPosition())
to get the text, but it crashes every time. what's the proper way to do this? here's some additional code that may be relevant:
/// qc defined above as a SimpleCursorAdapter
/////////setup product selection spinner from db
prdSpn = (Spinner)findViewById(R.id.prd_spn);
Cursor prdCur = null;
try {
prdCur = mDb.query(smsDbSchema.ProductSchema.TABLE_NAME, null, null, null, null, null, null);
} catch(Exception e) {
Log.e("smsdb", e.toString());
}
prdCur.moveToFirst();
startManagingCursor(prdCur);
qc = new SimpleCursorAdapter(
this,
android.R.layout.simple_spinner_item,
prdCur,
new String[] {smsDbSchema.ProductSchema.COLUMN_NAME},
new int[] {android.R.id.text1}
);
qc.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
prdSpn.setAdapter(qc);
Code similar to the following works for me...
Cursor theCursor = qc.getCursor();
String theString = theCursor.getString(theCursor.getColumnIndex(<your column name here>));
EDIT by moonlightcheese:
implementation:
Cursor theCursor = (Cursor)prdSpn.getSelectedItem();
Log.e("spnERRtest", "Item: " + theCursor.getString(theCursor.getColumnIndex(smsDbSchema.ProductSchema.COLUMN_NAME)));
//theCursor.getString(theCursor.getColumnIndex(smsDbSchema.ProductSchema.COLUMN_NAME)).contains("CAR")
((Cursor)prdSpn.getItemAtPosition(prdSpn.getSelectedItemPosition())).getString(prdSpn.getSelectedItemPosition())
I'm unclear why you are passing getSelectedItemPosition() to getString(). Shouldn't you pass the column number of the column that has the data you want? Isn't this column unrelated to the row that was selected in the spinner?