Why can't get the selected item in the filtered list of AutoCompleteTextField? - codenameone

I define a DefaultListModel in an AutoCompleteTextField.
DefaultListModel<String> options = new DefaultListModel<>();
AutoCompleteTextField labelACField = new AutoCompleteTextField(options){
#Override
protected boolean filter(String text) {.......
labelACField.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
if (filteredIdObjs!=null){
selectedIdx = options.getSelectedIndex();
selectedIdObj = filteredIdObjs[selectedIdx];
oidx = selectedIdObj.getId();
}
}
});
A User key in 'ss' in labelACField that show a list with 4 items.
The user selects the 3rd item - DS Drive shake Inc. but options.getSelectedIndex() always return 0. How do I get the user-selected item(the 3rd item)?

Related

I can not update an item list in the database room and add the item to the favorites list

I can not set an isfavorites value by clicking Add to Favorites .
Android Studio displays a null pointer exception for ringTonesDao .
I do not know how to fix this error.
On the other hand, because ringTonesDao is an interface, if I set its value to new RingTonesDao, I have to set all its functions.
this is RingTonesAdapter
//Imports and Package name
public class RingTonesAdapter extends
RecyclerView.Adapter<RingTonesAdapter.ringTonesViewHolder> {
private List<RingTones> ringTonesList;
RingTonesDao ringTonesDao; // <--This is null in logcat
public RingTonesAdapter(List<RingTones> ringTonesList) {
this.ringTonesList = ringTonesList;
}
#NonNull
#Override
public ringTonesViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.actv_main_list,
parent, false);
return new ringTonesViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ringTonesViewHolder holder, int position) {
//Set RingTone name to TextView
//Set RingTone Btn
//Set Alarm Btn
//Set Notification Btn
//Add To Favorites Btn
if (ringTonesList.get(position).isFavorite()) {
holder.btn_addToFavorites.setImageResource(R.drawable.ic_favorites);
} else {
holder.btn_addToFavorites.setImageResource(R.drawable.ic_addtofavorites);
}
holder.btn_addToFavorites.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
Long id = ringTonesList.get(position).getId();
ringTonesDao.update(true,id);
}catch (NullPointerException e){
Toast.makeText(v.getContext(),"Null Pointer
Exception",Toast.LENGTH_LONG).show();
}
}
});
//Set Play Btn
//ringTonesViewHolder and count items
and this is RingTonesDao
//import and package
#Dao
public interface RingTonesDao {
#Insert
Long add(RingTones ringTones);
#Delete
int delete(RingTones ringTones);
#Query("SELECT * FROM tbl_ringtones")
List<RingTones> getRingTones();
#Query("SELECT * FROM tbl_ringtones WHERE favorites>0 ")
List<RingTones> favorites();
#Query("DELETE FROM tbl_ringtones")
void deleteAll();
#Query("UPDATE tbl_ringtones SET favorites=:favorites WHERE id=:id")
int update (Boolean favorites ,Long id);
}
You need to do something like this
DatabaseClient.getInstance(v.getContext()).getAppDatabase()
.RingTonesDao()
.update(true,id);
read more how to use Rom database : from this example
also there is a difference between Boolean and boolean in Java,
in your case try to use `boolean` instead `Boolean` in your update function.

Make cursor corresponding array with multiple rows followed by same row id's

I have a DB in which id's are change after few rows, then same I'd in some rows then change I'd. What I want that, the same I'd values will be populated listview's in one line, then when the Ids are same, they are all in one row. And thus the next rows populate with same rows which have same ID's.
My DB columns and rows are as follows:
Verse_id -------words_id----------words_ar------ translate_bn--
1-----------------------1---------------Mamun-----------Assistant---
1-----------------------2--------------- Salam------------Operator------
1-----------------------3---------------John--------------Assistant------
2 ----------------------1--------------- Smith-------------Manager------
2-----------------------2---------------Roger--------------Director--------
3-----------------------1---------------Qoel---------------Helper----------
3-----------------------2---------------Saki---------------Mechanics-----
3-----------------------3----------------Ali-----------------Getman----------
I want this DB in three lines, as follows : (listview):
1. Mamun. Salam John
Assistant. Operator. Assistant
------------------------------------------------------------------
2. Smith. Roger.
Manager. Director
------------------------------------------------------------------
3. Qoel. Saki. Ali.
Helper. Mechanics. Getman
I have Tried in Two way :
First :
private static final String PRIMARY_ID = "_id";
private static final String TABLE_NAME = "bywords";
private static final String FRIEND_ID = "verse_id";
private static final String WORDS_ID = "words_id";
private static final String WORDS_bN = "translate_bn";
private static final String WORDS_AR = "words_ar";
private SQLiteDatabase database;
private ArrayList<String> friends;
private ArrayList<String> trans1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
mContext = this;
ExternalDbOpenHelper dbOpenHelper = new ExternalDbOpenHelper(this, DB_NAME);
database = dbOpenHelper.openDataBase();
Cursor cursor = database.rawQuery("SELECT * FROM bywords", null);
ListView list4=(ListView)findViewById(R.id.list4) ;
String[] from = {WORDS_AR }; // _id mandatory
int[] to = new int[]{R.id.alquran_text};
CursorAdapter adapter = new SimpleCursorAdapter(
mContext,
R.layout.list_item,
cursor,
from,
to,
CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
list4.setAdapter(adapter);
And Then Second :
trans1 = new ArrayList<String>();
String[] allColumns2 = new String[] { FRIEND_ID,
BN_TRANS };
Cursor friendCursor2 = database.query(TABLE_NAME, allColumns2, null,
null, null, null, null);
if (friendCursor2 != null) {
friendCursor2.moveToFirst();
}
//return friendCursor;
if(!friendCursor2.isAfterLast()) {
do {
String name = friendCursor2.getString(1);
trans1.add(name);
} while (friendCursor2.moveToNext());
}
friendCursor2.close();
String [] bntrans1= new String[trans1.size()];
bntrans1 = trans1.toArray(bntrans1);
ListAdapter adapter = new ArrayAdapter<String>(
getApplicationContext(), R.layout.alert_row, seleted_route) {
ViewHolder holder;
Drawable icon;
class ViewHolder {
ImageView icon;
TextView title;
TextView title2;
}
public View getView(int position, View convertView,
ViewGroup parent) {
final LayoutInflater inflater = (LayoutInflater) getApplicationContext()
.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(
R.layout.alert_row, null);
holder = new ViewHolder();
//holder.icon = (ImageView) convertView
// .findViewById(R.id.icon4);
holder.title = (TextView) convertView
.findViewById(R.id.title4);
holder.title2 = (TextView) convertView
.findViewById(R.id.title2);
convertView.setTag(holder);
} else {
// view already defined, retrieve view holder
holder = (ViewHolder) convertView.getTag();
}
Drawable drawable = getResources().getDrawable(R.drawable.iqra1); //this is an image from the drawables folder
holder.title.setText(seleted_route[position]);
holder.title2.setText(seleted_route[position]);
//holder.icon.setImageDrawable(drawable);
return convertView;
}
};
By the second way I can populate two column in two text view in one rows. But what I want that the corresponding rows with same id of rows must populate in one line of listview with verse I'd. The id's whataver are same in rows may be 5, 10 or twenty rows same id. Whenever the same Id They are one line, When the Id change the newline begins.

to display the data obtained from button listener to list- codename one

I have a button that display the data obtained from json. below is my code for button action. I need help to display the data obtained to list.
#Override
protected void onMain_ButtonAction(final Component c, ActionEvent event) {
ConnectionRequest r = new ConnectionRequest() {
Hashtable h;
#Override
protected void postResponse() {
}
#Override
protected void readResponse(InputStream input) throws IOException {
InputStreamReader reader = new InputStreamReader(input);
JSONParser p = new JSONParser();
h = p.parse(new InputStreamReader(input));
Hashtable response = p.parse(reader);
Hashtable feed = (Hashtable)response.get("root");
for (Object s : h.values()) {
Vector vec = new Vector(100);
vec = (Vector)s;
int i;
for(i = 0; i<vec.size(); i++){
Hashtable<String, String> ht= (Hashtable<String, String>) vec.get(i);
System.out.println(ht.get("location"));
// findLabel().setText(ht.get("location"));
}
}
}
};
r.setUrl("http://ruslanapp.demo.capitaleyenepal.com/vodka-mobile-interface/getData/locations");
r.setPost(false);
InfiniteProgress prog = new InfiniteProgress();
Dialog dlg = prog.showInifiniteBlocking();
r.setDisposeOnCompletion(dlg);
NetworkManager.getInstance().addToQueue(r);
}
I want to list the data obtained frm btn above to the list below. how can I do it??
#Override
protected boolean initListModelList1(List cmp) {
cmp.setModel(new com.codename1.ui.list.DefaultListModel(new String[] {"Item 1", "Item 2", "Item 3"}));
return true;
}
You did most of the work well, I suggest avoiding a list and using an infinite container. The PropertyCross demo has pretty much this functionality (including JSON): https://www.udemy.com/learn-mobile-programming-by-example-with-codename-one/
To finish the code above create the model ArrayList above e.g. assuming you are using a MultiList:
// define this in the class variables:
private ArrayList<Map<String, String>> modelData = new ArrayList<Map<String, String>>();
// then in the code (I assumed stuff about your JSON, correct the
// code to extract the data correctly, just set the hashmap values
for (Object s : h.values()) {
Collection<Map<String, String>>) data = (Collection<Map<String, String>>))s;
for(Map<String, String> ht : data) {
String location = ht.get("location");
HashMap<String, String> entry = new HashMap<String, String>();
entry.put("Line1", location);
modelData.add(entry);
}
}
Then in:
#Override
protected boolean initListModelList1(List cmp) {
cmp.setModel(new DefaultListModel(modelData));
return true;
}
Notice that you should use showForm() to show the next form in the postResponse method.

JavaFX 8: ComboBox button cell update behavior

I have a combo box which contains items of type Dog. If all items are replaced with new ones (via setAll on the ObservableList model) , the item renderer can cope with this update, while the button cell renderer cannot:
Here's a minimal example to reproduce the problem (full source incl. imports on GitHub):
public class ComboBoxRefresh extends Application {
private static final class Dog {
private final String name;
public Dog(String name) {
this.name = name;
}
}
private static final class DogListCell extends ListCell<Dog> {
#Override
public void updateItem(Dog item, boolean empty) {
super.updateItem(item, empty);
if (item == null || empty) {
setText("");
} else {
setText(item.name);
}
}
}
private static List<Dog> createThreeDogs() {
return range(0, 3).mapToObj(i -> new Dog("Buddy " + i)).collect(toList());
}
#Override
public void start(Stage stage) throws Exception {
ObservableList<Dog> items = observableArrayList(createThreeDogs());
ComboBox<Dog> comboBox = new ComboBox<>(items);
comboBox.setPrefWidth(400);
comboBox.setCellFactory(listView -> new DogListCell());
comboBox.setButtonCell(new DogListCell());
Button button = new Button("Refresh");
button.setOnAction(event -> {
List<Dog> newItems = createThreeDogs();
items.setAll(newItems);
});
VBox box = new VBox(10, comboBox, button);
box.setPadding(new Insets(10));
Scene scene = new Scene(box);
stage.setScene(scene);
stage.show();
}
}
If I add an equals implementation to the Dog class, everything works, but this is not an option in my real application.
Are there any work-arounds to enforce a proper refresh of the button cell?
It seems to be a bug. Workaround could be
button.setOnAction( event -> {
List<Dog> newItems = createThreeDogs();
items.clear();
items.addAll(newItems);
} );

Update listview with custom adapter and database handler

I can't update listview with custom adapter and database handler.
Items are updated in the database handler, but listview is updated only when I leave the fragment and come back. I would like to see changes just after adding new item.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.shopping_list_fragment_layout, container, false);
super.onCreate(savedInstanceState);
//// adding an item to itemList
nameTxt = (EditText) view.findViewById(R.id.txtItem);
couponsAmount = 3;
dbHandler = new ShoppingListDatabaseHandler(getActivity());
itemListView = (ListView) view.findViewById(R.id.listViewShoppingItems);
final ShoppingListListAdapter itemAdapter = new ShoppingListListAdapter(getActivity(), ITEMS_DATA);
final ImageButton addBtn = (ImageButton) view.findViewById(R.id.btnAddItem);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view){
ShoppingListItem item = new ShoppingListItem(dbHandler.getItemsCount(), String.valueOf(nameTxt.getText()), 3);
if (!itemExists(item)) {
dbHandler.createItem(item);
//getListView().invalidateViews();
itemAdapter.notifyDataSetChanged(); // TODO: is not updating
Toast.makeText(getActivity(), String.valueOf(nameTxt.getText()) + " has been added", Toast.LENGTH_SHORT).show();
nameTxt.setText("");
return;
}
Toast.makeText(getActivity(), String.valueOf(nameTxt.getText()) + " already exists", Toast.LENGTH_SHORT).show();
nameTxt.setText("");
}
});
if (dbHandler.getItemsCount() != 0){
ITEMS_DATA.addAll(dbHandler.getAllItems());
}
//itemListView.getListView().invalidateViews();
//itemAdapter.notifyDataSetChanged();
itemListView.setAdapter(itemAdapter);
return view;
}
and my adapter:
public class ShoppingListListAdapter extends BaseAdapter {
private Context context;
private final List<ShoppingListItem> Items; // = new ArrayList<ShoppingListItem>();
//Constructor to initialize values
public ShoppingListListAdapter(Context context, List<ShoppingListItem> Items) {
this.context = context;
this.Items = Items;
}
#Override
public int getCount() {
// Number of times getView method call depends upon
return Items.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
// Number of times getView method call depends upon
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
if (convertView == null) {
gridView = new View(context);
gridView = inflater.inflate(R.layout.shopping_list_list_item, null);
ShoppingListItem currentItem = Items.get(position);
TextView itemNameTxt = (TextView) gridView.findViewById(R.id.itemName);
itemNameTxt.setText(currentItem.getName());
TextView couponsAmount = (TextView) gridView.findViewById(R.id.couponsAmount);
couponsAmount.setText("-" + currentItem.getCouponsAmount().toString());
}
else {
gridView = (View) convertView;
}
return gridView;
}
}
I tried:
- getListView().invalidateViews();
- adapter.notifyDataSetChanged();
But probably I do sth wrongly, because it is not helping me.
Can you look at my code?
You have added the item to your database, but not to the list used to create the adapter.
ITEM_DATA.add(item):
itemAdapter.notifyDataSetChanged();

Resources